[about inheritance]...
posted 24 years ago
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
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
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
posted 24 years ago
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
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).]
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).]
posted 24 years ago
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
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
HTH
--Farooq
Muhammad Farooq<br />Sun Certified Programmer for Java 2 Platform<br />Oracle8i Certified Professional Database Administrator
| 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 |









