int i; Student s; i++; //WRONG: i has to be initialized. s.toString(); //WRONG: s has to be initialized. /////////////////////////////////////////////////// int i = 0; Student s = null; i++; s.toString(); /*This will pass compiling, but during the runtime, s.toString() will throw NullPointerException because s has not be constructed.*/ //////////////////////////////////////////////////// Student s = new Student("Paul Sun"); s.toString(); //This is ok. ///////////////////////////////////////////////////// //Now, we look at the Student Class: public class Student { private String m_strName; public Student(String name) { m_strName = name; } public String toString() { return "Student name: " + m_strName; } } /* //This is the Constructor: public Student(String name) { m_strName = name; } */ Constructor does two things: 1. Reserve memory space for the Object. 2. Initialize values for member Field. Even though 2 is not necessory. A default Constructor is a Constructor without any parameters like the following. public Student() { m_strName = new String(); }
类的构造方法,简单说就是和类同名的方法,用于初始化变量 例如: class a { a(){ System.out.println("Great"); } } 其中方法a()就是构造方法
如果想使用一个类的属性或方法,就需要一个该类的实例。(静态方法除外) 而构造方法,就是用来构造该类的实例的方法。 简单的理解,就是先使用构造方法获得实例,然后通过该实例调用类的属性或方法。 举个例子: class Car { String 油箱状态;
public Car(){ 油箱状态; = "空"; } public void 加油(){ 油箱状态 = "满"; } public void 检查油箱(){ System.out.println("当前的油箱状态为:" + 油箱状态); } }class A { Car car = new Car(); car.检查油箱(); car.加油(); car.检查油箱(); };
Student s;
i++; //WRONG: i has to be initialized.
s.toString(); //WRONG: s has to be initialized.
///////////////////////////////////////////////////
int i = 0;
Student s = null;
i++;
s.toString();
/*This will pass compiling, but during the runtime, s.toString() will throw NullPointerException because s has not be constructed.*/
////////////////////////////////////////////////////
Student s = new Student("Paul Sun");
s.toString();
//This is ok.
/////////////////////////////////////////////////////
//Now, we look at the Student Class:
public class Student
{
private String m_strName;
public Student(String name)
{
m_strName = name;
}
public String toString()
{
return "Student name: " + m_strName;
}
}
/*
//This is the Constructor:
public Student(String name)
{
m_strName = name;
}
*/
Constructor does two things:
1. Reserve memory space for the Object.
2. Initialize values for member Field.
Even though 2 is not necessory.
A default Constructor is a Constructor without any parameters like the following.
public Student()
{
m_strName = new String();
}
例如:
class a
{
a(){
System.out.println("Great");
}
}
其中方法a()就是构造方法
而构造方法,就是用来构造该类的实例的方法。
简单的理解,就是先使用构造方法获得实例,然后通过该实例调用类的属性或方法。
举个例子:
class Car
{
String 油箱状态;
public Car(){
油箱状态; = "空";
}
public void 加油(){
油箱状态 = "满";
} public void 检查油箱(){
System.out.println("当前的油箱状态为:" + 油箱状态);
}
}class A
{
Car car = new Car();
car.检查油箱();
car.加油();
car.检查油箱();
};