Wood Chen

Object Encapsulation

0 comments74 views110 words

This post was translated from Chinese by AI. If anything reads oddly, the Chinese original is authoritative. 中文原文

Access control keywords: default(default),,,public(public),,,protected(protected),,,private(private)   1.default  ——————package-private If no keyword is specified, default access is assigned. Other classes in the same file can access it directly.   2.public-----------public There are no access restrictions. Any Java class can access it directly from anywhere. Declaring an attribute or method with this keyword makes it public rather than encapsulating it. Only members declared with this keyword are guaranteed to be directly accessible by any other class or object anywhere in a Java program.   3.protected  —————protected Similar to default access, but slightly stricter.   4.private ————private Only this provides encapsulation in the strict sense.  

/* Define a cube class———Cube */

class Cube{

    int superficialColor;        //Default access modifier

    private  double edgeLength;        //The edge length variable is private and cannot be accessed outside the class

    protected   double weight;        //Weight has protected access, similar to default access

    public void setEdgeLength( double edge ){

 //A public method for setting the cube's edge length

        edgeLength = edge;

        return;

}

    public double sperficialArea(){

     //A public method for calculating this cube's surface area from anywhere

    return 6edgeLengthedgeLength;

}

}

Last updated 2024-01-14

Related posts

Comments 0