Page 1 of 1

A question about chapter 7

Posted: Thu May 31, 2012 8:04 pm
by Jix
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?

Re: A question about chapter 7

Posted: Fri Jun 01, 2012 12:50 pm
by admin
The reason why someone may assign a sub class object to a base class reference is to make sure that his code is not tied to a specified subclass of that base class.

For example, consider two classes: Car extends Automobile and say Class has an extra method changeGear();

Code: Select all

Car x = new Car();
x.drive();
x.changeGear(); 
By assigning car object to Automobile reference, the coder ensures that he does not inadvertantly use any method that is specific to the subclass. The benefit is clear when you have to change the object.

Code: Select all

Car x = new Scooter();
x.drive(); //No need to change
x.changeGear(); //will not work. Therefore, your code is tied to Car implementation.
In the following case, your code is less coupled to the implementation classes car and scooter.

Code: Select all

Automoble x = new Car();
x.drive();

Automoble x = new Scooter();
x.drive();
So, it is always a preferred approach to use as generic reference as possible. For example:
Instead of

Code: Select all

ArrayList l = new ArrayList(); 
you should use

Code: Select all

List l = new ArrayList();
as much as possible.

HTH,
Paul.

Re: A question about chapter 7

Posted: Fri Jun 01, 2012 4:06 pm
by Jix
Ok thanks