2021 big data learning journey JavaSE · object oriented (class, object, encapsulation, construction method)

preface

The series of articles is more suitable for non science students. From shallow to deep, step by step, and embark on the road of big data from the foundation

Let's work together to achieve our goals and realize our ideals

Finally, please leave your little ❤, Give me a little encouragement

1, Object oriented thought

1.1 overview of object-oriented thought

summary

Java language is an object-oriented programming language, and object-oriented idea is a programming idea. Under the guidance of object-oriented idea, we use java language to design and develop computer programs.

The object here generally refers to all things in reality, and each thing has its own attributes and behavior. The object-oriented idea is the design idea of abstracting the attribute characteristics and behavior characteristics of things and describing them as computer events (class attributes and behaviors) with reference to real things in the process of computer programming.

Different from the process oriented idea, it emphasizes that the function is realized by calling the behavior of the object, rather than operating and realizing it step by step.


The difference between process oriented and object-oriented

Process oriented: it is constructed according to causality, and there is no unique concept [development idea of integrated graphics card]

  • Advantages: for programs with relatively simple business logic, rapid development can be achieved, and the early investment cost is low
  • Disadvantages: it is difficult to solve very complex business logic. In addition, the process oriented approach leads to a very high degree of coupling between software elements. As long as there is a problem in one link, the whole system will be affected, resulting in poor software expansion. And component reuse cannot be achieved

Object oriented: dividing the real world into different objects, focusing on the independent individual, what action the individual can perform, and the degree of correlation between them is weak.

  • Advantages: low coupling, strong expansion ability, easier to solve complex logic
  • Disadvantages: high initial cost, requiring a lot of system analysis and design

Three characteristics of object-oriented

  • encapsulation
  • inherit
  • polymorphic

All object-oriented programming languages have these three characteristics (java is a pure object-oriented language). Object oriented thinking is an idea that is more in line with our thinking habits. It can simplify complex things and turn us from executor to commander.

To develop a software in an object-oriented way, there are three links in the life cycle (need to be clearly distinguished):

  • Object oriented Analysis: OOA (Analysis)
  • Object oriented design: OOD (Design)
  • Object oriented Programming: OOP (Programming)

give an example

wash clothes:

> Process oriented: take off your clothes-->Because we have to put our clothes together-->Find a basin-->Because I'm going to start washing clothes-->Put some washing powder-->Add some water....
> Object oriented: take off your clothes-->Turn on the automatic washing machine-->Throw clothes-->Button-->Let it dry

difference:

  • Process oriented: emphasize steps.

  • Object oriented: emphasize the object. The object here is the washing machine.


1.2 classes and objects

Looking around, you will find many objects, such as tables, chairs, cars, motorcycles and so on. Tables and chairs belong to office supplies, and cars and motorcycles belong to vehicles. So what is a class? What is an object?


What is a class

Class: class does not exist in the real world. It is A template, A concept, and the result of human brain thinking abstractly. Class represents A class of things, which is A set of related attributes and behaviors. In the real world, object A and object B have common characteristics. They abstract and summarize A series of attribute + behavior templates, which are called classes

In reality, describe a class of things:

  • Attribute: is the state information of the thing.
  • Behavior: is what the thing can do.

What is an object

Object: it is the concrete embodiment of a kind of things. The object is the actual individual, which actually exists in the real world. An object is an instance of a class (the object is not the object in the object), which must have the properties and behavior of this kind of things.


A software development process:

  • Observe the real world and find objects from the real world
  • After searching for N objects, it is found that all objects have common characteristics
  • Abstract to form a template [class]
  • java programmers express a class through java code
  • There are class definitions in java programs
  • Then you can instantiate the creation object through the class
  • With objects, multiple objects can cooperate to form a system

Class -- > [instantiation] – > object (instance) instance

Object -- > [Abstract] – > class


1.3 definition of class

[Modifier list]  class  Class name { 
    Attributes; //It is usually defined in the form of a variable
          //In the class body, variables defined outside the method body are called member variables`
          //The member variable has no assignment, and the system assigns a default value: everything is in line with 0
    method;
}

All class es belong to the reference data type
The modifier list here does not have static

  • Define class: defines the members of a class, including member variables and member methods.
  • Member variables (attributes): almost the same as previously defined variables. It's just that the location has changed. In a class, outside a method.
  • Member method (method): it is almost the same as the previously defined method. Just remove static. The function of static will be explained in detail later in the object-oriented part.

give an example

public class Student {
	//Member variable
  	String name;//full name
    int age;//Age

    //Member method
    public void study() {
    	System.out.println("study hard and make progress every day");
	}

	public void eat() {
		System.out.println("Full and strong");
	}
}

1.4 creation and use of objects

Create object:

Class name object name = new Class name();

Use objects to access properties and methods in a class:

Object name.Member variables;
Object name.Member method();

Example Part 1

//Create a template for the student class
//It describes the common characteristics of all students: state and behavior

//Create class body
public class Student{
    int age; //age cannot be accessed directly through the 'class' and needs to create objects, so this kind of member variable is also called instance variable
    String name; //If you don't create an instance, it won't occupy memory. Only when you create an object will this instance variable create space
    int num;
    Boolean sex;
    //Create method
    public void study(){
		System.out.println("Learning big data");
	}
}

Part 2

//create object
public class InstanceTest {
    public static void main (String[] args) {
        //Syntax of instantiated object new class name ();
        //The new operator is used to create objects and open up new memory space in the JVM heap memory
        //Review: load the class file into the memory of the method area; When executing method fragments, press the stack -- > out of the stack in the stack memory
        //Local variable -- stack memory
        //new object -- heap memory
        //After new creates the instance object, the corresponding member variable already exists in the heap memory, and the value is the default value
        Student xiaohong = new Student ();
        xiaohong.study();
    }
}

Default value of member variable

data typeDefault value
Basic typeInteger (byte, short, int, long)0
Basic typefloat, double0.0
Basic typeCharacter (char)'\u0000'
Basic typebooleanfalse
reference typeArray, class, interfacenull

1.5 class and object exercises

Define a mobile phone class with brand, price and color attributes, and create a method to implement it
1. use..Brand...Price...Call someone with a colored mobile phone
2. Display all properties of the phone
3. Reset all properties of the phone at the same time

reference resources

public class Phone{
    String brand; //brand
    double price; //Price
    String color; //colour

    public void phoneCall(String name){
        System.out.println("use"+brand+","+price+"Yuan,"+color+"Give me your cell phone"+name+"phone");
    }

    public void showProperty(){
        System.out.println(brand+","+price+","+color);
    }
    
    public void setProperty(String b, double p, String c){
        color = c; //Don't use this for the time being, I'll learn later
        price = p;
        brand = b;
    }
}
//Test class
public class OOTest {
    public static void main(String[] args) {
        Phone x = new Phone();
        x.showProperty(); //What is the output of thinking
        x.setProperty("Huawei", 999.99, "Chinese Red");
        x.showProperty(); 
        x.phoneCall("Zhang San");
    }
}

1.6 object memory diagram

An object that calls a method memory graph

From the above figure, we can understand that the method of running in stack memory follows the principle of "first in, last out, last in, first out". The variable p points to the space in the heap memory, looks for the method information, and executes the method.

However, there are still problems. When creating multiple objects, if a method information is saved inside each object, it will be a waste of memory, because the method information of all objects is the same. So how to solve this problem? Please see the diagram below.


Memory map of two objects calling the same method

When an object calls a method, find the method information in the class according to the method tag (address value) in the object. In this way, even if there are multiple objects, only one copy of method information is saved to save memory space.


1.7 differences between member variables and local variables

Variables are given different names according to their definition positions. As shown in the figure below:

The difference between local variables and member variables

  1. Different positions in the class [ key ]
    Member variable: in class, outside method
    Local variable: in method or on method declaration (formal parameter)
  2. Different initialization values [ key points ]
    Member variables: have default values
    Local variable: no default value. Must first define, assign, and finally use
  3. Different scope of action [ key ]
    Member variables: in classes
    Local variables: in method
  4. Different locations in memory (understand)
    Member variables: heap memory
    Local variables: stack memory
  5. Different life cycles (understanding)
    Member variable: exists with the creation of the object and disappears with the disappearance of the object
    Local variable: exists with the method call and disappears with the method call

Proximity access principle of variables

When using a variable, first find out whether there is this variable in the local range. If it is used directly, if it is not found in this class or parent class (you can understand this class first), if it is used directly, if it is not directly reported as an error.


2, Encapsulation

2.1 package overview

summary

The external variables cannot be modified directly in the external programming world and the internal variables cannot be manipulated directly in the external programming world. Encapsulation can be considered as a protective barrier to prevent the code and data of this class from being freely accessed by other classes. To access the data of this class, you must use the specified method. Proper encapsulation can make the code easier to understand and maintain, and also strengthen the security of the code.

Note: hide the property. If you need to access a property, you need to provide public methods to access it

2.2 steps of packaging

  1. Use the private keyword to decorate member variables.
  2. For the member variables to be accessed, provide a corresponding pair of getXxx methods and setXxx methods.

2.3 specific operation of encapsulation - private keyword

Meaning of private

  1. private is a permission modifier that represents the minimum permission.
  2. You can modify member variables and member methods.
  3. Member variables and member methods modified by private can only be accessed in this class.

Use format of private

private	data type	Variable name;

give an example

Modify member variables with private:

public class Student {
	private String name;
	private int age;
}

Provide it with getXxx method / setXxx method, which can access the member variable:

public class Student {
	private String name;
	private int age;

	public void setName(String n) {
		name = n;
	}

	public String getName() {
		return name;
	}

	public void setAge(int a) {
		age = a;
	}

	public int getAge() {
		return age;
	}
}
be careful: set/get The initial letter of the following variable name needs to be capitalized, which needs to be followed JavaBean Code standard

What to remember:

  • setter and getter methods have no static keyword
  • How to call a method decorated with static keyword: class name Method name (argument);
  • Method without static keyword modification: reference Method name (argument);

2.4 package optimization 1 - this keyword

We found that the formal parameter name in setXxx method does not meet the requirement of knowing the meaning by name. If the modification is consistent with the member variable name, is it known by name? The code is as follows:

public class Student {
	private String name;
	private int age;
	public void setName(String name) {
		name = name;
	}

	public void setAge(int age) {
		age = age;
	}
}

According to the nearest access principle of variables, we found a new problem. After modifying the formal parameter variable name of setXxx(), the method did not assign a value to the member variable! This is because the formal parameter variable name is the same as the member variable name, resulting in the member variable name being hidden, and the variable name in the method cannot access the member variable, so the assignment fails. Therefore, we can only use this keyword to solve the problem of duplicate names.


The meaning of this

this represents the reference (address value) of the current object of the class, that is, the reference of the object itself. this is stored in the object in heap memory by default, and saves the address value of the object, pointing to the object.

Remember: the object to which the method is called depends on the object in the method this It represents that object. That is, who is calling, this Who does it represent

this use format

this.Member variable name;

Use the variables in this modification method to solve the problem that member variables are hidden

public class Student {
	private String name;
	private int age;

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

	public String getName() {
		return name;
	}

	public void setAge(int age) {
		//age = age;
		this.age = age;
	}

	public int getAge() {
		return age;
	}
}

Tip: when there is only one variable name in the method (for example, public void() {name}), it is decorated with this by default. This can be omitted.


2.5 package optimization 2 - construction method

When an object is created, the constructor is used to initialize the object and assign the initial value to the member variable of the object.

Construction method statement structure

[modifier list]   construction method name (formal parameter list){
  structural method body
}

Review the general method structure

[modifier list]   return value type   method name (formal parameter list){
  structural method body
}

For the corresponding construction method, the type of the return value does not need to be specified, and void cannot be written. As long as void is added, it becomes an ordinary method

For the method name of the construction method, it must be consistent with the class name


Construction methods are divided into nonparametric construction methods and parametric construction methods. Nonparametric construction methods are also called default constructors

It should be noted that:

  1. If you do not provide a construction method, the system will give a parameterless construction method by default.
  2. If you provide a construction method (which can be parameterless / parameterless), the system will no longer provide a parameterless construction method.
  3. The construction method can be overloaded, and parameters can be defined or not.
  4. It is recommended to manually provide parameterless construction methods for the current class during development.

give an example

class Teacher {
    private String id; //Privatization of member variables
    private String name;

	//Nonparametric construction method
    public Teacher() { 
    }
	
	//Parametric construction method
    public Teacher(String id, String name) { 
        this.id = id;
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

2.6 quick creation of integrated development environment

IDEA (including other integrated development environments) provides automatic generation of default constructors, parametric construction methods, getter and setter methods, etc., in the following order:

  1. Right click – > generate in the code area (or shortcut Alt+Insert)
  2. Select the Constructor or Getter and Setter
  3. Select the desired parameters
    Nothing is selected as the default constructor for generation

    Select parameter -- > OK to generate a parameterized construction method

    Getter and setter -- > select all -- > OK generates the corresponding operation method of private member variables

It is particularly important to write these methods by yourself. Remember that you can't rely entirely on the IDE


3, Standard code – JavaBean

JavaBean is a standard specification of classes written in Java language. Classes that conform to JavaBean are required to be concrete and public, have parameterless construction methods, and provide set and get methods for operating member variables.

public class ClassName{
  //Member variable
  //Construction method
  //Nonparametric construction method [required]
  //Parametric construction method [suggestion]
  //Member method	
  //getXxx()
  //setXxx()
}

Write classes that conform to JavaBean specifications. Take student classes as an example. The standard code is as follows:

public class Student {
	//Member variable
	private String name;
	private int age;

	//Construction method
	public Student() {}

	public Student(String name,int age) {
		this.name = name;
		this.age = age;
	}

	//Member method
	publicvoid setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	publicvoid setAge(int age) {
		this.age = age;
	}

	publicint getAge() {
		return age;
	}
}

Test:

public class TestStudent {
	public static void main(String[] args) {
		//Use of parameterless construction
		Student s= new Student();
		s.setName("Zhang San");
		s.setAge(18);
		System.out.println(s.getName()+"---"+s.getAge());

		//Use of parametric construction
		Student s2= new Student("Li Si",28);
		System.out.println(s2.getName()+"---"+s2.getAge());
	}
}


summary


There are all series of articles on the home page in the upper left corner!

The best way to eradicate poverty is to learn big data with me. Come on, Ollie!

Please give me a compliment when you see here!

Keywords: Java Big Data JavaSE

Added by rochakchauhan on Sun, 30 Jan 2022 11:50:42 +0200