Java_ Object oriented 02: Encapsulation

Keywords: Java

What is encapsulation

Hide some information of the class inside the class and do not allow external programs to access it directly.

This class provides specific methods to realize the operation and access to hidden information.

In short

Hide object information

Interface accessed at the same time

Just like an atm machine, you can't see how much money there is, and you can hide the important information of money. At the same time, card inserting port, operation screen and note taking port are reserved. When you use it, you don't care where the money in the cash dispenser exists and how to deposit it. It not only ensures the safety of banknotes, but also realizes the functionality.

characteristic:

Important data can only be accessed through specified methods

Hide the instance details of the class to facilitate modification and implementation

java implementation encapsulation

Modifying the visibility of attributes can only be accessed within a class, but this class cannot be accessed

Set up an open interface

  Judge the legitimacy of input, such as gender can only be male or female, age can only be numbers, etc

  Example: for example, the age of a pet cat cannot be - 3, which can be realized through encapsulation

idea can automatically create getter s and setter s  

 

  If I only create getter s but not setter s for this property, it means that this property is read-only.

If only setter s are created for this property and no getter s are created, this property can only be written in.

You can optimize programs in getter s and setter s through exception handling, which will be described later.

package com.company;

public class CatTest {
    public static void main(String[] args){
        Cat one = new Cat();
        one.setName("Fanfan");
        System.out.println(one.getName());
        one.setMonth(-3);
        if (one.getMonth()==0)
            //retrun next, end the program directly
            return;
        System.out.println(one.getMonth());
    }
}
package com.company;
/*
*Pet cats
* @auther dongdong
* */
public class Cat {
    //Member attributes: nickname, age, weight, variety
    //Modify attribute visibility -- private restriction can only be accessed within the current class
    private String name;//name
    private int month;//Age
    private double weight;
    private String species;

    //Create get and set methods
    //Add a qualification to the property in the get and set methods
    public void setName(String name){
        this.name = name;
    }

    public String getName(){
        return "I'm a bird named"+this.name+"My cat";
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        if (month<0)
            System.out.println("The age entered is wrong, it should be>0");
        else
            this.month = month;
    }

    //Method: run and eat
    //Running method
    public void run(){
        this.eat();
        System.out.println("Kitten, run");
    }
    public void run(String name){
        System.out.println(name+"Run");
    }
    //How to eat
    public void eat(){
        System.out.println("Kittens eat fish");
    }
}

  Note: if the constructor with parameters is set, the value of - 3 will still be passed in when instantiating

Therefore, it is recommended to write this when writing a constructor with parameters.

 

 

package com.company;

public class CatTest {
    public static void main(String[] args){
        Cat one = new Cat();
        one.setName("Fanfan");
        System.out.println(one.getName());
        one.setMonth(3);
        if (one.getMonth()==0)
            //retrun next, end the program directly
            return;
        System.out.println(one.getMonth());
        //Verify the relationship between the constructor with parameters and setter
        Cat two = new Cat(-3);
        System.out.println(two.getMonth());
    }
}

 

package com.company;
/*
*Pet cats
* @auther dongdong
* */
public class Cat {
    //Member attributes: nickname, age, weight, variety
    //Modify attribute visibility -- private restriction can only be accessed within the current class
    private String name;//name
    private int month;//Age
    private double weight;
    private String species;

    //Create get and set methods
    //Add a qualification to the property in the get and set methods
    public void setName(String name){
        this.name = name;
    }

    public String getName(){
        return "I'm a bird named"+this.name+"My cat";
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        if (month<0)
            System.out.println("The age entered is wrong, it should be>0");
        else
            this.month = month;
    }

    public Cat(){}
    public Cat(int month){
//        this.month = month;
        this.setMonth(month);
    }
    //Method: run and eat
    //Running method
    public void run(){
        this.eat();
        System.out.println("Kitten, run");
    }
    public void run(String name){
        System.out.println(name+"Run");
    }
    //How to eat
    public void eat(){
        System.out.println("Kittens eat fish");
    }
}

Java file management

Package and class

java files are managed by package to solve the problem of file conflict with the same name

In java, classes with the same name are not allowed under a package. If you want to store two Cat classes, you need to store them under different classes.

Naming rules for packages:

Package means the operation of creating a package,

The package statement must be placed on the first line

It means that the cat class below is placed in the package.

The principle of single function is also applied in the package. We put the pet bag related classes in the pet bag, the robot cat related classes in the machine bag, and the test related classes in the test bag.  

 

  be careful:

1. It must be placed in the first line of the java source file

2. There can only be one package statement in a java source file

3. All package names are in English and lowercase

4. Naming method: domain name in reverse order + module + function

Several forms of cross package call

Three forms

  

  be careful

  This kind of class writing will lead to errors because it is impossible to distinguish which package you are importing

The solution is to change one of the imports to *, and Cat will find the Cat class with clear import. To find the robot Cat, you can only find that class by package name and class name. It has nothing to do with the order of import statements.

  Note that import com.imooc. *; This can only be loaded into the classes under imooc. There are no classes in this folder, and the classes in the package below will not be found layer by layer.

package com.imooc.test;
//import com.imooc.animal.*;// Indicates that in the current class, I want to load all classes in the animal package
import com.imooc.animal.Cat;//Represents a specific class that loads animal in the current class
import com.imooc.mechanics.*;
import com.imooc.animal.CatTest;
//import com.imooc.*;

public class Test {
    public static void main(String[] args){
        Cat cat = new Cat();
        //Directly load the package name and class name when the program is running
//        CatTest tex = new CatTest();
//        com.imooc.animal.CatTest tex = new com.imooc.animal.CatTest();
        com.imooc.mechanics.Cat mechanicscat =new com.imooc.mechanics.Cat();
    }
}
package com.imooc.mechanics;

public class Cat {
    public Cat(){
        System.out.println("im a mechaice cat");
    }
}
package com.imooc.animal;
/*
*Pet cats
* @auther dongdong
* */
public class Cat {
    //Member attributes: nickname, age, weight, variety
    //Modify attribute visibility -- private restriction can only be accessed within the current class
    private String name;//name
    private int month;//Age
    private double weight;
    private String species;

    //Create get and set methods
    //Add a qualification to the property in the get and set methods
    public void setName(String name){
        this.name = name;
    }

    public String getName(){
        return "I'm a bird named"+this.name+"My cat";
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        if (month<0)
            System.out.println("The age entered is wrong, it should be>0");
        else
            this.month = month;
    }

    public Cat(){
        System.out.println("I'm a pet cat");
    }

    public Cat(int month){
//        this.month = month;
        this.setMonth(month);
    }
    //Method: run and eat
    //Running method
    public void run(){
        this.eat();
        System.out.println("Kitten, run");
    }
    public void run(String name){
        System.out.println(name+"Run");
    }
    //How to eat
    public void eat(){
        System.out.println("Kittens eat fish");
    }
}

 

  System common package

  Static keyword

  Static static information

What information can static be combined with

What are the characteristics of static modification

  Members (properties) decorated with static

Members decorated with static are called static members or class members.

features:

1. Class object sharing

No matter how many objects this class instantiates, class members will share the same memory space.

 

  Two different objects are instantiated, but the price is the same, because static is set for the price.

  2. It is generated from the first loading of the class and released when destroyed, with a long life cycle

Static members are best called with static methods

Two access methods, either by object name or class name.

  static modification method

  Modify methods, class methods and member methods with static

It also has two kinds of call methods, class name call and object call. Class name calling is recommended

  Several points needing attention:

static cannot modify a class name

static cannot fix local variables

Static methods cannot directly access non static members in the same class, but can only call static members in the same class

If you want to access, you can only access non static members by instantiating the object. Member method

In member methods, you can directly access static members in a class

 

In fact, it is also well understood. Through debug, it is found that when calling static modified methods, there are only static members in memory. After instantiation, there are other things

 

You can debug to see the changes in memory. It's very interesting.

package com.imooc.test;
import com.imooc.animal.Cat;//Represents a specific class that loads animal in the current class

public class Test {
    public static void main(String[] args){
        Cat one = new Cat();
        one.prise = 2000;
        Cat two = new Cat();
        two.prise = 150;
        Cat.prise =3000;
        System.out.println(one.getName()+one.prise);
        System.out.println(two.getName()+two.prise);
        Cat.eat();
    }
}
package com.imooc.animal;
/*
*Pet cats
* @auther dongdong
* */
public class Cat {
    //Member attributes: nickname, age, weight, variety
    //Modify attribute visibility -- private restriction can only be accessed within the current class
    private String name;//name
    private int month;//Age
    private double weight;
    private String species;

    //Static member, class member
    public static int prise;

    //Create get and set methods
    //Add a qualification to the property in the get and set methods
    public void setName(String name){
        this.name = name;
    }

    public String getName(){
        return "I'm a bird named"+this.name+"My cat";
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        if (month<0)
            System.out.println("The age entered is wrong, it should be>0");
        else
            this.month = month;
    }

    public Cat(){
        System.out.println("I'm a pet cat");
    }

    public Cat(int month){
//        this.month = month;
        this.setMonth(month);
    }

    public Cat(String name){
        this.setName(name);
    }
    //Method: run and eat
    //Running method
    //In member methods, you can directly access static members in a class
    public void run(){
        eat();
        this.name="Niu Niu";
        this.prise=20;
        System.out.println(this.name+"Kitten, run"+"Your value"+Cat.prise);
    }
    //How to eat
    public static void eat(){
        //Static methods cannot directly access non static members in the same class, but can only call static members in the same class
        //If you want to access, you can only access non static members by instantiating the object. Member method
        Cat cat = new Cat();
//        cat.run();
        cat.name="Little fat";
        prise = 10;
        System.out.println("Kittens eat fish");
    }
}

Knowledge about code blocks

The code in java programs is enclosed in curly braces, {} pairs of curly braces are called code blocks.

Common code block and construction code block and static code block

When this code block appears in a method, it is called a normal code block.

When contemporary code blocks appear directly in a class, it is called constructing code blocks.

 

  When the construction code block is modified by the static keyword, it becomes a static code block

 

The static code block is executed only once no matter how many times the instance is. The constructed code block is not instantiated and executed once.

According to the above characteristics, static code blocks and construction code blocks are often used to attach initial values to attributes.

  The same static code block can only assign initial values to static attributes, and the constructed code block can assign values to two attributes.

Because static code will only be called once no matter how many times it is instantiated. What code we want to execute only once can be placed in static code blocks.

package com.imooc.animal;
/*
*Pet cats
* @auther dongdong
* */
public class Cat {
    //Member attributes: nickname, age, weight, variety
    //Modify attribute visibility -- private restriction can only be accessed within the current class
    private String name;//name
    private int month;//Age
    private double weight;
    private String species;

    //Static member, class member
    public static int prise;

    {
        name = "Newton";
        prise = 100;
        System.out.println("I'm building blocks");
    }
    static {
        prise = 200;
//        name = "little fat"// report errors
        System.out.println("I'm a static code block");
    }
    //Create get and set methods
    //Add a qualification to the property in the get and set methods
    public void setName(String name){
        this.name = name;
    }

    public String getName(){
        return "I'm a bird named"+this.name+"My cat";
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        if (month<0)
            System.out.println("The age entered is wrong, it should be>0");
        else
            this.month = month;
    }

    public Cat(){
        System.out.println("I'm a pet cat");
    }

    public Cat(int month){
//        this.month = month;
        this.setMonth(month);
    }

    public Cat(String name){
        this.setName(name);
    }
    //Method: run and eat
    //Running method
    //In member methods, you can directly access static members in a class
    public void run(){
        eat();
        this.name="Niu Niu";
        this.prise=20;
        System.out.println(this.name+"Kitten, run"+"Your value"+Cat.prise);
    }
    //How to eat
    public static void eat(){
        //Static methods cannot directly access non static members in the same class, but can only call static members in the same class
        //If you want to access, you can only access non static members by instantiating the object. Member method
        Cat cat = new Cat();
//        cat.run();
        cat.name="Little fat";
        prise = 10;
        System.out.println("Kittens eat fish");
    }
}

Variable scope

  Two variables with the same name cannot appear in the same scope.

Principle of proximity:

  The reason why we can define a variable with the same name in code block 1 and code block 2 is that the variable temp will also die with the end of code block 1. The lifetime of temp is only within the curly braces of code block 1. After the curly braces are completed, temp is recycled.

Just remember that the lifetime of the variable is the curly bracket of the code block.

 

 

Posted by hnissani on Fri, 03 Sep 2021 15:46:09 -0700