Java中的继承和构造函数
Java中的构造函数用于初始化对象的属性值,以使Java更接近现实世界。我们已经有一个默认构造函数,如果在代码中没有找到构造函数,它会自动调用。但是如果我们让任何构造函数说参数化构造函数来初始化一些属性,那么它必须写下默认构造函数,因为它现在将不再被自动调用。
Note: In Java, constructor of the base class with no argument gets automatically called in the derived class constructor.
例子:
Java
// Java Program to Illustrate
// Invokation of Constructor
// Calling Without Usage of
// super Keyword
// Class 1
// Super class
class Base {
// Constructor of super class
Base()
{
// Print statement
System.out.println(
"Base Class Constructor Called ");
}
}
// Class 2
// Sub class
class Derived extends Base {
// Constructor of sub class
Derived()
{
// Print statement
System.out.println(
"Derived Class Constructor Called ");
}
}
// Class 3
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an object of sub class
// inside main() method
Derived d = new Derived();
// Note: Here first super class constructor will be
// called there after derived(sub class) constructor
// will be called
}
}
Java
// Java Program to Illustrate Invokation
// of Constructor Calling With Usage
// of super Keyword
// Class 1
// Suoer class
class Base {
int x;
// Constructor of super class
Base(int _x) { x = _x; }
}
// Class 2
// Sub class
class Derived extends Base {
int y;
// Constructor of sub class
Derived(int _x, int _y)
{
// super keyword refers to super class
super(_x);
y = _y;
}
// Method of sub class
void Display()
{
// Print statement
System.out.println("x = " + x + ", y = " + y);
}
}
// Class 3
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating object of sub class
// inside main() method
Derived d = new Derived(10, 20);
// Invoking method inside main() method
d.Display();
}
}
输出
Base Class Constructor Called
Derived Class Constructor Called
输出说明:这里将调用第一个超类构造函数,然后调用派生(子类)构造函数,因为构造函数调用是从上到下的。是的,如果我们的 Parent 类正在扩展任何类,那么该类的主体将在之后执行,直至派生类。
但是,如果我们想调用基类的参数化构造函数,那么我们可以使用 super() 来调用它。需要注意的一点是基类构造函数调用必须在派生类构造函数的第一行。
实现: super(_x) 是第一行派生类构造函数。
Java
// Java Program to Illustrate Invokation
// of Constructor Calling With Usage
// of super Keyword
// Class 1
// Suoer class
class Base {
int x;
// Constructor of super class
Base(int _x) { x = _x; }
}
// Class 2
// Sub class
class Derived extends Base {
int y;
// Constructor of sub class
Derived(int _x, int _y)
{
// super keyword refers to super class
super(_x);
y = _y;
}
// Method of sub class
void Display()
{
// Print statement
System.out.println("x = " + x + ", y = " + y);
}
}
// Class 3
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating object of sub class
// inside main() method
Derived d = new Derived(10, 20);
// Invoking method inside main() method
d.Display();
}
}
输出
x = 10, y = 20