• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

marcus green mock #3 q.57

 
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

answer is 4. The object is Agg() but why is it looking for getField method in Base?
 
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Maria,
it is not possible in Java to invoke a method on a variable whose (declared/compile) type has not declared or inherited that method. This is why Java is a type safe language. Every expression has a type, and you can invoke only the methods corresponding to this type: you cannot treat an object as it were of another (unrelated) type.
Base a = new Agg();
the declared/compile type of the variable a is Base. However the type of the object pointed by a is Agg.

1) System.out.println(a.getFields());
Error. Base did not declared or inherited getFields
2) System.out.println(a.name);
Error. The same as above.
3) System.out.println((Base) a.getFields());
Error. The cast does not apply to a, but to the return of a.getFields. Thus error because of 1)
4) System.out.println( ((Agg) a).getFields());
OK. The declared/compile type of a is Agg. This is what the cast carries out. Now in the class Agg the invoked method is declared, that makes the compiler happy.
 
Maria Garcia
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Jose.
 
Slideshow boring ... losing consciousness ... just gonna take a quick nap on this tiny ad ...
Clean our rivers and oceans from home
https://www.kickstarter.com/projects/paulwheaton/willow-feeders
reply
    Bookmark Topic Watch Topic
  • New Topic