Answer the question
In order to leave comments, you need to log in
Why don't descendants have methods?
I am a beginner and for some the question may seem too simple, but I still decided to ask it without solving it.
public class Figure {
public String getName() {
return "Figure";
}
}
public class Line extends Figure {
public Line(int a, int b){
...
}
public String getName() {
return "Line";
}
public void move() {
...
}
}
public class Rect extends Figure{
public Rect(int a, int b){
...
}
public String getName() {
return "Rect";
}
public void move() {
...
}
public void setPosition(int a, int b){
...
}
}
public ArrayList<Figure> f = new ArrayList<>();
main(){
f.add(new Line(1,2));
f.add(new Rect(1,2));
System.out.print(f.get(0).getName()) // почему-то печатает "Figure"
Figure f1 = f.get(1);
f1.move(); // этого метода в списке нет
}
Answer the question
In order to leave comments, you need to log in
It's time for me to practice teaching:
So let's look at an example. When declaring a variable, we see the following structure in front of us:
Figure f1 = new Rect(1,2);
Figure in this expression is something that can be written to the variable f1 , but other than that, it symbolizes how we perceive this variable . In other words, whatever we write there, we will perceive it as a Figure and see the methods inherent only to this class. (It is worth noting that even if we see methods only from the parent class, if we override them, the new version will be executed).
The situation is similar with lists. What class you put in <>, and the contents of this list will be perceived.
If you need to get to invisible methods, you can do 2 things:
Line f2 = (Line)f.get(0);
Or ((Line)f.get(0)).move();
But here:
f.add(new Line(1,2));
System.out.print(f.get(0).getName()) // prints "Figure" for some reason
You're making a mistake, sir. It should and will output 'Line'. And you don't have to say you're wrong. Check what you write there and how you override this method.
Write @Override in the descendants of the methods you are overriding. For the visibility of a method that is not in the parent, you need to cast a type of type
Line f1 = (Line) f.get(1); f1.move();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question