11 object oriented class object encapsulation

Keywords: Java

1. Object oriented concept

"The object-oriented method is mainly to objectify things, including their attributes and behaviors. Object-oriented programming is closer to the idea of real life. Generally speaking, the bottom layer of object-oriented is process-oriented. Process-oriented is abstracted into classes and encapsulated for easy use. It is object-oriented (everything is object)."

Object oriented is a software development method and a programming paradigm. The concept and application of object-oriented have gone beyond program design and software development, and extended to fields such as database system, interactive interface, application structure, application platform, distributed system, network management structure, CAD technology, artificial intelligence and so on. Object oriented is a method of understanding and abstracting the real world. It is the product of the development of computer programming technology to a certain stage.
Object oriented is relative to process oriented. Object oriented method organizes the relevant data and methods as a whole, carries out system modeling from a higher level, and is closer to the natural operation mode of things.

The meaning of object refers to a specific thing, that is, something that can be seen and touched in real life. In object-oriented programming, an object refers to a component of a computer system. In object-oriented programming, object contains two meanings, one is data and the other is action. Objects are a combination of data and actions. The object can not only operate, but also record the operation results in time.

Process oriented emphasizes the process. For example, loading an elephant into a refrigerator is divided into three steps:
Step 1: open the refrigerator door
Step 2: put the elephant in
Step 3: close the refrigerator door
Object oriented emphasizes the results, such as:
What kind of refrigerator? What kind of elephant? Who is responsible for loading the elephant?

If the clothes are dirty, we can ask female basin friends to help wash them. We don't need to pay attention to how the intermediate process is washed, we can get clean clothes. Of course, we need to have an object first~~

Process oriented ---- it is a kind of thought. You should do everything yourself
Object oriented ---- an idea that focuses only on results

1.2 object oriented has three characteristics:

Encapsulation: encapsulate the relevant data into a "class" component
Inheritance: subclasses automatically share parent class properties and methods, which is a relationship between classes
Polymorphism: enhance the flexibility and reusability of software

2. Classes and objects

Type 2.1

1. The most basic unit of Java is class, which is similar to type
2. Class is the abstraction of a class of things
3. It can be understood as template or design drawing

2.2 object

Each object has three characteristics, object state, object behavior and object identification.

  1. The state of an object is used to describe the basic characteristics of an object
  2. The behavior of an object is used to describe the function of an object
  3. Object identification means that objects have a unique address value in memory to distinguish them from other objects
  4. A class is an abstraction of a class of things, and an object is a concrete implementation

2.3 relationship between class and object

  1. How does computer language describe things in the real world? Attribute + behavior
  2. How to describe it in java language?
    We can describe a kind of things through classes, use member variables to describe the attributes of things, and use methods to describe the behavior of things

2.4 common use of class

Before writing code, we need to analyze the following requirements:
For example, we should abstract things like mobile phones into code:
Then the type of this thing is "mobile phone", which can be described by classes
Class contains the common attributes and functions extracted from mobile phones

Mobile phone attributes: color, size, brand, price
Functions of mobile phone: making phone calls, sending text messages and listening to music

Object: in addition, we can also create objects, which is equivalent to mobile phones manufactured according to the drawings, such as mobile phone 1 object, which contains unique member variables and methods
We create classes with the class keyword and objects with the new keyword.
Next, let's start coding!
Open idea
Create module:
Creating packages: demo
Create class: TestPhone.java

package demo;
/**
 * This class is used for object-oriented introductory cases
 * Used to design and collect such things
 */
//1. Multiple classes can be defined in the same java file, but there can only be one public class modified by public
//  And the name of this public class is required to be the name of the current java file
public class TestPhone {
    public static void main(String[] args) {
        //4. In the main () method, create the Phone object with the new keyword
        Phone p = new Phone();
        //5. The method can be called through the object p of the mobile phone class
        p.call();
        p.message();
        p.video();
        //6. You can view the properties through the object p of the mobile phone class
        System.out.println(p.brand); //null
        System.out.println(p.color);  //null
        System.out.println(p.size);   //0.0
        System.out.println(p.price);  //0.0
        //7. Create the object p2 of the mobile phone class through the new keyword
        Phone p2 = new Phone();
        //8. Set value through p2 object
        p2. brand = "Huawei";
        p2. color = "Colorful black";
        p2. price = 88888.88;
        p2. size = 5.6;
        //9. View attribute value through p2 object
        System.out.println(p2.price);
        System.out.println(p2.brand);
        System.out.println(p2.color);
        System.out.println(p2.size);

    }
}

//1. Create a mobile phone class through the class keyword -- used to describe things such as mobile phones
//2. Similar to abstract, class abstract describes the characteristics / attributes of a class of things
//  Features: brand price color size
//  Behavior: call, send text messages and watch the live broadcast
    class Phone{
//2. Describe the characteristics / attributes / fields / member variables of a class of things through member variables -- Location: outside the method in the class
    String brand; //brand
    double price; //Price
    String color; //colour
    double size;  //size
    //3. Describe the function of a class of things through methods
    //Method format: modifier, return value type, method name (parameter list) {method body}
    public void call(){
        System.out.println("Calling*");
    }
    public void message(){
        System.out.println("Texting!");
    }
    public void video(){
        System.out.println("Watching live~");
    }
}

2.5 stored procedures of objects in memory

Java divides memory into five areas, and we focus on stack and heap.

  1. Generally speaking, local variables exist in the stack, and the memory is released after the method is executed
  2. Objects (things from new) are stored in the heap. Memory will be released only when the objects are no longer used
  3. Each heap memory element has an address value
  4. All properties in the object have default values
    TIPS: stack and queue refers to a data structure.
    Stack: FILO – First In Last Out
    Queue: FIFO – First In First Out


What happens to memory when you create an object:

  1. When creating an object, it will open up a good space in the heap: break,price, etc., store the reference type p, and put p at the bottom of the stack;
  2. Open up a space in the heap memory to store Phone objects
  3. Complete the initialization of the object and assign a default value
  4. Assign a unique address value to the initialized object
  5. Give the address value to the reference type variable p to save

2.6 process oriented

Process oriented is also a programming idea, which emphasizes that everything should be done by yourself, and each step should be done by yourself

2.7 object oriented

java is an object-oriented language
Object oriented OOP is also a programming idea. It emphasizes the results. I don't care how it is completed. I care that there are objects that can help me work; For example, if we want to eat, we don't care which cook does it. As long as there is a cook, it's OK

Type 2.8

Class refers to the Type type, which is described by the keyword class in Java
Class is the characteristics and behavior of a class of things
Therefore, we can think of a class as a template / design drawing of a class of things

2.9 object

Objects are independent and concrete instances created according to classes
A class can create multiple objects, which do not affect each other directly. We distinguish objects by their unique address

2.10 object creation process analysis

For example: Phone p = new Phone(); What happened to this sentence in memory?

  1. You can create a space in heap memory for images
  2. This object needs to be initialized
  3. After initialization, a unique address value will be generated for this object
  4. Open up a space in the stack memory to store variables of reference type Phone type p
  5. Give the address value of the object in the heap memory to the reference type variable p to save
  6. Later, you can find the objects in the heap and operate on them according to the address saved in p

3. Packaging

3.1 general

Encapsulation is to hide the properties and implementation details of objects, and only provide public access methods, such as classes and methods
Benefits:

Improve security
Improve reusability

3.2 private keyword

Is a permission modifier that can be used to modify member variables and member methods. Privatized members can only be accessed in this class

3.3 exercise: encapsulating student cases

Creating packages: demo
Create class: TestPrivate.java

package demo;

/**
 * This class is used to test the first feature of object-oriented -- encapsulation
 */
public class TestPrivate {
    public static void main(String[] args) {
        //4. Create student class object s
        Student s = new Student();
        //5. Operate the attributes and methods of student classes through objects
        System.out.println(s.name);   //Because name has no assignment, all prints are null as the initial value
        s.study();     //Learning
        //*2subject attribute in student
//        s.subject = "java learning";
//        System.out.println(s.subject);  //java learning
        //6.3 operate the subject attribute in the main method
        s.setSubject("CGB");//Set value
        System.out.println(s.getSubject());  //Print value
    }
}

//1. Describe the characteristics of students: student number name subject function: learn to eat and sleep
class Student {
    //2. Features: student number name subject --- member variable / attribute
    int sno;  //Student number
    String name;  //full name
    //*1private is a modifier. The resources modified by it can only be used in this class. It is a modifier with the least permission
    //6.1 encapsulating subjec attributes
    private  String subject;   //subject
    //6.2 we need to provide a public way for external use
    //Right click the blank line -- Generate--Getter and Setter -- to select the subject attribute
    /*If a method needs to return a result, the return value type defined by the method is no longer void,
    * As for the specific setting type, it is consistent with the type of return value
    * For example, the subject we want to return is of String type, so the return value type of the method is String
    * The return value is returned through the keyword return */


    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        //If a member variable in a class has the same name as a local variable, you need to use the this keyword to specify it. We specify that this specifies a member variable
        this.subject = subject;
    }

    //3. Function: learn to eat and sleep
    public void study(){
        System.out.println("Learning");
    }
    public void eat(){
        System.out.println("I'm eating");
    }
    public void sleep(){
        System.out.println("Sleeping");
    }
}

3.2 use of methods

package method;
/*
This category is used for the use of evaluation methods
 */
public class TestMethod {
    public static void main(String[] args) {
        //Method 1:
        int result = sum(1,5);
        System.out.println(result);

        //Method 2:
        System.out.println(sum(2,5));

        //It's not easy to use multiple times
        System.out.println(get());
        System.out.println(get()+"pagoda will stop river monster");
        //Can be used multiple times, or even concatenate strings
        String s = get();
        System.out.println(s);
        System.out.println(s+"pagoda will stop river monster");
        System.out.println(s+13135773);



    }

    //1. Define a method: function: pass in two numbers, calculate the sum of the two numbers, and return the result
    // Format: modifier return value type method name (parameter list) {method body}
    public static int sum(int a, int b){
        return a+b;
    }
    public static String get(){
        return "Heavenly King covering the earth tiger";
    }

}

3.3 comprehensive case exercises

package oop;

/**
 * This class is used for object-oriented synthesis cases
 */
public class TestCar {
    public static void main(String[] args) {
        //Create a car class object in the main method
        Car c = new Car();
        Car c2 = new Car();
        Car c3 = new Car();

        //6.1 set the car brand as "Mustang" for c object and print the set attribute value
        c.setBrand("wild horse");
        System.out.println(c.getBrand());
        //6.2 set the car price to 30w for c2 object and print the set price
        c.setPrice(300000);
        System.out.println(c.getPrice()+"element");
        //6.3 set the car color of c3 object as "green grassland", and print the set color
        c.setColor("green grassland");
        System.out.println("The color of the vehicle is"+c.getColor()+"colour");
        //6.4 get the color of c2 object and explain why it is such a printing effect
        System.out.println(c2.getColor());
        //No value has been set, so the default value is null

        c.start();
//        System.out.println(start()); resources modified by private can only be used in this class



    }
}
//1. Define a car class to describe the car type
class Car{
    //2. Define attribute - member variable
    //3. Encapsulate all attributes
    private String brand;   //brand
    private String color;   //colour
    private double length;   //Car Captain
    private int price;   //Price

    //3.2 provide SetXxx() and getXxx () for all attributes
    //Right click -- Generate--getter and setter -- press and hold shift to select all attributes

    public String getBrand() {
        return brand;
    }
    public void setBrand(String brand) {
        this.brand = brand;
    }


    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }


    public double getLength() {
        return length;
    }
    public void setLength(double length) {
        this.length = length;
    }


    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;

    }

    //4 provide car its own method
    public void start(){
        System.out.println("My car started");
        stop();
    }
    private   void stop(){
        System.out.println("My car stopped");
        //In the public method of this class, call the function of private method

    }

}

3.4 teacher case exercises

package oop;

/**
 * This class is used to practice object-oriented 2
 */
public class TestTeacher {
    public static void main(String[] args) {
        Teacher t1 = new Teacher();
        Teacher t2 = new Teacher();
        Teacher t3 = new Teacher();

        // 1. Create a teacher class object t1, the subject is CGB, and the name is bubble
        t1.setSubject("CGB");
        t1.setName("Bubble");
        System.out.println(t1.getSubject());
        System.out.println(t1.getName());
        //2. Create a teacher class object t2 with the job number of 13089 and the Department of java Teaching and research department 2
        t2.setNum(13089);
        t2.setDept("java Teaching and Research Department II");
        System.out.println(t2.getNum());
        System.out.println(t2.getDept());
        //3. Create a teacher class object t3, whose name is Taotao, job number is 10086, department is java Teaching and research department 1, and the subject is SCD
        t3.setName("Taotao");
        t3.setNum(10086);
        t3.setDept("java Teaching and research department I");
        t3.setSubject("SCG");
        System.out.println(t3.getName());
        System.out.println(t3.getNum());
        System.out.println(t3.getDept());
        System.out.println(t3.getSubject());


    }
}


//1. Define teacher class
//1.1 attribute: name, job number, subject granted by the Department and sealed
//1.2 function: lesson preparation method and teaching method
class Teacher {
    private String name;
    private int num;
    private String dept;
    private String subject;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }

    public String getDept() {
        return dept;
    }
    public void setDept(String dept) {
        this.dept = dept;
    }

    public String getSubject() {
        return subject;
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }

    //1.2 providing functions
    public void ready(){
        System.out.println("Preparing lessons");

    }
    public void teach(){
        System.out.println("Teaching in progress");

    }
}

4. Modifier

4.1 access control characters

Used to control the access scope of a class or members in a class.

TIPS:default means that the modifier is not written. By default, if you write the default word to modify it, an error will be reported

4.2 anonymous objects

An object without a name is a simplified representation of an object.
Usage scenario:
When the called object is called only once (multiple objects will be created many times, wasting memory)
Demo d = new Demo();
d.sleep();
d.game();
//This d is the name of the object.
It can also be written as:
new Demo().show(); / / creates an object calling method
new Demo().game(); / / another object calling method is created

Posted by Jason_London on Fri, 17 Sep 2021 06:20:59 -0700