如何在Java中完全封装一个对象?


将数据和作用于数据的代码封装在一起的过程称为封装。这是一种保护机制,我们通过它隐藏一个类的数据,使其无法被另一个类(的对象)访问。

由于变量保存类的变量,因此要封装一个类,您需要将所需的变量(您想要隐藏的变量)声明为私有,并提供公共方法来访问(读取/写入)它们。

通过这样做,您只能在当前类中访问变量,它们将对其他类隐藏,并且只能通过提供的方法访问。因此,它也被称为数据隐藏。

完全封装类/对象

要完全封装一个类/对象,您需要

  • 将类中所有变量声明为私有。
  • 提供公共的setter和getter方法来修改和查看它们的值。

示例

在下面的 Java 程序中,**Student** 类有两个变量 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

更新于: 2020年7月2日

313 次查看

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.