This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Assigning a subclass to a superclass type Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Assigning a subclass to a superclass type" Watch "Assigning a subclass to a superclass type" New topic
Author

Assigning a subclass to a superclass type

Ajushi Jones
Greenhorn

Joined: Dec 11, 2007
Posts: 25
I saw some code with this:



so when I do:



I'm calling the add() method of List and not from ArrayList right?
What are the advantages of using this?
Also, why do they do this if you can't use the specific methods of let's say ArrayList? I'm confused.

Thanks in advance!
[ January 01, 2009: Message edited by: Ajushi Jones ]
Darryl Burke
Bartender

Joined: May 03, 2008
Posts: 4523
    
    5

You're invoking the add(...) method on the object referenced by the variable brands. Instance methods are invoked on the instance referenced, static methods on the class named or, in case of bad coding, on the declared class of the variable.

The advantage of coding to the superclass, or in this case, the interface, is that changes in implementation details do not require changes elsewhere. This may be especially significant where the return value is declared to be of the super type: for example, a method declared to return java.util.List can return an ArrayList, AttributeList, LinkedList or any custom implementation of List. A change to this method that results in it returning a different implementation of List doesn't affect the public API and doens't require changes to the code using this method.


luck, db
There are no new questions, but there may be new answers.
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3817

Originally posted by Ajushi Lorenzo:

I'm calling the add() method of List and not from ArrayList right?
What are the advantages of using this?


It's bit different. You are allowed to call methods defined in List interface. But at the runtime actual implementation which is in the ArrayList class will run. This is what you called the polymorphism. You can use a superclass/interface type as the reference and can use an object of a subclass/any implementation class of the interface as the runtime object.


SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
Ajushi Jones
Greenhorn

Joined: Dec 11, 2007
Posts: 25
I'm getting it but not fully.
So you mean to say, at runtime I'm using ArrayList's add() method? What if I call a method that's not in the List interface, can I do that?

I get an ArrayList object with the type of List, is that correct?
kranthi adari
Greenhorn

Joined: Dec 29, 2008
Posts: 21
What if I call a method that's not in the List interface, can I do that?
answer)You cannot call a method that's is not in the List interface using a reference of List.

Run-time polymorphism applies only for overridden functions (i.e functions following proper overriding rule). Therefore it applies only for functions with same signature(ofcourse covariant return-type allowed with java 1.5) in the base and derived classes which is add() method in List and ArrayList in your case.


krad
Darryl Burke
Bartender

Joined: May 03, 2008
Posts: 4523
    
    5

You get a reference variable of type List that references an ArrayList object.

Definitely not recommended, but you can invoke methods specific to ArrayList after casting the reference to ArrayList. Omitting generics:

But if you find yourself having to do that, then it's probably more appropriate to code to the class and not the interface.
Ajushi Jones
Greenhorn

Joined: Dec 11, 2007
Posts: 25
Ahh I get it now! Thanks a lot guys!
Phone Myat Kyaw
Ranch Hand

Joined: Dec 26, 2008
Posts: 31
from my small tiny knowledge of Java as I'm also learning as a beginner to take SCJP 6.0 exam, this is called "Polymorphism".

You can do
SuperClass obj = [casting] sub();

With casting, you get new implemented features of subclasses(sub) though you actually created a super class object reference(obj). Without casting, you can use methods only implemented in its superclass (obj).

So, lets say -
Employee is a Superclass of SalariedEmployee and it has only two methods, setName() and getName() while the subclass SalariedEmployee has these two methods (setName() and getName()) plus two more methods (setSalary() and getSalary()).
If you want to call these two new added methods(setSalary() and getSalary()), you must do Casting. Otherwise, there will be no errors until you call the subclass's method.

If in case you wonder why it does so and why not in reverse,
Subclass sub = new Superclass(); << ERROR
because it's based on "is-a" relationship.

Every Salaried Employee "Is-A(n)" Employee , but
Every Employee "Is-not-A(n)" Salaried Emplyee (there might be hourly, weekly, or volunteered).
So, from the example, it's very safe to say that
Every Employee can use all methods of Salaried Employees (of course, if only with Casting) while all Salaried Employee cannot be ref obj of Employee.

To conclude,
A Superclass can call its subclasses' methods and instance variables if it's declared with Casting. But,
A Subclass ref obj cannot be used to ref to its superclass.

Hope this will clear(a bit if not so) on Polymorphism and Dynamic Binding (a little). Accept my apologies if there some parts I'm missing/completely wrong (I know it'll definitely as I'm also a beginner)

ps. forgive about my English
kranthi adari
Greenhorn

Joined: Dec 29, 2008
Posts: 21
The following stmt:
SuperClass obj = [casting] sub();

will never enable super class SuperClass reference(obj here) to get access to SubClass methods which were not overridden by the SubClass.

To know whether a function can be called on a reference, just refer to the type of the reference which is SuperClass here.

If the method is not present in ref-type, no matter you typecast or not, or to whatever derived class object reerence(obj here) is actually pointing to, the method cannot be called using the super-class ref(obj here).
kranthi adari
Greenhorn

Joined: Dec 29, 2008
Posts: 21
A Super-class reference can only access overriden methods from its derived class.
Gopinath Kothamasu
Greenhorn

Joined: Jul 16, 2009
Posts: 1
To make it more clear...
Using a superclass reference to a subclass instance makes the reference to access all the functionality of the super class whether you override them or not but you will miss the additional functinoality of the subclass for sure...(its a compile time error if you try to invoke the subclass specific functionality).

Using a subclass reference for a subclass instance you will get the functinality of both the super class as well as the subclass specific functionality.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38100
    
  22
Welcome to JavaRanch

Useful reply, but as it says here, the original poster is probably not reading any more .
 
jQuery in Action, 2nd edition
 
subject: Assigning a subclass to a superclass type
 
Similar Threads
arrayList.clear() VERSUS arrayList = new ArrayList()
I have doubt in a question in Generics(Q16) SCJP5 K&B book
Generics Wildcard Covariance
Generics - need help
WOW