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