还有人不懂继承?25 个 Case 包教包会
- 1.Implement single inheritance
- 2.Implement multilevel inheritance
- 3.Implement hierarchical inheritance
- 4.Override a base class method into a derived class
- 5.Demonstrate the protected access specifier
- 6.Create an Student class by inheriting Person class
- 7.Call the method with the same name using super keyword
- 8.Call a superclass constructor from sub/child class
- 9.Method Overloading and Inheritance
- 10.Final Class and Inheritance
- 11.Static Methods and Inheritance
- 12.Multiple Inheritance using Interfaces
- 13.Method Overriding with Exception Handling
- 14.Accessing Superclass Members
- 15.Method Overriding with Covariant Return Types
- 16.Constructor Overriding and Superclass Initialization
- 17.Demonstrates method overriding
- 18.Demonstrates the use of the protected access specifier
- 19.Demonstrates accessing superclass members using the super keyword
- 20.Demonstrates the use of a final class in inheritance
- 21.Demonstrates the use of abstract classes in inheritance
- 22.Demonstrate the order of superclass and subclass initialization
- 23.Demonstrate dynamic method dispatch
- 24.Demonstrate interface inheritance
- 25.Diamond problem in multiple inheritance
Java 的三大特性:封装、继承、多态。本篇博客将重点通过一些案例讲解 继承 这个概念。
1.Implement single inheritance
public class SingleInheritance // Main class
{public static void main(String[] args){ Dog dog = new Dog("Buddy"); // Create an instance of Dog dog.eat(); // Call methods from Animal class dog.bark(); // Call methods from Dog class}
}class Animal // Parent class (Superclass)
{protected String name;public Animal(String name){this.name = name;}public void eat(){System.out.println(name + " is Eating");}
}class Dog extends Animal // Child class (Subclass) inheriting from Animal
{public Dog(String name){super(name);}public void bark(){System.out.println(name + " is Barking");}
}
Buddy is Eating
Buddy is Barking
super()
/super(parameters)
必须出现在子类构造方法的第一行,这是显式调用父类构造方法的唯一方式。因为在子类中调用父类构造方法的名字会引起一个语法错误。构造方法可以用来构造一个类的实例,不像属性和方法,父类的构造方法是不被子类继承的,它们只能从子类的构造方法中用super
调用。
2.Implement multilevel inheritance
public class MultilevelInheritance // Main class
{public static void main(String[] args){ Puppy puppy = new Puppy("Buddy"); // Create an instance of Puppy puppy.eat(); // Call methods from Animal class puppy.bark(); // Call methods from Dog class puppy.play(); // Call methods from Puppy class}
}class Animal // Grandparent class
{protected String name;public Animal(String name){this.name = name;}public void eat(){System.out.println(name + " is Eating");}
}class Dog extends Animal // Parent class inheriting from Animal
{public Dog(String name){super(name);}public void bark(){System.out.println(name + " is Barking");}
}class Puppy extends Dog // Child class inheriting from Dog
{public Puppy(String name){super(name);}public void play(){System.out.println(name + " is Playing");}
}
Buddy is Eating
Buddy is Barking
Buddy is Playing
构造方法链(
constructor chaining
):在任何情况下,构造一个类的实例时,将会调用沿着继承链的所有父类的构造方法。当构造一个子类的对象时,子类构造方法会在完成自己的任务之前,首先调用它的父类的构造方法。如果父类继承自其他类,那么父类构造方法又会在完成自己的任务之前,调用它的父类的构造方法。这个过程持续到沿着这个继承体系机构的最后一个构造方法被调用为止。
3.Implement hierarchical inheritance
public class HierarchicalInheritance // Main class
{public static void main(String[] args){ Car car = new Car(); // Create objects of child classesMotorcycle motorcycle = new Motorcycle();car.display(); // Calling methods of parent classmotorcycle.display();car.displayCar(); // Calling methods of child classesmotorcycle.displayMotorcycle();}
}class Vehicle // Parent class
{void display(){System.out.println("This is a Vehicle");}
}class Car extends Vehicle // Child class 1
{void displayCar(){System.out.println("This is a Car");}
}class Motorcycle extends Vehicle // Child class 2
{void displayMotorcycle(){System.out.println("This is a Motorcycle");}
}
This is a Vehicle
This is a Vehicle
This is a Car
This is a Motorcycle
4.Override a base class method into a derived class
这个 Java 程序演示了方法覆盖,这是面向对象编程中的一个概念,即子类为父类中已定义的方法提供特定实现。在这个程序中,有两个类: Vehicle 和 Car。汽车类中的显示方法覆盖了车辆类中的显示方法。下面是对程序的解释:
public class OverrideMethod // Main class
{public static void main(String[] args){ Car car = new Car(); // Create an object of the derived class car.display(); // Call the overridden method}
}class Vehicle // Base class
{void display(){System.out.println("This is a Vehicle");}
}class Car extends Vehicle // Derived class
{@Overridevoid display(){System.out.println("This is a Car");}
}
This is a Car
5.Demonstrate the protected access specifier
public class AccessSpecifier // Main class
{public static void main(String[] args){ Car car = new Car(); // Create an object of the child class car.setBrand("Toyota"); // Set the brand using the public method car.displayBrand(); // Access the protected member and method}
}class Vehicle // Parent class
{protected String brand;protected void displayBrand(){System.out.println("Brand : " + brand);}
}class Car extends Vehicle // Child class
{public void setBrand(String brand){this.brand = brand;}
}
Brand : Toyota
6.Create an Student class by inheriting Person class
此 Java 程序说明了继承的概念,特别是单一继承。继承是面向对象编程的一个基本概念,它允许一个类(子类或派生类)继承另一个类(超类或基类)的属性和方法。在本程序中,有两个类: Person 和 Student,其中 Student 继承自 Person。下面是对该程序的解释:
public class InheritingExample
{public static void main(String[] args){Student stu = new Student(1000, "Ram Kumar", 25, 88.96f);stu.printStudentDetails();}
}class Person
{String name;int age;Person(int age, String name){this.name = name;this.age = age;}
}class Student extends Person
{int id;float per;Student(int idn, String name, int age, float percent){super(age, name);id = idn;per = percent;}void printStudentDetails(){System.out.println("Student ID : " + id);System.out.println("Student Name : " + name);System.out.println("Student Age : " + age);System.out.println("Student Percentage : " + per);}
}
Student ID : 1000
Student Name : Ram Kumar
Student Age : 25
Student Percentage : 88.96
7.Call the method with the same name using super keyword
这个 Java 程序演示了如何使用 super
关键字从父类调用方法。在这个程序中,有三个类: Parent 类、Child1 类和 Child2 类,形成一个类层次结构。Child1 和 Child2 类继承自父类。每个子类都会覆盖显示方法,并在执行各自的特定操作前使用 super
关键字调用父类的显示方法。下面是对程序的解释:
public class SuperKeyword // Main classs
{public static void main(String[] args){Child1 child1 = new Child1(); // Create objects of the Child classesChild2 child2 = new Child2();child1.display(); // Call the display() methodchild2.display();}
}class Parent // Parent class
{void display(){System.out.println("Parent class display method");}
}class Child1 extends Parent // Child class 1
{void display(){super.display(); // Call the display() method of the parent classSystem.out.println("Child 1 class display method");}
}class Child2 extends Parent // Child class 2
{void display(){super.display(); // Call the display() method of the parent classSystem.out.println("Child 2 class display method");}
}
Parent class display method
Child 1 class display method
Parent class display method
Child 2 class display method
8.Call a superclass constructor from sub/child class
这个 Java 程序演示了构造函数链以及在创建子类对象时使用 super
关键字调用超类构造函数的过程。在这个程序中,有两个类: Super 和 Sub,其中 Sub 继承自 Super。下面是对该程序的解释:
public class Constructor
{public static void main(String[] args){Sub obj = new Sub();}
}class Super
{Super(){System.out.println("Super class Constructor called");}
}class Sub extends Super
{Sub(){super();System.out.println("Sub class Constructor called");}
}
Super class Constructor called
Sub class Constructor called
9.Method Overloading and Inheritance
这个 Java 程序演示了方法重载,这是面向对象编程中的一个概念,即一个类可以有多个名称相同但参数列表不同的方法。在这个程序中,有两个类: Vehicle(父类)和 Car(子类),Car 类重载了 start
方法。下面是对程序的解释:
public class MethodOverloading // Main class
{public static void main(String[] args){Car car = new Car();car.start(); // Accessing parent class methodcar.start(3); // Accessing overloaded method in child class}
}class Vehicle // Parent class
{void start(){System.out.println("Vehicle starting ...");}
}class Car extends Vehicle // Child class
{void start(int count){System.out.println("Starting " + count + " Cars ...");}
}
Vehicle starting ...
Starting 3 Cars ...
10.Final Class and Inheritance
在这个 Java 程序中,您定义了一个名为 FinalClass 的类和一个名为 Vehicle 的 final
类。final
类是一个不能被其他类子类或扩展的类。下面是对程序的解释:
public class FinalClass // Main class
{public static void main(String[] args){Vehicle vehicle = new Vehicle();vehicle.start();}
}final class Vehicle // Final parent class
{void start(){System.out.println("Vehicle starting ...");}
}
Vehicle starting ...
11.Static Methods and Inheritance
这个 Java 程序演示了静态方法在类层次结构中的使用。在这个程序中,有两个类: Vehicle(父类)和 Car(子类)。这两个类都有一个名为 display
的静态方法。静态方法属于类而不是类的实例,它们可以使用类名本身来调用。下面是对程序的解释:
public class StaticMethods // Main class
{public static void main(String[] args){Vehicle.display(); // Accessing static method in parent classCar.display(); // Accessing static method in child class}
}class Vehicle // Parent class
{static void display(){System.out.println("This is a Vehicle");}
}class Car extends Vehicle // Child class
{static void display(){System.out.println("This is a Car");}
}
This is a Vehicle
This is a Car
12.Multiple Inheritance using Interfaces
这个 Java 程序演示了接口、多接口实现和方法重载的使用。在这个程序中,有两个接口(Flyable 和 Swimmable)和一个实现了这两个接口的类(Bird)。下面是对该程序的解释:
public class Interfaces // Main class
{public static void main(String[] args){Bird bird = new Bird();bird.fly();bird.swim();}
}interface Flyable // First interface
{void fly();
}interface Swimmable // Second interface
{void swim();
}class Bird implements Flyable, Swimmable // Class implementing multiple interfaces
{@Overridepublic void fly(){System.out.println("Bird is Flying");}@Overridepublic void swim(){System.out.println("Bird is Swimming");}
}
Bird is Flying
Bird is Swimming
13.Method Overriding with Exception Handling
在这个 Java 程序中,您将演示方法重载和异常处理的使用。程序定义了一个父类和一个继承自父类的子类。子类重载了显示方法,并更改了可抛出的异常类型。下面是对该程序的解释:
public class MethodOverride // Main class
{public static void main(String[] args){Parent parent = new Child();try{parent.display();}catch (Exception e){e.printStackTrace();}}
}class Parent // Parent class
{void display() throws Exception{System.out.println("Parent's display method");}
}class Child extends Parent // Child class
{@Overridevoid display() throws RuntimeException{System.out.println("Child's display method");}
}
Parent parent = new Child();
: 这一行创建了一个子类对象,但将其赋值给父类的引用。这样做是允许的,因为 Java 支持多态性,父类的引用变量可以引用子类的对象。
在这个程序中,子类中的显示方法覆盖了父类中的显示方法,并改变了它可以抛出的异常类型。这是允许的,因为子类方法可以抛出父类方法所抛出异常的子类型。
当你调用父类对象的 display
方法时,它实际上调用了子类的 display
方法,并且 Child's display method
被打印到控制台。但是,子类中的 display
方法会抛出一个 RuntimeException
,而主方法没有明确捕获该异常。因此,出现了一个未处理的异常,堆栈跟踪被打印到控制台。
Child's display method
14.Accessing Superclass Members
这个 Java 程序演示了如何使用 super
关键字从子类访问父类的成员。在这个程序中,有两个类: Parent(父类)和 Child(子类)。子类扩展了父类,并使用 super
关键字访问父类中的受保护成员。下面是对该程序的解释:
public class SuperClassMember // Main class
{public static void main(String[] args){Child child = new Child();child.displayMessage();}
}class Parent // Parent class
{protected String msg = "Hello World";
}class Child extends Parent // Child class
{void displayMessage(){System.out.println(super.msg); // Accessing parent class member using super keyword}
}
Hello World
15.Method Overriding with Covariant Return Types
这个 Java 程序说明了在处理不同返回类型时方法重载和多态性的概念。在这个程序中,有两个类: Animal(父类)和 Dog(子类),Dog 类覆盖了 Animal 类的 makeSound
方法。下面是对该程序的解释:
public class ReturnTypes // Main class
{public static void main(String[] args){Animal animal = new Dog();System.out.println(animal.makeSound());}
}class Animal // Parent class
{String makeSound(){return "Animal Makes a Sound";}
}class Dog extends Animal // Child class
{@OverrideString makeSound(){return "Dog Barks";}
}
Dog Barks
16.Constructor Overriding and Superclass Initialization
在这个 Java 程序中,有一个名为 Vehicle 的父类和一个名为 Car 的子类。Car 类继承自 Vehicle 类,两个类都有用于初始化属性的构造函数。该程序演示了如何初始化子类的属性,同时确保正确设置父类的属性。下面是对该程序的解释:
public class Initialization // Main class
{public static void main(String[] args){Car car = new Car("Ford", "Porsche");System.out.println("Brand : " + car.brand);System.out.println("Model : " + car.model);}
}class Vehicle // Parent class
{String brand;Vehicle(String brand){this.brand = brand;}
}class Car extends Vehicle // Child class
{String model;Car(String brand, String model){super(brand);this.model = model;}
}
Brand : Ford
Model : Porsche
17.Demonstrates method overriding
这个 Java 程序演示了类继承和方法重载。它定义了两个类,Shape(父类)和 Circle(子类),其中 Circle 继承自 Shape。程序使用 calculateArea
方法计算圆的面积,该方法在 Circle 类中被重载。下面是对程序的解释:
class Circle extends Shape
{double radius;Circle(double radius){this.radius = radius;}@Overridevoid calculateArea(){double area = Math.PI * radius * radius;System.out.println("Area of Circle : " + area);}public static void main(String[] args){Circle circle = new Circle(5.0);circle.calculateArea();}
}class Shape
{void calculateArea(){System.out.println("Area calculation not implemented");}
}
Area of Circle : 78.53981633974483
18.Demonstrates the use of the protected access specifier
这个 Java 程序演示了受保护访问修饰符和继承的使用。程序中有两个类,Person(父类)和 Student(子类)。Student 类继承自 Person 类,可以访问父类中定义的受保护方法。下面是对该程序的解释:
class Student extends Person
{void showDetails(){displayDetails(); // Protected method is accessible in the derived class}public static void main(String[] args){Student student = new Student();student.showDetails();}
}class Person
{protected void displayDetails(){System.out.println("This is a person");}
}
This is a person
19.Demonstrates accessing superclass members using the super keyword
这个 Java 程序说明了方法重载的概念,以及子类如何使用 super
关键字调用超类中的方法。在这个程序中,有两个类: Animal(父类)和 Dog(子类)。Dog 类扩展了 Animal 类,并覆盖了 displaySound
方法。下面是该程序的说明:
class Dog extends Animal
{@Overridevoid displaySound(){super.displaySound(); // Access superclass methodSystem.out.println("Dog barks");}public static void main(String[] args){Dog dog = new Dog();dog.displaySound();}
}class Animal
{void displaySound(){System.out.println("Animal makes a sound");}
}
Animal makes a sound
Dog barks
20.Demonstrates the use of a final class in inheritance
在这个 Java 程序中,您定义了一个名为 FinalClass 的 final
类,然后尝试创建一个名为 DerivedClass 的类来扩展 FinalClass。然而,这会导致编译错误,因为您不能从 final
类继承。
在类中使用 final
关键字时,表示该类不能被子类化或扩展。因此,任何从最终类(FinalClass)创建子类(如 DerivedClass)的尝试都会导致编译错误。
final class FinalClass
{// Some final class members
}// This line will result in a compilation error since FinalClass is final
class DerivedClass extends FinalClass
{// Some code here
}
Error : cannot inherit from final FinalClass
21.Demonstrates the use of abstract classes in inheritance
这个 Java 程序演示了如何使用 抽象类 和 方法重载 来计算形状的面积。它定义了一个抽象类 Shape 和两个具体子类 Circle 和 Rectangle,这两个子类提供了计算圆形和矩形面积的具体实现。下面是对该程序的解释:
public class Main
{public static void main(String[] args){Circle circle = new Circle(5);Rectangle rectangle = new Rectangle(4, 6);System.out.println("Area of Circle : " + circle.calculateArea());System.out.println("Area of Rectangle : " + rectangle.calculateArea());}
}abstract class Shape
{abstract double calculateArea();
}class Circle extends Shape
{double radius;Circle(double r){radius = r;}@Overridedouble calculateArea(){return Math.PI * radius * radius;}
}class Rectangle extends Shape
{double length, width;Rectangle(double l, double w){length = l;width = w;}@Overridedouble calculateArea(){return length * width;}
}
Area of Circle : 78.53981633974483
Area of Rectangle : 24.0
22.Demonstrate the order of superclass and subclass initialization
在这个 Java 程序中,有两个类:Base 和 Derived,它们分别代表一个基类和一个派生类(或子类)。这些类包括实例块和构造函数,用于演示对象实例化过程中的执行顺序。下面是对该程序的解释:
public class Main
{public static void main(String[] args){Derived derived = new Derived();}
}class Base //Base Class
{{System.out.println("Base class instance block");}Base(){System.out.println("Base class constructor");}
}class Derived extends Base //Derived Class
{{System.out.println("Derived class instance block");}Derived(){System.out.println("Derived class constructor");}
}
该程序演示了在创建继承自基类的派生类对象时,实例块和构造函数的执行顺序。
Base class instance block
Base class constructor
Derived class instance block
Derived class constructor
23.Demonstrate dynamic method dispatch
这个 Java 程序说明了多态性和继承在面向对象编程中的应用。它定义了一个类的层次结构,包括一个父类 Animal 和两个子类 Dog 和 Cat。Animal 类有一个 sound
方法,子类覆盖该方法以提供各自特定的声音行为。主方法创建了一个动物对象数组,并通过调用数组中每个元素的声音方法来演示多态行为。下面是对程序的解释:
public class Main
{public static void main(String[] args){Animal[] animals = new Animal[3];animals[0] = new Dog();animals[1] = new Cat();animals[2] = new Animal();for (Animal animal : animals){animal.sound();}}
}class Animal
{void sound(){System.out.println("Animal makes a sound");}
}class Dog extends Animal
{@Overridevoid sound(){System.out.println("Dog barks");}
}class Cat extends Animal
{@Overridevoid sound(){System.out.println("Cat meows");}
}
Dog barks
Cat meows
Animal makes a sound
24.Demonstrate interface inheritance
这个 Java 程序说明了接口的使用,以及一个类如何实现多个接口以提供不同的行为集。在这个程序中,有两个接口:Drawable 和 Resizable,以及一个实现了这两个接口的名为 Shape 的类。Shape 类为这些接口中定义的方法提供了具体实现。下面是对程序的解释:
public class Main
{public static void main(String[] args){Shape shape = new Shape();shape.draw();shape.resize();}
}interface Drawable
{void draw();
}interface Resizable
{void resize();
}class Shape implements Drawable, Resizable
{@Overridepublic void draw(){System.out.println("Drawing the Shape");}@Overridepublic void resize(){System.out.println("Resizing the Shape");}
}
在这个程序中,Shape 类实现了两个接口,即 Drawable 和 Resizable,它们提供了不同的行为集。当调用 Shape 类实例的绘制和调整大小方法时,将执行已实现接口的方法。这样,Shape 类就具有了绘制和调整大小的能力,使其成为一个由接口定义了多种行为的多功能对象。
Drawing the Shape
Resizing the Shape
25.Diamond problem in multiple inheritance
这个 Java 程序演示了当多个接口提供了一个方法的默认实现,而一个类实现了这些接口时,如何使用 super
关键字解决菱形问题。当一个类继承自两个或两个以上的类或接口,而这些类或接口都有一个同名的方法时,就会出现菱形问题。下面是对程序的解释:
public class Main
{public static void main(String[] args){D d = new D();d.display();}
}interface A
{default void display(){System.out.println("Interface A");}
}interface B extends A
{default void display(){System.out.println("Interface B");}
}interface C extends A
{default void display(){System.out.println("Interface C");}
}class D implements B, C
{@Overridepublic void display(){B.super.display(); // Resolving the diamond problem by specifying which interface's method to callC.super.display();}
}
当在 D 类的实例上调用显示方法时,它会在控制台中打印 Interface B
和 Interface C
,正如调用 B.super.display()
和 C.super.display()
所指定的那样。这演示了如何通过明确指定应调用哪个接口的方法来解决菱形问题。
Interface B
Interface C