A question about chapter 7
Posted: Thu May 31, 2012 8:04 pm
Hello, what's the point of appointing an object of a sub class to a reference of base class if i can't invoke the non-overriding sub class's methods?
for example, a question in ur question databank:
class Base{
void methodA(){
System.out.println("base - MethodA");
}
}
class Sub extends Base{
public void methodA(){
System.out.println("sub - MethodA");
}
public void methodB(){
System.out.println("sub - MethodB");
}
public static void main(String args[]){
Base b=new Sub(); //1
b.methodA(); //2
b.methodB(); //3
}
}
line 3 will cause compile time error, I understand why this error occurred but my question is:
Why should I appoint an object of sub to a base reference if I can't invoke sub's non-overriding methods then? I mean is there any advantage to appoint a sub object to a base reference?
for example, a question in ur question databank:
class Base{
void methodA(){
System.out.println("base - MethodA");
}
}
class Sub extends Base{
public void methodA(){
System.out.println("sub - MethodA");
}
public void methodB(){
System.out.println("sub - MethodB");
}
public static void main(String args[]){
Base b=new Sub(); //1
b.methodA(); //2
b.methodB(); //3
}
}
line 3 will cause compile time error, I understand why this error occurred but my question is:
Why should I appoint an object of sub to a base reference if I can't invoke sub's non-overriding methods then? I mean is there any advantage to appoint a sub object to a base reference?