A question about chapter 7

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
Jix
Posts: 14
Joined: Thu May 31, 2012 7:57 pm
Contact:

A question about chapter 7

Post 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?

admin
Site Admin
Posts: 10384
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: A question about chapter 7

Post 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.

Jix
Posts: 14
Joined: Thu May 31, 2012 7:57 pm
Contact:

Re: A question about chapter 7

Post by Jix »

Ok thanks

Post Reply

Who is online

Users browsing this forum: No registered users and 14 guests