java - 如何在Java中使用构造函数

标签 java constructor

public class Person{

    public static void main(String[] args){
        //Class constructor
        Person(String name, String status, int Age){
            this.name = name;
            this.status = status;
            this.Age = Age;
        }
        //Object creation
        Person one = new Person("John", "Single", 18);
        Person two = new Person("Kez", "Single", 21);
        Person three = new Person("Bob", "Married", 31);

        //Print out attributes
        System.out.println("Person one Profile: %s/t%s/t%d", +one.name,    +one.status, +one.Age);
        System.out.println("Person two Profile: %s/t%s/t%d", +two.name, +two.status, +two.Age);
        System.out.println("Person three Profile: %s/t%s/t%d", +three.name, +three.status, +three.Age);
    }
}

我的代码可能有什么问题? 编译器警告的错误并不能帮助我理解问题。

最佳答案

您的代码有 5 个问题。首先,变量应该以小写字母开头,所以我将 Age 更改为 age。其次,您的构造函数不应位于 main 方法中。第三,您需要 printf 而不是 println。您还需要去掉那些 + 符号。 + 是一个运算符,需要 2 个 String(两侧各一个),而不仅仅是一个 String。最后,我假设您的意思是 \t 而不是 /t。我已经改变了这一点,还添加了两个换行符。

更正后的代码为

public class Person {

    private String name;
    private String status;
    private int age;

    Person(String name, String status, int age){
        this.name = name;
        this.status = status;
        this.age = age;
    }

    public static void main(String[] args) {
        //Object creation
        Person one = new Person("John", "Single", 18);
        Person two = new Person("Kez", "Single", 21);
        Person three = new Person("Bob", "Married", 31);

        //Print out attributes
        System.out.printf("Person one Profile: %s\t%s\t%d\n", one.name, one.status, one.age);
        System.out.printf("Person two Profile: %s\t%s\t%d\n", two.name, two.status, two.age);
        System.out.printf("Person three Profile: %s\t%s\t%d", three.name, three.status, three.age);
    }
}

关于java - 如何在Java中使用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29810393/

相关文章:

java - 自定义输入格式,hadoop

java - 在 Java 中转换时在 C 代码中出现指针和 if 语句错误

c++ - 将右值引用传递给类构造函数的意义是什么?

javascript - 无法在构造函数原型(prototype)中调用 'this'

java - 创建新的 Java 项目,java 首选项不可用

java - 将参数传递给 JDBC PreparedStatement

java - 使用JPA和Hibernate时equals和hashcode应该如何实现

c++ - 将 auto_ptr 作为参数传递给构造函数

c# 编译器错误 CS1526 : A new expression requires (), [], or {} after type

c++ - 为什么这是这个程序的输出?