亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> java

Java - 覆盖

在上一章中,我们讨论了超类和子类。如果一个类从它的超类继承了一个方法,那么如果它没有被标记为final,那么就有机会覆盖这个方法。

重写的好处是:能够定义特定于子类类型的行为,这意味着子类可以根据其要求实现父类方法。

在面向对象的术语中,覆盖意味着覆盖现有方法的功能。

示例

让我们看一个例子。

现场演示
class Animal {
   public void move() {
      System.out.println("Animals can move");
   }
}

class Dog extends Animal {
   public void move() {
      System.out.println("Dogs can walk and run");
   }
}

public class TestDog {

   public static void main(String args[]) {
      Animal a = new Animal();   // Animal reference and object
      Animal b = new Dog();   // Animal reference but Dog object

      a.move();   // runs the method in Animal class
      b.move();   // runs the method in Dog class
   }
}

这将产生以下结果 -

输出

Animals can move
Dogs can walk and run

在上面的例子中,你可以看到即使 b 是 Animal 的一种类型,它在 Dog 类中运行 move 方法。这样做的原因是:在编译时,对引用类型进行检查。但是,在运行时,JVM 会确定对象类型并运行属于该特定对象的方法。

因此,在上面的示例中,由于 Animal 类具有 move 方法,因此程序将正确编译。然后,在运行时,它运行特定于该对象的方法。

考虑以下示例 -

示例

现场演示
class Animal {
   public void move() {
      System.out.println("Animals can move");
   }
}

class Dog extends Animal {
   public void move() {
      System.out.println("Dogs can walk and run");
   }
   public void bark() {
      System.out.println("Dogs can bark");
   }
}

public class TestDog {

   public static void main(String args[]) {
      Animal a = new Animal();   // Animal reference and object
      Animal b = new Dog();   // Animal reference but Dog object

      a.move();   // runs the method in Animal class
      b.move();   // runs the method in Dog class
      b.bark();
   }
}

这将产生以下结果 -

输出

TestDog.java:26: error: cannot find symbol
      b.bark();
       ^
  symbol:   method bark()
  location: variable b of type Animal
1 error

这个程序会抛出编译时错误,因为 b 的引用类型 Animal 没有名为 bark 的方法。

方法覆盖的规则

使用 super 关键字

当调用重写方法的超类版本时,super 使用了关键字。

示例

现场演示
class Animal {
   public void move() {
      System.out.println("Animals can move");
   }
}

class Dog extends Animal {
   public void move() {
      super.move();   // invokes the super class method
      System.out.println("Dogs can walk and run");
   }
}

public class TestDog {

   public static void main(String args[]) {
      Animal b = new Dog();   // Animal reference but Dog object
      b.move();   // runs the method in Dog class
   }
}

这将产生以下结果 -

输出

Animals can move
Dogs can walk and run

java

  1. Java 运算符
  2. Java 接口
  3. Java try-with-resources
  4. Java 注释
  5. Java 中的 String Length() 方法:如何通过示例查找
  6. Java String indexOf() 方法与子字符串和示例
  7. Java String charAt() 方法及示例
  8. Java String compareTo() 方法:如何与示例一起使用
  9. Java String contains() 方法 |用示例检查子字符串
  10. Java String endsWith() 方法及示例
  11. Java String replace()、replaceAll() 和 replaceFirst() 方法
  12. Java 中的静态变量:什么是静态块和方法 [示例]