简体   繁体   中英

Subclass reference to Superclass Object

What is use of creating Subclass reference to Superclass Object

class A { /* ... */ }

class B extends A { /* ... */ }

public class Sample {
    public static void main(String a[]){
        A a = new B();
    }
}

One reason is so you can call methods that appear in the subclass that do not appear in/override the methods of the superclass.

eg

Class A (Vehicle) ~ superclass

Class B (Car) ~ subclass

Vehicle has a method called getTopSpeed() , which can be called on any Vehicle. Car has a method called getTaxDiscExpiry() , which only makes sense for Cars but not for other vehicles such as Boats.

Do you mean creating a "superclass reference to a subclass object?" This question would seem to make more sense (and is what the code is doing) since you actually do (or potentially could) lose some functionality because of methods that aren't available in the superclass.

If so, it's because of abstraction - if you have lots of cars and you want them to drive() , you just need to treat them as cars. You don't need to find out and downcast to what type of car they are so you have additional methods available (might be massage() on some cars for instance.) Sure, downcasting in this case would get you more methods to play with but that's just unnecessary complexity that you're not going to use.

It's also a common supertype - if you were iterating over a list of saabs, vauxhalls and fords you can put them all in a List<Car> and iterate over them as Cars .

At a top level you could just have a Drivable interface and reference all the cars with that. That way you could have anything that drives in the list example above - car or not - and you'd never need to know any more details than you had to, as well as broadening the scope to everything that drives, not just cars.)

Its of no use in the code you have. but there will be Situations where in

many classes are extending single class

and a method some where in other class is called by both of these classes at that time

its arguement type should be of its Super class type for Object Oriented programming to come handy...

in one word its all for PolyMorphism .. assume condition like below

Class A
{
void f1(Super s){

}
}

class B extends Super
{

void f2(){
new A().f1(new B())
}
}

class A extends Super
{

void f2(){
new A().f1(new A())
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM