1

I know that when you overload method then java resolves it on compilation stage so that's why when you writing something like this:

public class SomeClass{
    private static void someMethod(Object obj){
        System.out.println("obj");
    }
    private static void someMethod(String str){
        System.out.println("str");
    }
    public static void main(String[] args) {
        Object obj = new SomeClass();
        obj.someMethod(obj);
    }
}

you will get obj, because oveloading is resolved on compilation and doing something like that:

 public abstract class Animal {
                public void careFor() {
        play();
    }
    public void play() {
        System.out.println("pet animal");
    }
}
 public class Lion extends Animal {

    public void play() {
        System.out.println("toss in meat");
    }

    public static void main(String[] args) {
        Animal animal = new Lion();
        animal.careFor();
    }
}

you will get toss in meat beacuse overriding method is resolved on runtime stage. But what I don't understand. Why when you overrding instance variable you will get situation like resolving on compilation stage. For example:

public abstract class Animal {
    String name = "???";

    public void printName() {
        System.out.println(name);
    }
}
public class Lion extends Animal {
    String name = "Leo";

    public static void main(String[] args) {
        Animal animal = new Lion();
        animal.printName();
    }
}

In this situation I will get ??? . So it looks like resolving on compilation stage when you overriding variable. Is it so?

Bohdan Myslyvchuk
  • 1,657
  • 3
  • 24
  • 39
  • Well, yes, it is. Variables are accessed based on reference, not instance. There is conceptually no "overriding" of variables. – Mena May 23 '17 at 12:42

1 Answers1

4

In Java Only methods are Polymorphism and not variables.

So when you do

 Animal animal = new Lion();

You get all the variables from Animal and methods from Lion gets execute.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307