Polymorphic and static method

 1 class Parent {
 2     int num = 4;
 3 
 4     protected void foo() {
 5         System.out.println("foo() of Parent");
 6     }
 7 
 8     static protected void bar() {
 9         System.out.println("bar() of Parent");
10     }
11 }
12 
13 class Child extends Parent {
14     int num = 5;
15 
16     protected void foo() {
17         System.out.println("foo() of Child");
18     }
19 
20     static protected void bar() {
21         System.out.println("bar() of Child");
22     }
23 }
24 
25 public class Test {
26     public static void main(String[] args) {
27         Parent f1 = new Parent();
28         System.out.println(f1.num);
29 
30         Parent f2 = new Child();
31         System.out.println(f2.num);
32 
33         Child c = new Child();
34         System.out.println(c.num);
35 
36         f1.foo();
37         f2.foo();
38         c.foo();
39 
40         f1.bar();
41         f2.bar();
42         c.bar();
43     }
44 }

输出如下:

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

 

1.关于输出4 4 5:需要明确多态的定义,多态是针对方法的,和属性无关,f2引用的类型是Parent,所以输出4

2.关于f2.bar():static方法是没有多态的,static、final、private都是前期绑定(编译期绑定),多态是晚绑定(动态绑定)。扩展:当被定义为private,会被隐式指定为final

补充:

1.final:

There are three distinct meanings for the final keyword in Java.

  • final class cannot be extended.

  • final method cannot be overridden.

  • final variable cannot be assigned to after it has been initialized.

  • 总结:子类可以获得父类的final方法,但无法覆盖(override)

2. All methods that are accessible are inherited by subclasses.The only difference with inherited static (class) methods and inherited non-static (instance) methods is that when you write a new static method with the same signature, the old static method is just hidden, not overridden.

在本例中,子类的static bar隐藏了父类的static bar,也就是说就算没有子类的bar方法,子类依然可以调用bar方法

 

posted @ 2021-04-11 20:57  lancer666  阅读(56)  评论(0)    收藏  举报