Data field encapsulation, JavaSE

1. Introduction

Objects outside the class that defines the private data domain cannot access this data domain. But there are often situations where the client needs to access and modify the data field. In order to be able to access the private data field, a get method can be provided to return the value of the data field. In order to be able to update a data field, a set method can be provided to set a new value for the data field. The get method is also called an accessor, and the set method is called a modifier.
The getRadiusO method returns the radius value. The setRadius(newRadius) method sets a new radius for the object. If the new radius is negative, the radius of the object is set to 0. Because these methods are the only way to read and modify the radius, you have complete control over how to access the radius property. If the implementation of these methods must be changed, there is no need to change the client program that uses them. This will make the class easier to maintain.

2. Code

Implementation class

package com.zhuo.demo;

public class CircleWithPrivateDataFields {
    
    
    private double radius = 1;
    private static int numberOfObjects = 0;
    CircleWithPrivateDataFields() {
    
    
        numberOfObjects++;
    }
    CircleWithPrivateDataFields(double newRadius) {
    
    
        radius = newRadius;
        numberOfObjects++;
    }
    public void setRadius(double newRadius) {
    
    
        radius = newRadius > 0 ? newRadius : 0;
    }
    public double getRadius() {
    
    
        return radius;
    }
    public static int getNumberOfObjects() {
    
    
        return numberOfObjects;
    }
    public double getArea() {
    
    
        return radius * radius * Math.PI;
    }
}

Test class

package com.zhuo.demo;

public class TestCirclePrivateDataFields {
    
    
    public static void main(String[] args) {
    
    
        CircleWithPrivateDataFields mycircle = new CircleWithPrivateDataFields(5.0);
        System.out.println("半径为" + mycircle.getRadius() + "的圆的面积为" + mycircle.getArea());
        mycircle.setRadius(mycircle.getRadius() * 1.1);
        System.out.println("半径为" + mycircle.getRadius() + "的圆的面积为" + mycircle.getArea());
        System.out.println("创建的对象数量为" + CircleWithPrivateDataFields.getNumberOfObjects());
    }
}

Three. Running results

半径为5.0的圆的面积为78.53981633974483
半径为5.5的圆的面积为95.03317777109125
创建的对象数量为1

Process finished with exit code 0


Guess you like

Origin blog.csdn.net/weixin_42768634/article/details/113836388