构造函数调用必须是构造函数中的第一个语句 - 即使我已经使用了第一个语句

问题描述 投票:0回答:2

下面的代码有什么问题吗? 为什么我无法在第一个语句中调用 this() 方法? 封装 oopsConcepts;

公开课测试{

int age;
int salary;
int amount;
private int marks;

public Testing Testing(int age, int salary, int amount) {
    this.age = age;
    this.salary = salary;
    this.amount = amount;
    marks = 200;
    return this;
}

public int Testing(int age, int salary) {
    // this(23,9999,140);
    this.age = age;
    this.salary = salary;
    return 50;

}

public Testing Testing() {
    this(23, 9999);
    // System.out.println("Hey dude default constructor");
    return this;
}

public static void main(String[] args) {

    Testing t1 = new Testing();

    t1.Testing().Testing(32, 45678);
    System.out.println(t1.age);
    System.out.println(t1.salary);
    System.out.println(t1.amount);
    System.out.println(t1.marks);

}

}

解决上述代码中的错误。 了解如果构造函数只有 this 的返回类型如何调用 this() 。

java constructor this
2个回答
0
投票

enter image description here

附图供参考


0
投票

构造函数没有返回类型。您必须将它们写成

public Testing() {...}
,而不是
public Testing Testing(){...}
public int Testing() {...}
,并且您一定不能从它们返回值,例如
return 50;
甚至
return this;

© www.soinside.com 2019 - 2024. All rights reserved.