Object oriented design of java Foundation

Posted by cassius on Sun, 16 Jan 2022 20:09:49 +0100

11. Object oriented

The difference between object oriented and process oriented

Process oriented

The main concerns are: the specific process of implementation, causality [development idea of integrated graphics card]

Advantages: for programs with 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 by developing in a process oriented manner. In addition, the process oriented approach leads to a high degree of "coupling" between software elements. As long as one of the links goes wrong, the whole system will be affected, resulting in poor "expansion" of the final software. In addition, because there is no concept of independence, component reuse cannot be achieved.

object-oriented

The main concerns are: what functions can be completed by the main focus object [independent solid]. [development idea of independent graphics card]

Advantages: low coupling and strong expansion force. It is easier to solve the more complex business logic in the real world. Strong reusability of components.

Disadvantages: high initial investment cost, independent body extraction and a large number of system analysis and design.

C language is purely object-oriented, C + + semi object-oriented and java purely object-oriented

Three characteristics of object-oriented: encapsulation, inheritance and polymorphism

Develop a software in an object-oriented way. In the life cycle:

Object oriented analysis: OOA

Object oriented design: OOD

Object oriented programming: OOP

Overview and characteristics of object-oriented thought

Object oriented programming is based on the idea of process oriented programming

characteristic:

1. It is a kind of thought more in line with our thinking habits

2. You can simplify complex things

3. Program us from executor to commander (the role has changed)

Relationship between class and object

Classes describe the common characteristics of objects

Common features such as height

When accessing this height feature, you must first create an object to access this feature through the object.

Because the value of this feature is different after it is on a specific object. Some are 180 and some are 280

What is a class?

Concept of class

Is a collection of related properties and behaviors.

It does not exist in the real world. It is A template and A concept. It is the result of human brain thinking abstractly. (in the real world, object A and object B have common characteristics. Abstract and summarize A template, which is called class.)

Class = attribute + method

Property: describes the state information of the object

Method: describe the action information of the object

Note: when the state and action are specific to an object, the final results may be different.

There are common features between objects, but there are data differences after objects.

Class definition
Syntax structure:
[Modifier ] class Class name{
}

eg.

public class Student{

//Attribute [describes the status information of the object]
//Attributes are usually defined as variables
//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

	int no;//Student number
	String name;//name
	boolean sex;//Gender
	int age//Age
	String address;//address

//method
//Method describes the action information of the object
//The current example only describes attributes, not methods

}

Basic data type:

​ byte,short,int,long,double,float,char,boolean

Reference data type (provided by SUN or written by programmers themselves}

​ String.class,System.class,User,class...

All in the Java language class belongs to the reference data type

What is an object?

Concept of object

The object is the actual individual. In the real world.

Object creation and use

Attribute [stored data is in the form of variable]

Since variables are defined in the class body and outside the method body, such variables are called member variables

Objects are also called instances, and instance variables are also called object variables. [object level variables]

If the object is not created, the memory space of the variable does not exist. Only when the object is created, the memory space of the variable will be created

eg.

public class Student1{
	public static void main(String[] args){


		int        i       =         10;
	 //The data type variable name a literal of type int

	//N objects can be instantiated through a class
	//Syntax of instantiated object: new class name ();
	//new is an operator in the java language
	//The new operator is used to create objects and open up new memory space in the JVM heap memory

	//Method area memory: when the class is loaded, the class bytecode code fragment is loaded into the memory space
	//Heap memory: new objects are stored in heap memory

	//Student is a reference data type
	//s is a variable name
	//new Student () is a student object
	//s is a local variable [stored in stack memory]

	//What is an object: the memory space opened up by the new operator in heap memory is called an object
	//What is a reference: a reference is a variable, but this variable holds the memory address of another java object
	//In java language, programmers can only access instance variables inside objects in heap memory through "reference". You cannot directly manipulate heap memory. There are no pointers in java.

		Student s = new Student();

		//Syntax format for accessing instance variables:
		//Reading data: references Variable name
		//Modifying data: references Variable name = value

		int stNo = s.no;//Student number
		String stName = s.name;//name
		boolean  = s.sex;//Gender
		int stAge = s.age//Age
		String stAddr = s.addr;//address

		System.out.println("Student number="+stNo);
		System.out.println("full name="+stName);
		System.out.println("Age="+stSex);
		System.out.println("Gender="+stAge);
		System.out.println("address="+stAddr);

		Student stu = new Student();

		System.out.println("Student number="+stu.no);
		System.out.println("full name="+stu.name);
		System.out.println("Age="+stu.sex);
		System.out.println("Gender="+stu.age);
		System.out.println("address="+stu.addr);

}
}

Differences between member variables and local variables

Different positions in the class

Outside method in member variable class

Inside a local variable method or on a method declaration

Different locations in memory

Member variable heap memory

Local variable stack memory

Different life cycles

Member variables exist with the existence of the object and disappear with the disappearance of the object

Local variables exist with the method call and disappear with the method call

Different initialization values

Member variables have default initialization values

Local variables have no default initialization value. They must be defined and assigned before they can be used.

Differences between member variables and local variables

Summary of relevant knowledge points

1. The JVM mainly includes three memory spaces: stack memory, heap memory and method area memory.

2. There is one heap memory and one method area memory. One thread, one stack memory.

3. When a method is called, the memory space required by the method is allocated in the stack memory, which is called pressing the stack. After the method is executed, the memory space to which the method belongs is released, which is called elastic stack.

4. In the war, the local variables in the method body are mainly stored.

5. The code fragments of the method and the whole class are stored in the memory of the method area. These code fragments will be loaded when the class is loaded

6. The java object created by using the new operator during program execution patrols the heap memory. There are instance variables inside the object, and arbitrary instance variables are in heap memory

7. Variable classification:

Local variable [declared in method body]

Member variable [method declaration]

Instance variable [no static before modifier]

Static variable [static in modifier]

8. Static variables are stored in the memory of the method area

9. Among the three pieces of memory, the stack memory changes most frequently, the method area memory is the first to have data, and the garbage collector is mainly aimed at heap memory

10. When will the garbage collector [automatic garbage collection mechanism, GC mechanism] consider recycling the memory of a java object?

When the java objects in the heap memory become garbage data, they will be collected by the garbage collector

When do java objects in heap memory become garbage?

When there are no more references to it

This object cannot be accessed because the access object can only be accessed by reference.

Objects and references

Concepts of objects and references

Object: the memory space opened up in heap memory by using the new operator is called object

Reference: it is a variable, not necessarily a local variable, but also a member variable. The reference holds the memory address and points to the object in the heap memory.

All data related to accessing instances need to be accessed by reference, because objects can only be found by reference.

If there is only one null object, null pointer exception will occur when accessing the data related to the instance of the object.

Transfer of parameters

The main research and learning is how to transfer data when the method is called, which involves the problem of parameter transfer?

eg.1

int i=10;

int j=i;//When i is passed to j, it actually just passes the saved 10 in the i variable to J. J is actually a new memory space.

eg.2

User u=new User;

User u2=u;//When u is passed to u2, the memory address is actually assigned to u2. U and u2 are actually two different local variables.

eg.3

package Parameter transfer;
public class Parameter transfer {
    public static void main(String[] args) {
      User u=new User(20);
//When you pass u to the add method, you actually pass the value saved in the U variable, but this value is the memory address of a java object.
       add(u);
       System.out.println(u.age);
    }
   
    public static void add(User u){
        u.age++;
        System.out.println(u.age);
    }
}
class User{
    int age;
    public User(int age){
    	this.age=age;
    }
}

[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-elN7TAbQ-1626482468372)(C:\Users \ fantasists are too lazy to think \ appdata \ roaming \ typora \ typora user images \ image-20210716202326615. PNG)]

Formal parameter problem

When the basic parameter is a formal parameter, its actual parameters will not be affected

When the reference type is a formal parameter, its actual parameters are also affected

class Demo { 
	public int getSum(int a,int b) { 
		return a + b; 
	} 
}
class Test { 
	public static void main(String[] args) { 
		Demo d = new Demo(); 
		System.out.println(d.getSum(10,20)); 
	} 
}

//When explaining, first say we go to dinner and call the waiter's recording function, and then the waiter calls the cook's cooking function. After that, the chef calls the waiter's serving function. Finally, we'll eat it. 
class Student { 
	public void show() { 
		System.out.println("show"); 
	} 
}
class StudentDemo { 
	//If the parameter is a class name, what is actually needed is a specific object 
	public void method(Student s) { 
		s.show(); 
	} 
}
class StudentTest { 
	public static void main(String[] args) { 
		StudentDemo sd = new StudentDemo(); 
		Student s = new Student(); 
		sd.method(s); //Writing of multiple anonymous objects 
		new StudentDemo.method(new Student()); 
	} 
}

Final conclusion

When calling a method, it involves parameter passing. When passing, java only follows a syntax mechanism, that is, passing the "value" saved in the variable, but sometimes the value is a literal value of 10, and sometimes the value is the memory address of another object.

Anonymous object

Anonymous object:

It's an object without a name.

Is a simplified representation of an object

Two uses of anonymous objects

Pass as actual parameter

When an object calls a method only once

(because there is no stack memory variable pointing to the heap memory address, it directly opens up space in the heap memory. After use, it will be recycled immediately!)

1:new Student().show();
2:new StudentTest().method(new StudentDemo());

encapsulation

Benefits of encapsulation

2.1 after encapsulation, for that thing, you can't see the more complex side of the error, but only the simple side of the thing. Complexity encapsulation, providing simple operation access to the outside world. (camera: complex principle and simple operation)

2.2 only after encapsulation can a real "object" and a real "unique solid" be formed

2.3 encapsulation means that future programs can be reused. And this thing should be adaptable and can be used in any occasion.

2.4 after encapsulation, the thing itself is safe, and the security is improved [security level is improved]

Characteristics of private keyword:

1) You can modify member variables or member methods, but they can only be accessed in this class, not in external classes
2) These private modified member variables or member methods can be accessed indirectly through public methods!

Steps for encapsulation

1. All attributes are privatized and modified with the private keyword. Private means private. All modified data can only be accessed in this class

2. Provide external simple operation portals, that is, external programs must access the age attribute through these simple portals in the future:

Two public methods are provided: get and set

Modify - set

Read - get

3. Naming specification of set method:

public void set+Initial capitalization of attribute name (formal parameter){
}

eg.

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

4. Naming specification of get method:

public void set+Initial capitalization of attribute name (formal parameter){
}

eg.

public int getAge(){
	return age;
}

There are two ways to access a property:

get read set modification

setter and getter methods have no static keyword

How to call a method decorated with static keyword: class name Method name (argument);

How to call a method without static keyword modification: reference Method name (argument);

this keyword

About this keyword of java:

1 this is a keyword, meaning: this

2 this is a reference and this is a variable. The memory address stored in this variable points to itself. This is stored in the java object in the JVM heap memory.

3 create 100 java objects. Each object has this, that is, 100 different this

4this can appear in the instance method. This points to the object of the action currently being executed (this represents the current object)

5 in most cases, this can be omitted

6this cannot be used in methods with static

7this. It cannot be omitted when distinguishing local variables from instance variables

private int ID;

public void setId(int id){

	this.id=id;

}

public int getId(){

	return id;

}

this essence

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-26TqSUmr-1626482468374)(C:\Users \ visionaries are too lazy to think about \ appdata \ roaming \ typora \ typora user images \ image-20210716204158187. PNG)]

Ps. methods without static keyword are called "instance methods". How can instance methods be accessed? "Reference."

Variables without static keyword are called "instance variables"

Note: when an object needs to participate in the execution of a behavior / action, this method must be defined as an "instance method" without the static keyword

Call of this

Instance method:

public class NewClass {
    public static void main(String[] args) {
    
        NewClass.dosome();
        
        dosome();
        
        NewClass a=new NewClass();
        a.dosome2();
        
        a.sagd();
}
    public static void dosome(){
        System.out.println("1");
    }
    
    //Example method
    public void dosome2(){
        System.out.println("2");
    }
    
    
    //Instance method and calling method must have an object
    //You must create an object to call a method
    public void sagd(){
        
        //There must be a "current object" in the code execution process in braces
        //That means there must be "this"
        System.out.println("3");
        
        /*
        dosome2 Is an instance method, and the instance method call must have the existence of an object
        The meaning of the following code is to call the dosome2 method of the current object
        */
        this.dosome2();
        dosome2();//this can generally be omitted
    }
}

Instance variable:

public class This20 {
int num=1;//Instance variable
    public static void main(String[] args) {
        This20 a=new This20();
        System.out.println(a.num);
    }
}

Application scope of this

It can be used in the instance method to represent the current object [this.]

You can call other construction methods [this (argument)] through the current construction method in the construction method

Important: this () can only appear on the first line of the constructor

eg.1

public class This date {
    public static void main(String[] args) {
        //Create date object 1
        Date t1=new Date();
        t1.print();
        
        //Create date object 2
        Date t2=new Date(2000,8,24);
        t2.print();
    }
}

public class Date {
    private int year;
    private int month;
    private int day;
    
    //Construction method
    public Date(int year,int month,int day){
        this.year=year;
        this.month=month;
        this.day=day;
    }
    
    /*
    When the programmer calls the parameterless method, the default setting date is "1970-1-1"
    */
    public Date(){
        /*
        this.year=1970;
        this.month=1;
        this.day=1;
        */
        //The above code can be completed by calling another constructor
        
        //The following syntax is required to complete the call of the construction method
        //This method does not need to create new java objects, but it can call other construction methods at the same time.
        this(1970,1,1);                
    }
    //set get
    public int getYear(){
        return year;
    }
    public int getMonth(){
        return month;
    }
    public int getDay(){
        return day;
    }
    
    public void setYear(int year){
        this.year=year;
    }
    public void setMonth(int month){
        this.month=month;
    }
    public void setDay(int day){
        this.day=day;
    }
    
    //Provide a method to print the date to the console
    //Example method
    public void print(){
        System.out.println(this.year+"year"+this.month+"month"+this.day+"day");
    }
}

Construction method

About construction methods in java:

1. The construction method is also called Constructor / Constructor / Constructor

2. Syntax structure of construction method:

[Modifier list] Constructor name (formal parameter list){
	Construction method body;
}

3. Syntax structure of common methods:

[Modifier list] Return value type method name (formal parameter list){
	Method body;
}

4. For the constructor, the return value type does not need to be specified. And you can't write void. If you write void, this method will become an ordinary method.

5. For constructor, the method name of constructor must be consistent with the class name.

6. Function of construction method?

The meaning of construction method is that objects can be created through the call of construction method.

7. How to call the constructor?

Ordinary methods are called like this: class name Method name (argument list) or reference Method name (argument list)

new constructor name (argument list)

8. Is there a return value after the constructor method is called and executed?

Each constructor will actually have a return value after execution, but there is no need to write a statement such as the return value. The java program will automatically return the value. And the return value type is the type of the class in which the method is constructed. Since the return value type of the constructor is itself, the return value type does not need to be abbreviated.

9. When no constructor is defined in a class, the system provides a parameterless constructor for the class by default. This constructor is called the default constructor

10. When the constructor of a class is defined, the system will no longer provide a default constructor for this class by default. It is recommended to manually provide parameterless construction methods for the current class in development. Because the parameterless construction method is too common.

11. The construction method supports the overload mechanism. Multiple construction methods are written in a class. Obviously, these construction methods have constituted the method overload mechanism.

Function of construction method:

1 create object

2 initialize the memory space of the instance variable while creating the object. [assign value to instance variable]

Member variable value instance variable, which belongs to object level variable. This kind of variable can have instance variable only if there is an existing object

When the instance variable is not assigned manually, the system assigns the value by default. When is the default assignment completed? Is it when the class is loaded?

No, because Lei Jia only loaded code fragments when he was, and he didn't have time to create objects. Therefore, the instance object is not initialized at this time.

In fact, the memory space of the instance object is developed during the execution of the construction method. Complete initialization.

When the system assigns values by default, it also completes the assignment during the execution of the construction method.

Instance variables are stored in the heap memory of the JVM

Standard class

class

Member variable

Construction method

Nonparametric construction method

Structural method with parameters

Member method

getXxx()

setXxx()

How to assign values to member variables

Parameterless construction method + setXxx()

Structural method with parameters

eg.

class Student{
	//Property privatization
	private String name ;//full name
	private int age ; //Age
	private String gender ;//Gender
	private String sid ;  //Student number
	
	//Nonparametric construction method
	public Student(){
		
	}
	
	//Parametric construction method
	public Student(String name,int age,String gender,String sid) {
		//assignment
		this.name = name ;
		this.age = age ;
		this.gender = gender ;
		this.sid = sid ;
	}
	
	//Provide setXXX()/getXXX() methods
	//Assign a name
	public void setName(String name){
		this.name = name ;
	}
	//Get name
	public String getName(){
		return name ;
	}
	
	//Assign age
	public void setAge(int age){
		this.age = age ;
	}
	//Get age
	public int getAge(){
		return age ;
	}
	
	//Assign gender
	public void setGender(String gender){
		this.gender = gender ;
	}
	//Get gender
	public String getGender(){
		return gender ;
	}
	
	//Assign value to student number
	public void setSid(String sid){
		this.sid = sid ;
	}
	//Get student number
	public String getSid(){
		return sid ;
	}
	
	//eat
	public void eat(){
		System.out.println("Students eat nutritious meals...") ;
	}
	//sleep
	public void sleep(){
		System.out.println("When you are tired of study, you need to rest") ;
	}
	//study
	public void study(){
		System.out.println("study JavaSE...") ;
	}
}


//Test class
class StudentTest{
	public static void main(String[] args){
		
		//Test student class
		//Method 1: construct method without parameters + setXXX()/getXXX()
		Student s = new Student() ;
		s.setName("Asso") ;
		s.setAge(23) ;
		s.setGender("male") ;
		s.setSid("s007") ;
		//Get content
		System.out.println("Name is:"+s.getName()+",Age is:"+s.getAge()+",Gender is:"+s.getGender()+",The student number is:"+s.getSid()) ;
		s.eat() ;
		s.sleep() ;
		s.study() ;
		
		System.out.println("----------------------------------------") ;
		
		//Method 2: get the content by assignment + getXXX() of the parameterized construction method
		Student s2 = new Student("Li Qing",45,"male","s008") ;
		System.out.println("Name is:"+s2.getName()+",Age is:"+s2.getAge()+",Gender is:"+s2.getGender()+
		",The student number is:"+s2.getSid()) ;
		s2.eat() ;
		s2.sleep() ;
		s2.study() ;
		
		
	}
	
}

To be continued...

Topics: Java