子类父类方法与属性的调用(4)

 package com.me;

public class Parent {
 public String name="parent name";
 {
  System.out.println("parent common 语句块");
 }
 static {
     System.out.println("parent static 语句块"); 
 }

 public Parent(){
  System.out.println(this.name);
  this.show();
 }
 public void show(){
  System.out.println("here  "+this.name);
  System.out.println("Parent common show");
 }
}


package com.me;

public class ChildA extends Parent{
    public static String name="CA";
 static {
     System.out.println("childa static 语句块"); 
 }
 {
  System.out.println("childa common 语句块");
 }
    public ChildA(){
     
     System.out.println(this.name);
     this.show();
    }
    public void show(){
     System.out.println("childA common show");
    }
}

package com.me;

public class ChildB extends ChildA{
  public String name="CB";
  public C c=new C();
  static {
      System.out.println("childb static 语句块"); 
  }
  {
   System.out.println("childb common 语句块");
  }
  
  public ChildB(){
      System.out.println(this.name);
       this.show();
       D d=new D();
     }
 
  public void show(){
      System.out.println("childB common show");
      
  }
 
 
}


package com.me;

public class C {
 public String name="C"; 
    public C(){
     System.out.println(this.name);
    }
}

package com.me;

public class D {
 public String name="D";
    public D(){
     System.out.println(this.name);
    }
}

package com.me;

public class Test { 
 public static void main(String[] args){
     ChildB cb=new ChildB();     
    }
}

一共六个类parent,childa,childb,c,d,test

public class ChildA extends Parent
public class ChildB extends ChildA
c,d,test独立
ChildB的属性中public C c=new C();
ChildB的构造方法中D d=new D();

好了,明白了类之间的关系就写出打印结果了,如下:
parent static 语句块
childa static 语句块
childb static 语句块
parent common 语句块
parent name
childB common show
childa common 语句块
CA
childB common show
C
childb common 语句块
CB
childB common show
D

总结:
执行的顺序

父类------>子类

各个类中的静态语句块(匿名方法)

普通(非静态)语句块,属性的初始化都在构造方法前执行

普通(非静态)语句块,属性按顺序由上到下一次执行

Parent类,ChildA,ChildB存在继承关系,并且三个类中都有
方法show,this.show执行的始终是子类中的show方法,若ChildB中
无show则执行ChildA中的show方法,若ChildB中也没有则执行Parent
中的方法,若ChildB中没有ChildA中有则执行Parent中的(废话,呵呵)

到此"子类父类方法与属性的调用"系列到此结束,不知坚持看完这四篇
文章的朋友晕了没,呵呵

睡觉去了。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值