重写(override)指的是在child class中用签名相同(即名称相同、参数相同、返回值相同)的method覆盖parent class中对应method的行为。这样一来,对于child class而言调用的就会是重写后的method。下面的例子中MeanGreeter继承了Greetergreet method并将其重写了。

public class Greeter
{
   public String greet()
   {
      return "Hi";
   }

   public static void main(String[] args)
   {
      Greeter g1 = new Greeter();
      System.out.println(g1.greet());
      Greeter g2 = new MeanGreeter();
      System.out.println(g2.greet());
   }
}

class MeanGreeter extends Greeter
{
   public String greet()
   {
      return "Go Away";
   }
}

重载(overload)指的是好几个method有相同的名字,但参数类型、顺序或数目各不相同。下面的例子中greet(String who)重载了greet()MeanGreeter继承了greet(String who),并没有重写它。

public class Greeter
{
   public String greet()
   {
      return "Hi";
   }

   public String greet(String who)
   {
      return "Hello " + who;
   }

   public static void main(String[] args)
   {
      Greeter g1 = new Greeter();
      System.out.println(g1.greet("Sam"));
      Greeter g2 = new MeanGreeter();
      System.out.println(g2.greet("Nimish"));
   }
}

class MeanGreeter extends Greeter
{
   public String greet()
   {
      return "Go Away";
   }
}

Java会自动根据传入的参数组合决定调用哪个重载函数。



0:00

Which of the following declarations in Student would correctly override the getFood method in Person?

public class Person
{
   private String name = null;

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

   public String getFood()
   {
      return "Hamburger";
   }
}

public class Student extends Person
{
   private int id;
   private static int nextId = 0;

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

   public int getId() {return id;}

   public void setId (int theId)
   {
      this.id = theId;
   }
}
选项三的参数签名和parent class中的对应method一致。
3

Which of the following declarations in Person would correctly overload the getFood method in Person?

public class Person
{
   private String name = null;

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

   public String getFood()
   {
      return "Hamburger";
   }
}

public class Student extends Person
{
   private int id;
   private static int nextId = 0;

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

   public int getId() {return id;}
   public void setId (int theId)
   {
      this.id = theId;
   }
}
选项二同名不同参,满足重载的条件。
2


陈 欣

AADPS创始人

发表评论