V
V
Vlad2020-06-12 21:56:07
Java
Vlad, 2020-06-12 21:56:07

Subclass fields under polymorphism?

Why are subclass variables visible in polymorphism that are not in the superclass?

class Greeting{
    protected void sayHello(){
        System.out.println("hello");
    }
}

class GreetingByName extends Greeting{
    String name = "Vasya";
    @Override
    protected void sayHello() {
        System.out.println("hello " + name);
    }
}
Greeting greeting = new GreetingByName();
greeting.sayHello();


After the call, hello vasya will turn out, but how is the name(vasya) variable visible if it is not in the class that is the type for the link? At runtime, jvm learns the exact type of the object and works with it, allowing you to call only the methods prescribed in the type (class) of the link?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question