Java中的getter/setter方法和建構函式有什麼區別?
建構函式
Java中的建構函式類似於方法,它在建立類的物件時被呼叫,通常用於初始化類的例項變數。建構函式與它們的類名相同,並且沒有返回型別。
如果不提供建構函式,編譯器會代表你定義一個建構函式,該建構函式會將例項變數初始化為預設值。
你也可以透過建構函式接受引數,並使用給定值初始化類的例項變數,這些被稱為引數化建構函式。
示例
下面的Java程式包含一個名為student的類,它使用預設建構函式和引數化建構函式初始化其例項變數name和age。
import java.util.Scanner;
class Student {
private String name;
private int age;
Student(){
this.name = "Rama";
this.age = 29;
}
Student(String name, int age){
this.name = name;
this.age = age;
}
public void display() {
System.out.println("name: "+this.name);
System.out.println("age: "+this.age);
}
}
public class AccessData{
public static void main(String args[]) {
//Reading values from user
Scanner sc = new Scanner(System.in);
System.out.println("Enter the name of the student: ");
String name = sc.nextLine();
System.out.println("Enter the age of the student: ");
int age = sc.nextInt();
Student obj1 = new Student(name, age);
obj1.display();
Student obj2 = new Student();
obj2.display();
}
}輸出
Enter the name of the student: Krishna Enter the age of the student: 20 name: Krishna age: 20 name: Rama age: 29
getter和setter方法
在定義POJO/Bean物件(或封裝類的變數)時,我們通常:
將所有變數宣告為私有。
提供公共方法來修改和檢視它們的值(因為你不能直接訪問它們)。
用於設定/修改類的私有例項變數值的方法稱為setter方法,用於檢索私有例項變數值的方法稱為getter方法。
示例
在下面的Java程式中,**_Student_**(POJO)類有兩個變數name和age。我們透過將它們設為私有並提供setter和getter方法來封裝這個類。
如果你想訪問這些變數,你不能直接訪問它們,你只能使用提供的setter和getter方法來讀寫它們的值。你沒有為其提供這些方法的變數將完全隱藏在外部類之外。
import java.util.Scanner;
class Student {
private String name;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void display() {
System.out.println("name: "+getName());
System.out.println("age: "+getAge());
}
}
public class AccessData{
public static void main(String args[]) {
//Reading values from user
Scanner sc = new Scanner(System.in);
System.out.println("Enter the name of the student: ");
String name = sc.nextLine();
System.out.println("Enter the age of the student: ");
int age = sc.nextInt();
//Calling the setter and getter methods
Student obj = new Student();
obj.setName(name);
obj.setAge(age);
obj.display();
}
}輸出
Enter the name of the student: Krishna Enter the age of the student: 20 name: Krishna age: 20
正如你所看到的,建構函式和setter/getter方法的主要區別在於:
建構函式用於初始化類的例項變數或建立物件。
setter/getter方法用於賦值/更改和檢索類的例項變數的值。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP