Please help me understand how inheritance works in the context of working with abstract classes and their heirs, calling methods and constructors of both, and analyzing a concrete example with me.
There is an abstract class Animal in the example, and its descendant Monkey .
abstract public class Animal { public int nLegs = 0; public void numLegs(int nLegs) { this.nLegs = nLegs; } public abstract int getLegs(); //Constructor public Animal (int nLegs) { numLegs(nLegs) } } public class Monkey extends Animals { public int getLegs(){ return this.nLegs; } public monkey(){ super(2); } public void saySome(){ System.out.println("Hello, I am a monkey!"); } } In Animal, there is a переменная nLegs (number of legs), метод numLegs that sets the value of this variable, a геттер getLegs to get its value, and a конструктор that sets the value of the переменной nLegs using метода numLegs .
In Monkey, we реализуем геттер (an abstract method must be implemented), создаем конструктор that calls конструктор Animal , assigning the value 2 to its local variable, and also write an additional метод saySome , that outputs a string to the console.
Is that right? Then we go further:
In the main class we write:
public class MainClass{ public static void main(String []args){ Animal jay = new Monkey (); System.out.println(jay.nLegs); /* jay.saySome()*/ ((Monkey) jay).saySome(); } } Questions:
What does such an expression mean when creating a jay object? jay cannot belong to an abstractive class, he knows Monkey , but then how to read the logic of this expression (now I'm reading
Animal jay = new Monkey ();as aКласса Animal объект jay = новый объект jay класса MonkeyWhy
jay.saySome()method,jay.saySome()I comment on, does not work? Why does((Monkey) jay).saySome();?