Win a copy of Building Blockchain Apps this week in the Cloud/Virtualization forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Liutauras Vilda
  • Knute Snortum
  • Bear Bibeault
Sheriffs:
  • Devaka Cooray
  • Jeanne Boyarsky
  • Junilu Lacar
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • salvin francis
Bartenders:
  • Tim Holloway
  • Piet Souris
  • Frits Walraven

Question from Mock Exam #3 by Marcus Green.

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Base {}
class Agg extends Base{
public String getFields(){
String name = "Agg";
return name;
}
}

public class Avf{
public static void main(String argv[]){
Base a = new Agg();
//Here
}
}
What code placed after the comment //Here will result in calling the getFields method resulting in the output of the string "Agg"?
Answer: System.out.println( ((Agg) a).getField());
I thought the answer would be:
System.out.println(a.getFields());
I do not understand why we need to downcast. Is not that the case that methods are being invoked based on the underlying object, in this case it is Agg. Or does it have anything to do with the fact that getFields() is not an overriding method because Base does not have it? And in this case if Base would have getFields() and it would be overridden in Agg, then we would not need a downcast?
 
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Originally posted by Anna Swartz:
...Is not that the case that methods are being invoked based on the underlying object, in this case it is Agg. Or does it have anything to do with the fact that getFields() is not an overriding method because Base does not have it? And in this case if Base would have getFields() and it would be overridden in Agg, then we would not need a downcast?


Static methods are invoked based on the reference type at compile time. Instance methods are invoked on the underlying object at run time. However, a compiler error is generated if the reference type does not declare the method that you are trying to invoke.
 
Anna Swartz
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks much Don, it is clear to me now!
 
Oh. Hi guys! Look at this tiny ad:
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!