• 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:
  • Devaka Cooray
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Saloon Keepers:
  • Tim Holloway
Bartenders:

[about inheritance]...

 
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class Base {}
class Sub extends Base{
public String getFields(){
String name = "Sub";
return name;
}
}
public class Avf{
public static void main(String argv[]){
Base a = new Sub();
System.out.println(a.getFields());
}
}
We know the instance "a" will invoke the method in class Sub,
the variable in class Base.
But the code above will compile error,error message is
there are no getField() method in class Base,
why??we only need the method in class Sub,
why compile error??
---------------------------
thanks for help,Liao
 
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You have declared variable "a" as type "Base". Even though the object is of type "Sub", Java is looking at it like it is a "Base", which does not have a "getFields" method. So the compiler complains.
In order for inheritance to work, the base class must include the method to be overriden (or the "Sub" class could implement an interface that includes the method...).
[This message has been edited by Guy Reynolds (edited August 17, 2001).]
 
Ranch Hand
Posts: 356
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Liao, as the "a" is of type Base, the method of the Base class will be called, if the method in the Base class is present, it will be called, and if that method is overriden in the sub class then the method(overriden) from the sub class will be called ( and if the method in the Base is either static or private it will be called, as they can't be overriden)
HTH
--Farooq
 
Drove my Chevy to the levee but the levee was dry. A wrung this tiny ad and it was still dry.
The new gardening playing cards kickstarter is now live!
https://www.kickstarter.com/projects/paulwheaton/garden-cards
reply
    Bookmark Topic Watch Topic
  • New Topic