[英]In Java, is there any way to call this() and super() in same constructor?
我有两个类,如下所示。 我想在单个构造函数 TestEmployee() 中访问 this() 和 super() 构造函数。 当前方法无法编译。 Java 中有没有其他方法可以在同一个构造函数的主体中同时调用 this() 和 super()。
class Employee{
double salary;
Employee(double salary){
this.salary = salary;
}
}
class TestEmployee extends Employee{
TestEmployee(){
super(1000000);
this(10000);
}
double bonus;
TestEmployee(double bonus){
this.bonus = bonus;
}
}
显然不行,super和this都必须是构造函数体的第一条语句。而且只能有一个第一条语句
这是没有意义的,因为TestEmployee
有一个薪水,它被传入并发送到基类Employee
因为TestEmployee
派生自Employee
。 奖金是补偿的一个单独部分,将单独存储。 理想情况下,您将在Employee
基类中有一个不同的构造函数,它允许传递TestEmployee
可以访问的salary
和bonus
。
正如其他人所说,您无法按照自己尝试的方式完全按照自己的意愿行事。 但是,您可以做的是稍微不同地设计您的类,以便您可以实现相同的目标。
class Employee{
double salary;
Employee(double salary){
this.salary = salary;
}
}
class TestEmployee extends Employee{
TestEmployee(double salary, double bonus){
super(salary);
this.bonus=bonus;
}
double bonus;
}
然后,如果你想要一个默认的 TestEmployee 构造函数,你可以这样做:
TestEmployee() {
this(1000000,10000);
}
为了防止代码重复,您可以定义一个非静态方法,该方法为所有构造函数执行所有初始化块。您可以在调用 super() 之后包含此方法以初始化您的对象。但缺点是..它可以从类中的任何其他方法调用。所以这不是一个好的设计模式
class TestEmployee extends Employee{
double bonus;
TestEmployee(){
super(1000000);
intialize(10000);
}
TestEmployee(double bonus){
super(bonus);
intialize(bonus);
}
private void intialize(double bonus)
{
this.salary = bonus;
}
}
你不能把这两个调用放在同一个构造函数中,因为在调用父类时,它们都需要首先放在构造函数中。 当你有一个额外的参数时,你可以在同一个构造函数中使用 this 和 super 。 就像在这个例子中:
class TestEmployee extends Employee{
double: age;
TestEmployee(double salary, double age){
super(1000000);
this.age=age;
}
Or when you are using a Chaining Constructor, for example:
public class Employee{
String name;
double salary;
double age;
public Employee()
{
this("James Bond", 34000);
}
public Employee(String n, double s)
{
this("Ana", 34000, 23);
}
public Employee(String n, double s, double age)
{
name = n;
salary = s;
this.age=age;
}
正如其他人所说,你为什么要这样做。 这没有道理。
您可以通过调用另一个构造函数来伪造它,该构造函数又调用其超类构造函数。 但是,如果调用另一个构造函数的唯一原因是传递到另一个超类构造函数而不是隐式调用的构造函数,那么几乎可以肯定您的设计存在严重错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.