访问量: 10 次浏览
在Java中,super指向父类,为了将一个类继承到另一个类中,我们使用 extends 关键字。
在编写Java程序以使用构造函数分配和初始化超类成员之前,让我们通过本篇文章中要使用的一些概念。
当用户没有创建任何构造函数时,Java编译器将自动创建一个(我们称之为默认构造函数)。
public class Constructor_example {
Constructor_example() {
// 构造函数
// 要执行的代码
}
}
public class Cnst {
Cnst(){
// 构造函数
System.out.println("我是构造函数");
}
public static void main(String[] args) {
Cnst obj = new Cnst();
// 调用构造函数
}
}
我是构造函数
this 关键字用于区分同一类方法的本地变量与实例变量,而 super 关键字用于区分超类成员与子类成员。this 关键字用于调用当前类的方法、构造函数和变量,而 super 关键字用于调用基类的方法和构造函数。下面的示例说明了 this 关键字的用法。
public class Main {
String name = "Your name";
Main(String name) {
// 构造函数
this.name = name;
// 表示Main构造函数的变量
System.out.println(name);
}
public static void main(String[] args) {
Main obj = new Main("Tutorialspoint");
}
}
Tutorialspoint
在上面的代码中,我们创建了一个带有 string 类型参数 name 的带参数的构造函数 Main 。
因此,在调用构造函数时,我们使用了参数“Tutorialspoint”。
下面的示例说明了 super 关键字的用法。
class Tutorialspoint {
String name="Your name";
}
public class Tutorix extends Tutorialspoint {
String name = "My name";
public void show() {
// 访问Tutorix的局部变量
System.out.println("访问基类名称:" + super.name);
// 访问Tutorix的局部变量
System.out.println("访问子类名称:" + name);
}
public static void main(String[] args) {
Tutorix obj = new Tutorix();
obj.show();
}
}
访问基类名称:Your name
访问子类名称:My name
在上述代码中,类 Tutorix 继承类 Tutorialspoint 。
在子类 Tutorix 的 show() 方法中,我们使用 super 关键字尝试访问其父类 Tutorialspoint 的变量 name 。
在main方法中,我们使用 new 关键字创建了 Tutorix 类的对象,并使用该对象调用了 show() 方法。
class P {
String item_name;
int rate;
int quantity;
P(String item_name, int rate, int quantity) { // 父类的构造函数
this.item_name = item_name;
this.rate = rate;
this.quantity = quantity;
System.out.println("我是超类构造函数");
System.out.println("我包含 " + item_name + " " + rate + " " + quantity);
}
}
public class C extends P {
// 使用extends关键字继承父类
C(String status) {
// 子类的构造函数
super("Milk", 60, 2);
// 分配值给父类成员
System.out.println("我是子类构造函数");
System.out.println(status);
}
public static void main(String[] args) {
C obj = new C("paid"); // 调用子类构造函数
}
}
我是超类构造函数
我包含Milk 60 2
我是子类构造函数
paid
在上面的代码中,我们创建了一个父类 P ,其中包含三个变量和一个构造函数及三个参数。
类 C 是 P 的子类。在 C 中,我们使用 super 关键字将值分配给父类 P 。
在本篇文章中,我们了解了构造函数与普通方法的区别,以及 this 和 super 关键字的用法。
最后,我们创建了一个Java程序,以使用构造函数分配和初始化超类成员。