Pezze Pezze - 5 months ago 8
Java Question

Instance of a class inheritance

I am currently studying java. I have a question about inheritance.
I am aware you can inherit the variables of the parent class using:

public class ChildClass extends ParentClass{
}


However, i wanted to do somethin like inheriting the variables and the values assigned to them from an instance of the ParentClass. Example: i have a class Animal and a class Dog extending from Animal. The class animal has:

private int number_of_legs;
private int number_of_eyes;


At this point i create a new instance of the class animal:

Animal first_animal = new Animal(4,2);
/*where 4 and 2 are the number of legs and eyes which
*i attribute through a constructor present in Animal.
*/


Now i want to create a new instance of the class Dog which inherits the values from the instance of the class Animal i just created (first_animal).

Dog first_dog = new ??? // i tried with ...new first_animal.Dog but it didn't work.


Can anyone help me? Thanks for your time.

Answer

This will do:

Dog dog = new Dog(4, 2);

You cannot create an instance of a subclass as an instance of a super class. You can say that all Dogs are Animals, but not that all Animals are Dogs.

Note that the statement above means:

//valid and accepted because one kind of instance of animal is a dog
Animal dog = new Dog(4, 2);
//invalid and throws a compiler error because one kind of instance of a Dog cannot be any animal
Dog anotherDog = new Animal(4, 2);

new Animal.Dog is wrong here because it means that you have a static class Dog inside Animal class. new first_animal.Dog is wrong here because it means that you have an inner class Dog inside Animal class. Those are different topics you should not cover yet.