Java: superclass and subclass

  • Is it possible to distinguish a subclass variable from any of its superclasses?
  • Can any subclass variable be assigned to a superclass variable?
  • Is it possible to assign any variable to a superclass?
  • If so, can an interface variable be assigned from any implementation class?
+1
source share
5 answers

Are all dogs animals too?

Are all animals also dogs?

If you need an animal and I give you a dog, is that always acceptable?

If you need a dog specifically, but I give you some kind of animal, can this be problematic?

If you need something that you can drive, but you don't care what it is, as long as it has methods like: Acceleration and .Steer, do you care if it is a Porsche or an ambulance?

+10
source
  • Yes
  • You can assign an instance of a subclass to a superclass variable
  • A?
  • You can assign an instance of a class to a variable of any type of interface that the class implements
+7
source

Just for clarity, consider:

class A extends B implements C { } 

Where A is a subclass, B is a superclass, and C is the interface implemented by A

  • A subclass can be transferred to any superclass.

     B b = new A(); 
  • A superclass cannot be carried down to any subclass (this is unreasonable because subclasses may have capabilities that are not in the superclass). You can not:

     A a = new B(); // invalid! 
  • A superclass can be assigned any variable of the corresponding type.

     A q = new A(); // sure, any variable q or otherwise... 
  • A class can be assigned to a variable of the type of one of the implemented interfaces.

     C c = new A(); 
+3
source

Can a subclass variable be added to any of its superclasses?

Yes

And can a subclass variable be assigned to a superclass variable?

Yes

Is it possible to assign a superclass to a class variable?

Yes

If so, can an interface variable be assigned to a variable from any implementing class?

Yes

0
source

Yes, usually the basic idea is polymorphism .

Say you have some shapes: circle, square, triangle. You will have:

 class Shape { ... } class Circle extends Shape { ... } class Square extends Shape { ... } class Triangle extends Shape { ... } 

The idea of โ€‹โ€‹inheritance is that a circle is a form. So you can do:

 Shape x = ...; Point p = x.getCenterPosition(); 

You do not need to worry about which particular type the x variable has.

0
source

All Articles