Introduction to Java programming tutorial--object creation process

error sample program

A sample program of the creation process of an object in the case of inheritance.

 

Example program analysis

       This example cannot be compiled correctly through Java , and the error shown above occurs because an error occurred when executing the Square construction method.

       Java stipulates that the construction method of the subclass needs to be backtracked to execute the construction method of the parent class before it is actually executed.

       Since the Square class is a subclass of the Rectangle class, when the system executes: Square square = new Square (10);, it first executes the construction method of the parent class Rectangle class. By default, it executes the empty construction method of the parent class. In this example, the Rectangle class has already defined an explicit construction method of type Rectangle ( int a,  int b) , so the system will no longer generate a default empty construction method for the Rectangle class, so that no matching method can be found when the program is running. Empty constructor of parent class.

solution one


Add an empty constructor to the parent class

class Rectangle {  
   ...
   Rectangle ( ) { } //Method 1: Add an empty constructor
   Rectangle (int a, int b){width =a; height=b;}
   ...
}


solution two


The construction method of the subclass clearly indicates the type of the parent class construction method to be executed
class Square extends Rectangle {     ...     public Square(int a)     { super(a,a); ... } //Method 2: specify the specific construction method of the parent class to be executed     ... }





 

 

Guess you like

Origin blog.csdn.net/u010764893/article/details/131140135