JAVA object oriented

object-oriented

concept

In life:

Class is an abstract concept. We often classify things with the same characteristics and operations into one class

Order: in life, there are entities first, and then the concept of class

In the code:

Class is an abstract concept that groups objects with the same properties and methods into a column

Writing order: first have classes, and then create objects

Function of class: a class is equivalent to a template that depicts objects with the same attributes and methods

class

  1. Class has only properties and methods
  2. Attributes are also called global variables. Attributes are divided into member variables and static variables
  3. Methods are divided into member methods and static methods
public class Class name{
    //Attributes are also called global variables, which are divided into member variables and static variables
    
    //Member variable
    Data type variable name;
    
    //Static variable
    static Data type variable name;
    
    //Methods are divided into member methods and static methods
    
    //Member method
    Access modifier return value type method name([parameter]){}
    
    //Static method
    Access modifier  static Return value type method name([parameter]){}
}

give an example:

package com.dream.test01;

//human beings
public class Person {
	
	//Properties - global variables
	//Attribute classification: member variable and static variable
	//Member variable
	String name;
	char sex;
	int age;

	//method
	//Classification of methods: member methods, static methods and abstract methods
	//Member method
	public void eat(){
        //this indicates the object that calls the method, which will be specifically mentioned in the following introduction
		System.out.println(this.name + "having dinner");
	}
	
	public void sleep(){
		System.out.println(name + "sleep");
	}
}

object

Syntax for creating objects: class name object name = new class name ();

new class name (): if it belongs to an object, it will open up space in heap memory

Class name object name: the object name belongs to reference and stores the address of the object in heap memory

Operation object:

  1. Set member properties
  2. Get member properties
  3. Call member method

Test class

package com.dream.test01;

//Test class: test the code we write
//Features: there is a main method
public class Test01 {
	
	public static void main(String[] args) {
		
		//Create human objects
		Person p = new Person();
		
		//Set member variables
		p.name = "Zhang San";
		p.sex = 'male';
		p.age = 21;
		
		//Get member variable
		System.out.println(p.name);//Zhang San
		System.out.println(p.sex);//male
		System.out.println(p.age);//21
		
		//Call member method
		p.eat();//Zhang San has dinner
		p.sleep();//Zhang San sleeps
	}
}

Member properties / member variables

Syntax structure: data type variable name;

Where to write: inside the class, outside the method

Member variable vs local variable

Member variable: the variable outside the method in the class, and the system will assign a default value to act on the whole class

Local variable: a variable within a method. The system will not assign a default value and will act on the method

Member method

Syntax structure: access modifier return value type method name ([parameter]) {}

Writing location: in class

Member method vs static method

Member method: a method belonging to an object, which must be called with an object

Static method: a method belonging to a class, which is called with the class name

Construction method

Meaning: together with new, it is the function of creating objects

characteristic:

  1. Method with the same class name

  2. No items returned

be careful:

  1. When no constructor is written in the class, the system will add parameterless constructor (parameterless constructor) by default

  2. Construction methods can be overloaded

Benefits of parametric Construction: when creating an object, assign data to the object

Follow the above case

//Parametric structure
public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
}
//Nonparametric structure
public Person() {
	super();
}

private - privatization

Meaning: Privatization

effect:

  1. Modified attribute: it is a privatized attribute and cannot be used by the outside world

  2. Modification method: privatization method, which cannot be used by the outside world

Application scenario: attributes and methods that are not accessible to the outside world are decorated with private

encapsulation

Steps:

  1. Privatization attribute

  2. Add get / set method

Benefits: protect the security of attributes. The outside world cannot directly operate attributes. They must be operated through get and set methods. Special functions can be done in get and set methods

Case: simulate the class of a bank

package com.dream.test03;

import java.time.LocalDateTime;

public class User {
	
	private String userId;
	private String username;
	private String password;
	private double money;
	
	public User() {
	}

	public User(String userId, String username, String password, double money) {
		super();
		this.userId = userId;
		this.username = username;
		this.password = password;
		this.money = money;
	}

	//Get the money property of this object
	public double getMoney(){
		//Additional features
		System.out.println(LocalDateTime.now() + "Got it money Properties:" + money);
		return this.money;
	}

	//Set the money property of this object
	public void setMoney(double money){
		//Additional features
		System.out.println(LocalDateTime.now() + "Set money Properties:" + money);
		this.money = money;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}


	public String getUserId() {
		return userId;
	}


	public void setUserId(String userId) {
		this.userId = userId;
	}
}

package com.dream.test03;

public class Test01 {
	
	public static void main(String[] args) {
		
		User user = new User("1445584980", "123123", "Zhang San", 3500);
		//Withdrawal: 1 Deposit voucher 2 Modified amount
		user.setMoney(user.getMoney()-200);
		
	}

}

This - this object

Meaning: represents this object. This appears in the method and represents the object calling the method

effect:

  1. this. Property: call the member variable of this object

  2. this. Method: call the member method of this object

  3. this(): call the constructor of this object

    Note: the first sentence in one constructor calls another constructor

    For example:

    public Person() {
    		//Calling the constructor of this class is to call the constructor to initialize the object. At this time, this can only be in the first sentence. If there are other codes in front of this, an error will be reported
    		this("Xiao Hong",'female',23);
    }
    

Examples of the use of this:

package com.dream.test04;

public class Person {

	private String name;
	private char sex;
	private int age;
	
	public Person() {
		//Call the constructor of this class
		this("Xiao Hong",'female',23);
	}	
	public Person(String name, char sex) {
		this.name = name;
		this.sex = sex;
	}
	public Person(String name, char sex, int age) {
		this.name = name;
		this.sex = sex;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public char getSex() {
		return sex;
	}
	public void setSex(char sex) {
		this.sex = sex;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public void eat(){
		//this.name: call the member variable of this object
		System.out.println(this.name + "having dinner");
		//Use this object to call member methods
		this.sleep();
    }
	public void sleep(){
		System.out.println(this.name + "sleep");
	}
}

package com.dream.test04;

public class Test01 {	
	public static void main(String[] args) {	
		Person p1 = new Person();
		Person p2 = new Person("Xiao Li", 'female', 18);
		System.out.println(p1.getName());//Xiao Hong	
		p1.eat();//Xiao Hong eats and Xiao Hong sleeps
		System.out.println("-----------------");
		p2.eat();//Xiaoli eats and sleeps
		p2.sleep();	//Xiao Li sleeps
	}
}
//The output reason is that the sleep member method is called by using this in the eat member method

Static - static

effect:

  1. Modifier attribute

When a class is loaded into the method area, the JVM scans all the properties of the class
And load the static attributes into the static area. The static attributes belong to class attributes,
All objects of this class share this property
Static properties are not recycled until the end of the project

Note: static properties are called using the class name

  1. Modification method

    It belongs to a class method and is called directly with the class name

    Application scenario: tool class

  2. Static code block

    Static code block is called only when the class is loaded into the method area. This code block can only initialize static variables

    The code block takes precedence over the constructor call when creating an object. The code block can initialize member variables and static variables

    The construction method is called when the object is created. This method can initialize member variables and static variables

Member variable vs static variable

Member variable: a variable belonging to an object. Each object has an exclusive copy

Static variable: a variable belonging to a class. Each object shares one

Examples of static variables:

package com.dream.test05;

public class Person {
	String str1;
	static String str2;
}
package com.dream.test05;

public class Test01 {

	public static void main(String[] args) {

		Person p1 = new Person();
		Person p2 = new Person();
		p1.str1="aaa";
		p2.str1="bbb";
		System.out.println(p1.str1); //aaa
		System.out.println(p2.str1); //bbb
		System.out.println("--------------------");
		p1.str2="aaa";
        System.out.println(p1.str2); //aaa
		p2.str2="bbb";
        //Because str2 is defined in the Person class as a static attribute shared by all objects, the p1 call is for AAA, and the P2 call modifies the value of str2, so the subsequent output is bbb
        //In order to make it easy to see that objects share the same attribute value, the object call used here is not recommended in practice, but should be called directly with the class name
		System.out.println(p1.str2); //bbb
		System.out.println(p2.str2); //bbb
    }
}

Examples of static methods are creating a tool class

Here we create a tool class for finding the maximum, minimum and sorting of int arrays

package com.dream.work01;

public class ArrayUtils {

	double doubleArray[];
	/**
	 * Find the maximum value
	 * @param intArray
	 * @return
	 */
	public static int getMax(int intArray[]) {
		int max = intArray[0];
		for(int i = 1; i < intArray.length;i++) {
			max = (max < intArray[i])?intArray[i]:max;
		}
		return max;
	}
	/**
	 * Find the minimum value
	 * @param intArray
	 * @return
	 */
	public static int getMin(int intArray[]) {
		int min = intArray[0];
		for(int i = 1; i < intArray.length;i++) {
			min = (min > intArray[i])?intArray[i]:min;
		}
		return min;
	}
	/**
	 * Sort int array
	 * @param intArray
	 */
	public static void getSort(int intArray[]) {
		
		for(int i = 0; i < intArray.length-1;i++) {
			for(int j = 0; j < intArray.length-i-1;j++) {
				if(intArray[j] > intArray[j+1]) {
					int temp = intArray[j];
					intArray[j] = intArray[j+1];
					intArray[j+1]=temp;
				}
			}
		}
	}
}

Define a test class to test the tool class

package com.dream.test01;

import com.dream.work01.ArrayUtils;;

public class Test01 {
	
	public static void main(String[] args) {
		
		int[] is = {2,4,1,5,3,6};
		//The tool class we created is just an array of integers
		ArrayUtils.getSort(is);
		for (int i : is) {
			System.out.println(i);//1 2 3 4 5 6
		}
		int max = ArrayUtils.getMax(is);
		System.out.println(max); //6
        
		int min = ArrayUtils.getMin(is);
		System.out.println(min);//1
		
	}

}

Examples of static code blocks

package com.dream.test02;

public class A {
	
	String str1;
	static String str2;
	
	//Static code block: called when the class is loaded into the method area
	//Static variables can be initialized
	static{
		str2 = "yyy";//A.str2
		System.out.println("A Static code block for");
	}
	
	//Code block: object creation takes precedence over construction method calls
	//You can initialize static variables and member variables
	{
		str1 = "xxx";//this.str1
		str2 = "yyy";//A.str2
		System.out.println("A Code block for");
	}
	
	//Construction method: called when creating an object
	//You can initialize static variables and member variables
	public A() {
		str1 = "xxx";//this.str1
		str2 = "yyy";//A.str2
		System.out.println("A Construction method of");
	}
}

package com.dream.test02;

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

		A a1 = new A();
		A a2 = new A();
        /*
        Operation results:
        	A Static code block for
            A Code block for
            A Construction method of
            A Code block for
            A Construction method of
        */
	}
}
/*
From the running results, we can see that the program gives priority to the static code block when the new object is loaded. Because the static code block is run when the class is loaded, it is executed first. Because the class is loaded only once, the content of the static code block defining the two objects is also run only once
 The second is to execute the code in the code block. Each new object will execute the content in the code block, and then directly construct the method
*/

inherit

Usage scenario: multiple similar classes with the same attributes and methods can extract the same attributes and methods from the parent class

Benefits: reduced code redundancy

Deep inheritance:

1. When creating a subclass object, will the parent class constructor be called?
meeting
2. If you create a subclass object, will you create a parent object?
can't
3. Why do you call the parent class constructor when you create a subclass object?
The purpose is to store the properties of the parent class in the child class object

4. To create a subclass object, first call the parent class constructor or subclass constructor?
Call the subclass constructor first

5. To create a subclass object, first complete the parent class construction method or subclass construction method?
Complete the parent class construction method first

6. Can a subclass inherit the properties and methods privatized by the parent class?

Yes, but it can not be called directly, but you can set public methods in the parent class, calling private properties and methods in the public way, but only indirectly.

Parent class

package com.dream.test04;

public class A {
	
	String aAtrr;
	//Parent class privatization attribute
	private String a = "xxx";
	
	public A() {
		System.out.println("Construction method of parent class");
	}
	
	//Parent class privatization method
	private void aMethod01(){
		System.out.println("Parent class privatization method");
	}
	
	public void aMethod02(){
		System.out.println(a);
		aMethod01();
	}
}

Subclass

package com.dream.test04;

public class B extends A{
	
	String bAtrr;

	public B() {
//		super();// Call the parameterless construction of the parent class, which is implemented by default
		System.out.println("Construction method of subclass");
	}

}

Test class

package com.dream.test04;

public class Test01 {

	public static void main(String[] args) {
		
		B b = new B();/*The constructor of the subclass will be called first. Since the constructor of the subclass will implement the constructor of the parent class by default, the constructor of the parent class is called in the constructor of the subclass. Therefore, the following output results appear*/
		b.aMethod02();/*Call the public method of the parent class. The private method of the parent class is called in the public method. The private attribute subclass cannot be called directly. It can only be called indirectly in this way*/
	}
}
/*
	Output results:
        Construction method of parent class
        Construction method of subclass
        xxx
        Parent class privatization method
*/

super - parent class

Meaning: represents the parent class

Acting in subclasses:

  1. super. Property: call the non privatized member variable of the parent class
  2. super. Method: call the non privatized member method of the parent class
  3. super(): call the non privatized constructor of the parent class

give an example

Parent class

package com.dream.test05;

public class A {

	String str;
	
	public A() {
		System.out.println("A Nonparametric construction method of class");
	}
	
	public void aMethod(){
		System.out.println("A Class method");
	}	
}

Subclass

package com.dream.test05;

public class B extends A{
	
	String strB;
	public B() {
		//Call the non privatized parameterless constructor of the parent class
		super();
        System.out.println("B Class nonparametric construction");
	}
	public B(String strB) {
		super();
		this.strB = strB;
	}
	public void method(){	
		//Call the non privatized property of the parent class
		super.str = "xxx";	
		//Call the non privatized method of the parent class
		super.aMethod();
	}
	public void method1() {
		System.out.println(str);
	}
}

Test class

package com.dream.test05;

public class Test01 {
	
	public static void main(String[] args) {
		B b = new B("strB"); /*new Object, call the construction method first. At this time, there are parameters, so call the parameterized construction. Because there is super() in the parameterized construction, and super() calls the parameterless construction of the parent class, the sentence "class A parameterless construction method" will be output first, and then "strB" will be assigned to the member variable in the b object */
		System.out.println(b.strB);//strB
		System.out.println(b.str);//Null at this time, the str object of the parent class has not been initialized, and there is only one null, which is the default value given by the program
		b.method();//Call the method method of the subclass, assign the value to str, and then call the aMethod method of the parent class to output the method of class A.
		System.out.println("---------");
		b.method1();//xxx calls the subclass's method to output the str variable  
	}
}
/*
	Output results:
		A Nonparametric construction method of class
        strB
        null
        A Class method
        ---------
        xxx
        xxx
*/

rewrite

Meaning: rewriting is also called replication, which rewrites the methods in the parent class in the child class

Application scenario: when the parent method does not meet the needs of the child, the child can repeat the parent method

An @ Override annotation is usually added to the rewritten method, so that we and the program can clearly know that this method is a rewritten method

Conditions:

  1. Override the method of the parent class in a subclass

       2. The return value, method name and parameter list must be consistent with the method overridden by the parent class
    		3. The access modifier cannot be more restrictive than the method overridden by the parent class(If the parent class method is used public Modifier, then methods overridden in subclasses cannot be used private protected To decorate)
    

Access modifier

Meaning: modifies classes, methods and attributes, and defines the scope of use

Learning: doing experiments

Access modifier This categoryThis packageOther steamed stuffed bun subclassesOther packages
privateOK
defaultOKOK
protectedOKOKOK
publicOkOKOKOk

Object

Meaning: a base class is also called a superclass. Object is the ancestor of all classes

Note: if a class has no explicitly inherited parent class, it inherits Object by default

equals: compares whether the memory addresses of two objects are the same

hashCode: get the hash value of the object

getClass: gets the bytecode file object of the class

toString: gets the string representation of the object

Benchmarking: as the parent class of all classes, Object defines several methods to facilitate child classes to override

Benchmark function of equals: compare whether two objects are the same, and the comparison rules of different objects are different, so subclass can be overridden

Benchmarking function of toString: each subclass has different properties. Rewriting toString directly prints all properties in the object to facilitate data observation

final

Meaning: Final

effect:

  1. Decorated class: this class cannot be inherited

  2. Modifier method: this method cannot be overridden

  3. Modified variable: becomes a constant and cannot be re assigned

    Naming rules of constants: all uppercase, words separated by underscores

    Declaration cycle of constant: it exists in the constant pool and will not be destroyed until the end of the project

Abstract classes and abstract methods

//abstract class
public abstract class Class name{
    //Abstract method
    public abstract void method();
}

Abstract methods are implemented (overridden) by non Abstract subclasses

Application scenario: when a method must appear in the parent class, but the method is difficult to implement, turn the method into an abstract method and hand it over to a non Abstract subclass for implementation

Interview questions:
1. An abstract class cannot have a constructor?

Abstract classes can have constructors

2. Only abstract methods can exist in an abstract class?

There are non abstract methods (member methods and static methods) in abstract classes

3. An abstract class cannot have no abstract methods?

Abstract classes can have no abstract methods, but they are meaningless

4. If the parent class is an abstract class, the child class must implement the abstract method of the parent class?

Not necessarily. If the subclass is an abstract class, it can not implement the abstract method of the parent class

5. You can use the new keyword to create abstract class objects?

No, an object of an anonymous inner class is created

Interface

Meaning: special abstract class

be careful:

  1. JDK1.7, the interface can only have static constants and abstract methods
  2. JDK1. Starting from 8, there are static constants, abstract methods and default methods in the interface

Application scenario: the interface is more like a specification

Abstract class vs interface

Abstract classes: member variables, static variables, static constants, member methods, and static methods

Interface: static constant, static method, default method (JDK1.8)

Interview questions:

1. Can a class implement multiple interfaces? sure

2. Can one interface implement multiple interfaces? No, the relationship between interfaces is multi inheritance

3. The methods in the interface are not necessarily abstract? JDK1. At 7:00, there can only be abstract methods in the interface, jdk1 8-hour interface can have abstract methods and default methods

4. Does the interface solve the single inheritance problem of classes? Yes, because classes and classes are single inheritance, and classes and interfaces are multi implementation

5. Can a class inherit a class and implement multiple interfaces at the same time? sure

6. The interface can be a new object? An interface is a special abstract class, but its essence is still an abstract class. An abstract class cannot be a new object, and an interface cannot be a new object. New is an object of an anonymous class

Class interface relationship:
Class - class: single inheritance
Class interface: multiple implementations
Interfaces - Interfaces: multi inheritance

Keywords: Java

Added by whatsthis on Mon, 03 Jan 2022 03:25:22 +0200