java构造方法

2018-03-07  本文已影响0人  ZzRr_

因为Fx中的Fx()已经显示的调用了super(),而Fx(int i)也调用了this(),所以也间接的调用了super(),所以的new Fx(5)的时候会通过this()显式的调动父类构造器Ex()

public class Ex {
  Ex() {
      System.out.println("Ex,no-args");
  }
  Ex(int i) {
      System.out.println("Ex,int");
  }
  public static void main(String[] args) {
      Fx f = new Fx(5);
  }
}
class Fx extends Ex {
  Fx() {
      super();
      System.out.println("Fx,no-args");
  }
  Fx(int i) {
      this();
      System.out.println("Fx,int");
  }
}
public class Obj implements Cloneable {
    private int a = 0;
    public int getA() {
        return a;
    }
    public void setA(int a) {
        this.a = a;
    }
    public Obj() {
        System.out.println("sonstruct");
    }
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object o = null;
        o = (Obj)super.clone();
        return o;
    }
    public static void main(String[] args) {
        Obj a = new Obj();
        Obj b = null;
        a.setA(11);
        try {
             b = (Obj)a.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        System.out.println(a.getA());
        a.setA(99);
        System.out.println(b.getA());
    }
}
  1. 反射--会调用构造器
class Person{
    String name = "H";

    public Person() {
        System.out.println("construct");
    }

    @Override
    public String toString() {
        return name;
    }
}
public class Test {
    public static void main(String[] args) {
        Class clazz;
        try {
            clazz = Class.forName("Person");
            Person person = (Person)clazz.newInstance();
            System.out.println(person);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  1. 通过反序列化--不许调用构造器
public class People implements Serializable{
    private String name;

    public People() {
        this.name = "OOOO";
        System.out.println("construct");
    }
    @Override
    public String toString() {
        return name;
    }

    public static void main(String[] args) {
        People p = new People();
        System.out.println(p);
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;

        try {
            FileOutputStream fos = new FileOutputStream("people.out");
            oos = new ObjectOutputStream(fos);
            oos.writeObject(p);
            oos.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        People p1;

        try {
            FileInputStream fis = new FileInputStream("people.out");
            ois = new ObjectInputStream(fis);
            p1 = (People)ois.readObject();
            System.out.println(p1);
            if (p != p1) {
                System.out.println("tow object");
            }
            ois.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读