我正在使用Java作爲初學者,我正在學習一個教程(http://www.javatpoint.com/object-and-class-in-java),其中指出可以通過三種不同的方式將對象初始化爲java。在Java中通過三種不同方式初始化對象有什麼用途?
- 通過引用變量
- 通過方法
- 通過構造
我的問題是,什麼是使用三種不同的方法對單個任務的意義。
實施例: 1)對象和類示例:初始化通過參考
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
2)對象和類示例:初始化通過方法
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
3)對象和類示例:初始化通過構造函數
class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}
嗯,是什麼?.....你有代碼示例爲1,2,3來顯示你的意思,因爲我不完全是你在說什麼 – Antoniossss
你能解釋你到底需要什麼嗎? – Akshay
問題更新 – jax