首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java属性步骤执行顺序

2012-10-07 
java属性方法执行顺序?样题一:class P {?? ?private int val 10??? ?public void output() {?? ? ? ?Sy

java属性方法执行顺序

?

样题一

class P {

?? ?private int val = 10;

?

?? ?public void output() {

?? ? ? ?System.out.println("P.output(),val+" + val);

?? ?}

?

?? ?public P() {

?? ? ? ?System.out.println("P constructor");

?? ? ? ?output();

?? ?}

}

?

public class A extends P {

?? ?private int val = 1;

?

?? ?public void output() {

?? ? ? ?System.out.println("A.output(),val=" + val);

?? ?}

?

?? ?public A(int val) {

?? ? ? ?this.val = val;

?? ? ? ?System.out.println("A constructor");

?? ?}

?

?? ?public static void main(String[] args) {

?? ? ? ?A a = new A(5);

?? ?}

}

答案:P?constructor??A.output(),val=0??A?constructor

?

样题二

?

class parent {

?? ?public parent() {

?? ? ? ?System.out.println("parent...");

?? ?}

}

?

class child extends parent {

?? ?brother b = new brother();

?? ?public child() {

?? ? ? ?System.out.println("child...");

?? ?}

?

}

?

class brother {

?? ?public brother() {

?? ? ? ?System.out.println("brother...");

?? ?}

}

?

public class Testchild {

?

?? ?/**

?? ? * @param args

?? ? */

?? ?public static void main(String[] args) {

?? ? ? ?System.out.println(new child());

?

?? ?}

?

}

答案:parent... ?brother... ?child...

?

结论:属性的优先级高于方法,父类构造方法高于自身构造方法,重写父亲类的方法高于本身属性执行?。

热点排行