如果在child class中不能直接操作继承而来的那些private field,又该如何初始化它们呢?在Java中可以使用关键字super调用parent class的构造函数。如果要这么做的话,super()必须是child class构造函数的第一条语句。

class Person
{
   private String name;

   public Person(String theName)
   {
      this.name = theName;
   }

   public String getName()
   {
      return name;
   }

   public boolean setName(String theNewName)
   {
      if (theNewName != null)
      {
         this.name = theNewName;
         return true;
      }
      return false;
   }
}

public class Employee extends Person
{

   private static int nextId = 1;
   private int id;

   public Employee(String theName)
   {
      super(theName);
      id = nextId;
      nextId++;
   }

   public int getId()
   {
      return id;
   }

   public static void main(String[] args)
   {
      Employee emp = new Employee("Mark");
      System.out.println(emp.getName());
      System.out.println(emp.getId());
   }
}

以上例子中,Employee构造函数中的super(theName)会调用class Person的构造函数,利用字符串参数来设置姓名。

如果一个Java class没有构造函数,编译器会自动加上一个无参数的默认构造函数,如public Person()。注意构造函数没有返回类型,且名字要与class名一致。如果parent class有多个构造函数可供选择,super()的参数决定了具体是哪个构造函数被调用。当child class没有在自身构造函数的第一句调用super而parent class里又只定义了带参数的构造函数时,编译器会因为无法判定parent class构造函数的适用性而报错。解决的办法是在parent class中定义无参默认构造函数,或者在child class里显式用super()调用带参数的构造函数。



0:00

Given the class definitions of Point2D and Point3D below, which of the constructors that follow (labeled I, II, and III) would be valid in class Point3D?

class Point2D {
   public int x;
   public int y;

   public Point2D() {}

   public Point2D(int x,int y) {
     this.x = x;
     this.y = y;
   }
   // other methods
}

public class Point3D extends Point2D
{
   public int z;

   // other code
}

// possible constructors for Point3D
I.  public Point3D() {}
II. public Point3D(int x, int y, int z)
    {
       super(x,y);
       this.z = z;
    }
III. public Point3D(int x, int y)
     {
        this.x = x;
        this.y = y;
        this.z = 0;
     }
注意xy均是public,都能在child class中被直接访问。
4

Given the class definitions of Point and NamedPoint below, which of the constructors that follow (labeled I, II, and III) would be valid in class NamedPoint?

class MPoint
{
   private int myX; // coordinates
   private int myY;

   public MPoint( )
   {
      myX = 0;
      myY = 0;
   }

   public MPoint(int a, int b)
   {
      myX = a;
      myY = b;
   }

   // ... other methods not shown

}

public class NamedPoint extends MPoint
{
   private String myName;
   // constructors go here
   // ... other methods not shown
}

//  Proposed constructors for this class:
I.   public NamedPoint()
     {
        myName = "";
     }
II.  public NamedPoint(int d1, int d2, String name)
     {
        myX = d1;
        myY = d2;
        myName = name;
     }
III. public NamedPoint(int d1, int d2, String name)
     {
        super(d1, d2);
        myName = name;
     }
myXmyYprivate,只能通过super来初始化。隐式调用默认构造函数和显示调用带参构造函数都是正确的做法。
2


陈 欣

AADPS创始人

发表评论