我想将默认构造函数(person1)从public更改为private,然后让用户输入信息而不是给定值。
我有两个不同的类 - 人;这是封装的,然后是测试信息的PersonTest。
class Person {
// Data Members
private String name; // The name of this person
private int age; // The age of this person
private char gender; // The gender of this person
// Default constructor
public Person() {
name = "Not Given";
age = 0;
gender = 'U';
}
// Constructs a new Person with passed name, age, and gender parameters.
public Person(String personName, int personAge, char personGender) {
name = personName;
age = personAge;
gender = personGender;
}
// Returns the age of this person.
public int getAge( ) {
return age;
}
// Returns the gender of this person.
public char getGender( ) {
return gender;
}
// Returns the name of this person.
public String getName( ) {
return name;
}
// Sets the age of this person.
public void setAge( int personAge ) {
age = personAge;
}
// Sets the gender of this person.
public void setGender( char personGender ) {
gender = personGender;
}
// Sets the name of this person.
public void setName( String personName ) {
name = personName;
}
}
import java.util.Scanner;
public class PersonTest {
// Main method
public static void main(String[] args){
// Create first instance of Person class to test the default constructor.
Person person1 = new Person();
// Create a new instance of the Person class.
Person person2 = new Person();
Scanner input = new Scanner(System.in);
// Get the values from user for first instance of Person class.
System.out.println("Person 2 Name: ");
person2.setName(input.nextLine());
System.out.println("Person 2 Age: ");
person2.setAge(input.nextInt());
System.out.println("Person 2 Gender: ");
person2.setGender(input.next().charAt(0));
// Print out the information.
System.out.println("Person 1 Name = " + person1.getName());
System.out.println("Person 1 Age = " + person1.getAge());
System.out.println("Person 1 Gender = " + person1.getGender());
System.out.println("");
System.out.println("Person 2 Name = " + person2.getName());
System.out.println("Person 2 Age = " + person2.getAge());
System.out.println("Person 2 Gender = " + person2.getGender());
System.out.println("");
}
}
答案 0 :(得分:0)
如果您不想使用默认构造函数,则不要指定一个。只要编写至少一个带参数的构造函数,Java就不会提供默认构造函数,除非你有一个。
示例:
public class AClass
{
int value = 0;
}
public class BClass
{
int value;
public BClass()
{
value = 0;
}
public BClass(int value)
{
this.value = value;
}
}
这个类有默认构造函数,你可以编写
AClass a = new AClass();
BClass b = new BClass();
获取此类的新实例。
public class CClass
{
int value;
public CClass(int value)
{
this.value = value;
}
}
此类没有default-constructor,因为至少指定了一个其他构造函数,并且没有写入default-constructor。因此
CClass c = new CClass();
将导致语法错误。
答案 1 :(得分:0)
可以从“外部”访问构造函数的主要目的之一,以便外部类可以实例化和使用您的类。你不应该将构造函数设为私有。它将无法访问,因此它的主要目的将被违反!