0

Please help me about this code,thx!

class Parent {
    int num = 4;

    protected void foo() {
        System.out.println("foo() of Parent");
    }

    static protected void bar() {
        System.out.println("bar() of Parent");
    }
}

class Child extends Parent {
    int num = 5;

    protected void foo() {
        System.out.println("foo() of Child");
    }

    static protected void bar() {
        System.out.println("bar() of Child");
    }
}

public class Test {
    public static void main(String[] args) {
        Parent f1 = new Parent();
        System.out.println(f1.num);

        Parent f2 = new Child();
        System.out.println(f2.num);

        Child c = new Child();
        System.out.println(c.num);

        f1.foo();
        f2.foo();
        c.foo();

        f1.bar();
        f2.bar();
        c.bar();
    }
}

The output is as follows:

4
4
5
foo() of Parent
foo() of Child
foo() of Child
bar() of Parent
bar() of Parent
bar() of Child

Could you tell me if Person f2=new Child() is polymorphism?If so,why the output of 'f2.num' is 4,but 'f2.foo()' is 'foo() of Child'. I think it has to do with the super class's static bar().Please tell me the principle,thanks very much.

lancer666
  • 3
  • 2
  • 1
    this sounds like you're asking for an answer to your school work, I could be wrong but if so that's not really what SO is for. – default_avatar Apr 10 '21 at 13:58

1 Answers1

0

Yes, Person f2=new Child() is a Runtime Polymorphism. And you are absolutely correct for the output of f2.num' is 4,but f2.foo() is foo() of Child. As the static member is inherited to the subclass but with some restrictions which are:

  • You can override them
  • If you redefined a method in the subclass then the inherited method (bar()) of the parent class get hidden

Hence when you are creating the object f2 with the reference of Parent class the normal procedure runtime polymorphism is happening (binding child object with parent) but as you have redefined the bar() method, the parent method gets hidden and the child class bar() method is mapped to this statement f2.bar()

Sumit Singh
  • 487
  • 5
  • 19