Home Java javaTutorial What are the three major characteristics of object-oriented encapsulation? How to implement encapsulation (code example)

What are the three major characteristics of object-oriented encapsulation? How to implement encapsulation (code example)

Oct 27, 2018 pm 05:43 PM
encapsulation object-oriented

The content of this article is to introduce what are the three major features of object-oriented encapsulation? Ways to implement encapsulation (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. What is encapsulation? And why encapsulation is necessary?

Usually, you can assign some legal but unreasonable values ​​to member variables. In this case, no error will be reported or any prompt information will be given during the compilation phase and the running phase. Although this value is legal But it is inconsistent with real life; in order to avoid the above problems, member variables need to be sealed and packaged to ensure the legality and rationality of the member variables. This mechanism is called encapsulation. Encapsulation can be thought of as a protective barrier that prevents the code and data of the class from being randomly accessed by code defined by the external class. Access to the code and data of this class must be controlled through strict interfaces.

2. How to encapsulate?

(1) Privatize member variables and use the private keyword to modify them;

(2) Provide public get and set methods, judge reasonable values ​​in the method body, and use the public key Word modification;

(3) Use the set method in the construction method to judge reasonable values;

3. Examples are as follows/*Person.java*/

/*
     编程实现Person类的封装
 */
public class Person{
    //1.私有化成员变量,使用private关键字修饰
    private String name; 
    private int age;
    private String country;
    //使用static关键字修饰成员变量表示提升为类层级只有一份被所有对象共享
    //public static String country;

    //3.在构造方法中调用set方法进行合理值的判断
    public Person(){
    }
    public Person(String name, int age, String country){
        setName(name);
        setAge(age);
        setCountry(country);
    }

    //2.提供公有的get和set方法,在方法体中进行合理值的判断
    public String getName(){
        return name;
    }
    public void setName(String name){
        this.name = name;
    }
    public int getAge(){
        return age;
    }
    public void setAge(int age){
        if(age > 0 && age < 150){
            this.age = age;
        }else{
            System.out.println("年龄不合理!!!");
        }
    }
    public String getCountry(){
        return country;
    }
    public void setCountry(String country){
        this.country = country;
    }

    public void show(){
        System.out.println("我是" + getName() + ",今年" + getAge() + "岁了,来自" + getCountry() + "!");
    }

    //自定义成员方法描述吃饭的行为
    public void eat(String food){
        System.out.println(food + "真好吃!");
    }
    //自定义成员方法描述娱乐的行为
    public void play(String game){
        System.out.println(game + "真好玩!");
    }
}
Copy after login

The above is the detailed content of What are the three major characteristics of object-oriented encapsulation? How to implement encapsulation (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year Apr 17, 2024 pm 08:00 PM

According to news from this site on April 17, TrendForce recently released a report, believing that demand for Nvidia's new Blackwell platform products is bullish, and is expected to drive TSMC's total CoWoS packaging production capacity to increase by more than 150% in 2024. NVIDIA Blackwell's new platform products include B-series GPUs and GB200 accelerator cards integrating NVIDIA's own GraceArm CPU. TrendForce confirms that the supply chain is currently very optimistic about GB200. It is estimated that shipments in 2025 are expected to exceed one million units, accounting for 40-50% of Nvidia's high-end GPUs. Nvidia plans to deliver products such as GB200 and B100 in the second half of the year, but upstream wafer packaging must further adopt more complex products.

What is the importance of @JsonIdentityInfo annotation using Jackson in Java? What is the importance of @JsonIdentityInfo annotation using Jackson in Java? Sep 23, 2023 am 09:37 AM

The @JsonIdentityInfo annotation is used when an object has a parent-child relationship in the Jackson library. The @JsonIdentityInfo annotation is used to indicate object identity during serialization and deserialization. ObjectIdGenerators.PropertyGenerator is an abstract placeholder class used to represent situations where the object identifier to be used comes from a POJO property. Syntax@Target(value={ANNOTATION_TYPE,TYPE,FIELD,METHOD,PARAMETER})@Retention(value=RUNTIME)public

AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix Jul 18, 2024 am 02:04 AM

This website reported on July 9 that the AMD Zen5 architecture "Strix" series processors will have two packaging solutions. The smaller StrixPoint will use the FP8 package, while the StrixHalo will use the FP11 package. Source: videocardz source @Olrak29_ The latest revelation is that StrixHalo’s FP11 package size is 37.5mm*45mm (1687 square millimeters), which is the same as the LGA-1700 package size of Intel’s AlderLake and RaptorLake CPUs. AMD’s latest Phoenix APU uses an FP8 packaging solution with a size of 25*40mm, which means that StrixHalo’s F

Explore object-oriented programming in Go Explore object-oriented programming in Go Apr 04, 2024 am 10:39 AM

Go language supports object-oriented programming through type definition and method association. It does not support traditional inheritance, but is implemented through composition. Interfaces provide consistency between types and allow abstract methods to be defined. Practical cases show how to use OOP to manage customer information, including creating, obtaining, updating and deleting customer operations.

PHP Advanced Features: Best Practices in Object-Oriented Programming PHP Advanced Features: Best Practices in Object-Oriented Programming Jun 05, 2024 pm 09:39 PM

OOP best practices in PHP include naming conventions, interfaces and abstract classes, inheritance and polymorphism, and dependency injection. Practical cases include: using warehouse mode to manage data and using strategy mode to implement sorting.

How do C++ functions improve the efficiency of GUI development by encapsulating code? How do C++ functions improve the efficiency of GUI development by encapsulating code? Apr 25, 2024 pm 12:27 PM

By encapsulating code, C++ functions can improve GUI development efficiency: Code encapsulation: Functions group code into independent units, making the code easier to understand and maintain. Reusability: Functions create common functionality that can be reused across applications, reducing duplication and errors. Concise code: Encapsulated code makes the main logic concise and easy to read and debug.

Analysis of object-oriented features of Go language Analysis of object-oriented features of Go language Apr 04, 2024 am 11:18 AM

The Go language supports object-oriented programming, defining objects through structs, defining methods using pointer receivers, and implementing polymorphism through interfaces. The object-oriented features provide code reuse, maintainability and encapsulation in the Go language, but there are also limitations such as the lack of traditional concepts of classes and inheritance and method signature casts.

Are there any class-like object-oriented features in Golang? Are there any class-like object-oriented features in Golang? Mar 19, 2024 pm 02:51 PM

There is no concept of a class in the traditional sense in Golang (Go language), but it provides a data type called a structure, through which object-oriented features similar to classes can be achieved. In this article, we'll explain how to use structures to implement object-oriented features and provide concrete code examples. Definition and use of structures First, let's take a look at the definition and use of structures. In Golang, structures can be defined through the type keyword and then used where needed. Structures can contain attributes

See all articles