[Solved] Inheritance. casting and polymorphism in java [closed]


I’m goign to take a shot at it because I recently tried to understand those and this is a good way to see if I did 🙂 because If you can’t explain something you haven’t really understood it 🙂

Casting is fairly simple. It means to pretty much convert a value or object of a certain type to a different type. This way you can for example turn a float into an integer

float y = 7.0
int x = (int) y

x will now be 7.
Of course you can’t simply cast any type to any other type. There are limitations which you should search for on google – i could never cover all of them.

Polymorphism sounds similar but is actually something else. As I understand it it means that certain objects can be of multiple types. For example of you have a class that extends another class any instance of the parent class can also be of the type of the derived class.

class Base {...} 
class Derived extends Base {...} 

Base obj1 = new Base();
Derived obj2 = new Derived();

obj1 = obj2;

Over the course of this snippet obj1 will have been an instance of Base first but then it will be an instance of Derived which is a class derived from base. This is possible because instances of derived classes contain an “inner object” (i don’t know the official name) of the base class. When you cast the Base instance to an instance of Derived you will actually get this “inner object”

Hope this helps

solved Inheritance. casting and polymorphism in java [closed]