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?
A question about chapter 7
Moderator: admin
-
- Site Admin
- Posts: 10384
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: A question about chapter 7
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();
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.
In the following case, your code is less coupled to the implementation classes car and scooter.
So, it is always a preferred approach to use as generic reference as possible. For example:
Instead ofyou should use
as much as possible.
HTH,
Paul.
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();
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.
Code: Select all
Automoble x = new Car();
x.drive();
Automoble x = new Scooter();
x.drive();
Instead of
Code: Select all
ArrayList l = new ArrayList();
Code: Select all
List l = new ArrayList();
HTH,
Paul.
-
- Posts: 14
- Joined: Thu May 31, 2012 7:57 pm
- Contact:
Re: A question about chapter 7
Ok thanks
Who is online
Users browsing this forum: No registered users and 14 guests