Java---面向对象---精确掌握程序执行顺序

来源:互联网 发布:查看端口状态命令 编辑:程序博客网 时间:2024/06/06 17:18
public class Person {private String name="Jack";//4private int age=2;//5public Person() {//3 此处先执行super(...),再返回到当前类往下执行age=1000;//6}public static void main(String[] args) {//1Person p = new Person();//2System.out.println(p.name+","+p.age);//7}}


public class Demo {public static void main(String[] args) {new C();}}class A{static{}{System.out.println("A的属性");}public A() {System.out.println("A的构造方法");}}class B extends A{{System.out.println("B的属性");}public B() {System.out.println("B的构造方法");}}class C extends B{{System.out.println("C的属性");}public C() {System.out.println("C的构造方法");}}

运行结果:

A的属性
A的构造方法
B的属性
B的构造方法
C的属性
C的构造方法


由此可知:初始化一个对象时,必先初始其属性;构造一个对象时,必先构造其父类对象。


public class Demo {public static void main(String[] args) {Father father = new Child();System.out.println("---------");father = new Child();}}class Father{public Father(){System.out.println("father的构造");}static{System.out.println("father的静态块");}}class Child extends Father{public Child(){System.out.println("child的构造");}static{System.out.println("child的静态块");}}
运行结果:
father的静态块
child的静态块
father的构造
child的构造
---------
father的构造

child的构造


由此可知:先静态(先父类再子类),再非静态(先父类再子类); 整个程序执行期间,静态块只执行一次,而且类模板对象只有一个。

同时需知:静态方法不能被非静态方法覆盖,反之也不行。 覆盖方法:前(权限)不能小,后(非运行时异常)不能大。



理解堆内存与栈内存的不同

public class Demo {static Foo fooBar(Foo foo) { //1011   ③foo.setX(100);return foo;}public static void main(String[] args) {Foo foo = new Foo(300); //假设堆内存地址:1011   ①System.out.println(foo.getX()); //运行结果:300Foo fooFoo = fooBar(foo);//1011   ②System.out.println(foo.getX() + "-" + fooFoo.getX());//运行结果:100-100foo = fooBar(fooFoo);System.out.println(foo.getX() + "-" + fooFoo.getX());//运行结果:100-100}}class Foo {private int x;//100public Foo(int x) {this.x = x;}public void setX(int x) {this.x = x; // x=x; //若上一句改成这样,则setX()无效---无法为实例变量赋值}public int getX() {return x;}}



原创粉丝点击