Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using superclass to initialise a subclass object java [duplicate]

Tags:

SuperClass object = new SubClass(); 

Why use a superclass to instantiate a subclass object like above? Because the only way i learnt to instantiate an object is to:

SubClass object = new SubClass(); 

I'm learning java.

like image 946
user1050548 Avatar asked Apr 16 '12 15:04

user1050548


People also ask

Can a subclass be instantiated as a superclass?

If a superclass is defined in a path of the inheritance tree using the addition CREATE PRIVATE, outside consumers cannot instantiate a subclass, and a subclass cannot even instantiate itself, because it has no access to the instance constructor of the superclass.

Can a superclass object reference a subclass object?

Yes, the super class reference variable can hold the sub class object actually, it is widening in case of objects (Conversion of lower datatype to a higher datatype).

What happens when a sub class object is assigned to a super class object reference?

Therefore, if you assign an object of the subclass to the reference variable of the superclass then the subclass object is converted into the type of superclass and this process is termed as widening (in terms of references).

What happens if superclass and subclass having same field name?

When declaring a variable in a subclass with the same name as in the superclass, you are hiding the variable, unlike methods which are overwritten.


2 Answers

You may have a method that only takes an instance of SuperClass. Since SubClass is a SuperClass, you can use an instance of SubClass and treat it as SuperClass.

The same behavior is used when working with interfaces:

List someList = new ArrayList(); 

That's the beauty of polymorphism. It allows you to change out the implementation of the class' internals without breaking the rest of your code.

like image 66
Justin Niessner Avatar answered Oct 25 '22 01:10

Justin Niessner


This is known as polymorphism. Imagine the following example:

Musician musician = new Pianist();  

or

Musician musician = new Drummer();  

Suppose Musician class has a method: play(). It doesn't matter who the musician is, if you call play method, you'll know how to play the determined instrument, base on concrete class, on this case, no matter if Pianist or Drummer.

Each concrete class, overwriting its play() method, can play on your own:

e.g. for Pianist class: play() { playsBeethoven(); }

For detailed information, please check http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html

It's always good to remember to use it with inheritance http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

like image 20
axcdnt Avatar answered Oct 25 '22 01:10

axcdnt