Java object oriented review

Posted by amy_ewe on Mon, 03 Jan 2022 04:04:00 +0100

Java object oriented learning

Source of learning materials: Alibaba cloud University Java object-oriented programming Magic Music Technology Software School
Other notes will be updated in this note: Java learning notes

1. Class and object

1.1 introduction to object oriented

Encapsulation: internal operations are not visible to the outside

Inheritance: continue to expand functions on the basis of existing structures;.

Polymorphism: an extended concept based on inheritance, which refers to the conversion of types.

1.2 class and object introduction

A class is a template, and an object is an instance that a class can use. There are classes before objects.

Class composition:

  • Member properties (Field)
  • Operation Method

1.3 use of classes and objects

*1.4 object memory analysis

New: used to open up new space

For memory analysis, first give the two most commonly used memory spaces:

  • Heap memory: it stores the specific information of the object. In the program, the development of heap memory space is completed through new

  • Stack memory: the address of a heap memory is saved, that is, the heap memory is found through the address, and then the object content is found. However, for analysis and simplification, it can be simply understood as: the object name is saved in stack memory

All objects can only be executed after instantiation. The NulPointerException exception in the program is a problem after there is no heap memory, and this problem exists only in the reference data type.

*1.5 object reference analysis

Class itself is a reference data type. Since it is a reference data type, it involves memory reference passing. The essence of the so-called reference passing: the same heap memory space can be pointed to by different stack memories or changed.

  • Reference passing

Person per1 = new Person();
Person per2 = per1 ;

Reference passing can occur on a method. At this time, you must observe the parameter type of the method and the pointing process of the method.

1.6 reference and waste generation analysis

The so-called garbage space means that there is no heap memory space pointed to by any stack memory. All garbage will be recycled regularly by GC and useless memory will be released. However, too much garbage will affect GC.

2 in depth analysis of classes and objects

2.1 member attribute encapsulation

  • Use private to decorate attributes
  • Use setXXX() and getXXX() methods to access properties

2.2 construction methods and anonymous objects

**Construction method: * * you can use the construction method to initialize the attributes in the instantiated object

  • The constructor name must be consistent with the class name;
  • The constructor cannot set any return value type, that is, there is no return value definition;
  • The constructor is automatically called when instantiating an object with the keyword new.
  • Java sets a parameterless constructor by default

**Overload of construction method: * * only the number and type of parameters need to be considered, and others remain unchanged

Anonymous object: if the value is operated by instantiating an object, this form of object is called anonymous because it has no name.

new Person("zhangsan",10); / / anonymous object

At this time, the tell() method in the class is still called through the object, but since the object does not have any reference name, the object will become garbage once used, and all garbage will be recycled and collected by GC.

3 this keyword

3.1 this class attribute is called by this

In the program code you write later, you must add "this" whenever you access the properties in this class.

3.2 this class method is called

The following important issues should be paid attention to for the mutual call of this class's construction methods:

  • The constructor must be called when instantiating a new object, so the statement "this()" can only be placed on the first line of the constructor
  • When constructors call each other, please keep the exit of the program so as not to form an endless loop;

3.3 simple Java classes

  • Class names must be meaningful and can clearly describe a class of things;.
  • All properties in the class must be encapsulated in private, and the encapsulated properties must be provided with setter and getter methods.
  • There can be countless constructors in a class, but the parameterless constructors must be preserved
  • No output statement is allowed in the class, and all contents must be returned;

4 static keyword

4.1 declare static attribute

The static property can be called directly by the class name.

Although the static attribute is defined in the class, it is not controlled by the class instantiation object. The static property can be used when no object is instantiated

When considering public information storage, use static. It's kind of like a global variable

4.2 declaring static methods

  • Static method only allows calling static property or static method;
  • Non static methods allow you to call static properties or static methods;
  • this cannot be used in static methods

Static defined methods or properties are not what you need to consider at the beginning of code writing. You will only consider using static defined methods or properties when avoiding instantiation object calls and describing public properties.

5 code block

5.1 common code block

The main feature of common code block is the code block defined in a method.

5.2 building blocks

The construction block takes precedence over the execution of the construction method, and the code in the construction block of the new object is instantiated every time.

Execution results:

aaaaaaa
hhhhhh
aaaaaaa
hhhhhh

5.3 static code block

Static code blocks take precedence over construction blocks and are executed only once for static attribute initialization.

6 object oriented case analysis

7 array

7.1 array reference passing analysis

Array is a reference type. You must make space in the heap to use it.

7.2 array common function library

Sorting: arrays sort();

Copy: system arraycopy();

7.3 method variable parameters

Example: public int sum(int... data) {} / / the number of parameters is variable and still belongs to the array in essence

7.4 object array

The elements in an array are objects, and such an array is an object array.

8 practical application of reference passing

8.1 class association structure

class Car{
	private String name;
	private double price;
	private Person person ;
	
	public Car(String name, double price) {
		this.name = name;
		this.price = price;
	}
	public String getInfor(){
		return "License plate:"+name+" Price"+price;
	}
	// setter getter
	public Person getPerson() {
		return person;
	}
	public void setPerson(Person person) {
		this.person = person;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
}

class Person{
	private String name;
	private int age;
	private Car car;
	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	public String getInfor() {
		return "Owner:"+name+" Age: "+age;
	}
	// setter getter	
	public String getName() {
		return name;
	}
	public Car getCar() {
		return car;
	}
	public void setCar(Car car) {
		this.car = car;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}


public class Test {
	public static void main(String[] args) {
		Person person = new Person("Zhang San", 20);
		Car car = new Car("Rolls-Royce", 80000000);
		// Create Association
		person.setCar(car); // A man has a car
		car.setPerson(person); // A car belongs to one person
		// Get data according to relationship
		System.out.println(person.getCar().getInfor()); // Car information
		System.out.println(car.getPerson().getInfor()); // Owner's information
	}
}

*8.2 self association

class Car{
	private String name;
	private double price;
	private Person person ;
	public Car(String name, double price) {
		this.name = name;
		this.price = price;
	}
	public String getInfor(){
		return "License plate:"+name+" Price"+price;
	}
	// setter getter
	public Person getPerson() {
		return person;
	}
	public void setPerson(Person person) {
		this.person = person;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
}

class Person{
	private String name;
	private int age;
	private Car car;
	private Person[]  children;  // One person has many children
	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	public String getInfor() {
		return "Owner:"+name+" Age: "+age;
	}
	// setter getter
	public Person[] getChildren() {
		return children;
	}
	public void setChildren(Person[] children) {
		this.children = children;
	}
	public String getName() {
		return name;
	}
	public Car getCar() {
		return car;
	}
	public void setCar(Car car) {
		this.car = car;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}


public class Test {
	public static void main(String[] args) {
		Person person = new Person("Zhang San", 20);
		Car car = new Car("Rolls-Royce", 80000000);
		Person childA = new Person("Son", 12);
		Person childB = new Person("daughter", 10);
		childA.setCar(new Car("bmw", 30000)); // Anonymous object
		childB.setCar(new Car("audi", 40000)); // Anonymous object
		person.setChildren(new Person[]{childA,childB}); // A man has children	
		// Create Association
		person.setCar(car); // A man has a car
		car.setPerson(person); // A car belongs to one person
		// View a person's child information and a child's car
		for(int i = 0; i<person.getChildren().length;i++){
			System.out.println("name:"+person.getChildren()[i].getName());
			System.out.println("\t "+person.getChildren()[i].getCar().getInfor());
		}
	}
}

9 datagram and simple Java class mapping transformation

9.1 datagram and simple Java class mapping transformation

9.3 many to many mapping

12 definition and use of inheritance

12.1 derivation of inheritance issues

The essence of inheritance: continue to expand on the basis of the original class

12.2 implementation of inheritance

A subclass is also called a derived class, and a parent class is called a superClass

extends

12.3 subclass object instantiation process

super() refers to the statement that the subclass construction calls the parent construction. This statement is only allowed to call the parameterless construction in the first line. By default, however, if the parent class has no parameterless construction, the subclass must explicitly call the parameterless construction with super.

No matter how you toss, you will instantiate the parent object while instantiating the child object, in order to allocate space for all attributes.

This refers to calling the constructor of this class, and super refers to calling the constructor of parent class. They are all placed in the first line, so they cannot appear at the same time.

12.4 definition and limitation of succession

  1. Java cannot inherit multiple classes, only multi-level inheritance: a class cannot inherit more than two classes at the same time.
  2. When defining inheritance relationship, subclasses can inherit all operation structures in the parent class. However, private operations belong to implicit inheritance, and others belong to display inheritance.
  3. Implicit inheritance: for inheritance in java, a subclass can inherit all properties and methods from the parent class. Whether the access modifier is private or other, it will be inherited by the subclass. However, due to the restriction of the access modifier, the inherited private properties and methods cannot be directly accessed in the subclass

13 override

13.1 method override

The method name is the same as the parent class, but the parameter type, number and return value are the same, which is called override.

Since the instantiation is a subclass object, the method called at this time must be the method overridden by the subclass. If the method has not been overridden. The method provided in the parent class will be called. The meaning of overriding is to optimize the function of the parent class

"super. Method ()" must be used if you want to continue calling the method in the parent class after the subclass overrides the method.

Whenever you call a parent class method in a subclass, you must append the "super. method" before the method.

13.2 method override restrictions

  1. Overridden methods cannot have more stringent access permissions than the parent class.
  2. Overload VS overwrite

13.3 attribute override

When a subclass defines a member with the same name as the parent class, it is called attribute override. (if the attribute is encapsulated, it is not an attribute override at this time)

super vs this

  • Using this in the program class means to find the required properties or methods from this class first. If this class does not exist, find the parent class definition. If super is used, it means to find the parent class directly without finding the child class.
  • Both this and super can call construction methods, but this calls the construction of this class, but super calls the construction of parent class

13.4 final keyword

final defines classes that cannot be inherited.

final defines methods and constants that cannot be overridden.

final is used to define constants.

In fact, constants are usually public and shared, so public static final int ON = 1 is often used; This defines constants.

14 inheritance analysis

class Person{
	private String name;
	private int age;
	private String sex;
	public Person(String name){
		this.name = name;
	}
	public Person(String name, int age, String sex) {
		this(name);
		this.age = age;
		this.sex = sex;
	}
	public String getInfor(){
		return "full name:"+name+"\t Age:"+age+"\t Gender:"+sex;
	}
}
class Student extends Person{
	private String school;
	private String grade;
	public Student(String name, int age, String sex,String school,String grade) {
		super(name, age, sex);
		this.school = school;
		this.grade = grade;
	}
	public String getInfor(){
		return super.getInfor()+"\t school:"+school+"\t grade: "+grade;
	}
}
public class Test {
	public static void main(String[] args) {
		Student student = new Student("Bobo", 12, "man", "LNU", "se");
		System.out.println(student.getInfor());
	}
}

15 Annotation

15.1 introduction to annotation

Annotation can effectively reduce the code of program configuration, and can be used for some structured definitions. Annotation is a program development implemented in the form of annotation.

Some configuration files can be reduced by using annotations.

15.2 accurately overwrite @ Override

You can add an @ Override to the method to Override

This annotation can help developers check for problematic errors during program compilation (for example, the method name to be overwritten is written incorrectly).

15.3 expired statement @ Deprecated

The so-called expiration operation means that there may be a method or a class in the iterative development process of a software project, Due to careless consideration (defects) in the initial design, the new version of the application will not adapt (not affected by the old version), it is impossible to delete these operations directly at this time, so we want to give a transition time, so we use an expired declaration to stop these operations for new users and use them for old users. This method must be defined with @ Deprecated.

15.4 suppress warnings

Is to keep the warning message from appearing and harass you.

16 polymorphism

16.1 introduction to polymorphism

  • Polymorphism of methods:
    • Method overload
    • Override of method
  • Object polymorphism: conversion processing between parent and child instances
    • Object upward Transformation: parent class, parent class instance = child class instance, automatically complete the transformation;
    • Object downward Transformation: subclass subclass instance = (subclass) parent class instance, forced conversion.

Most of them are upward transformation

16.2 object upward transformation

Advantages of upward Transformation: unified design of parameters (uniformity of received or returned parameters).

Key: which subclass is instantiated and whether the subclass overrides the method.

class Person{
	private String name;
	private int age;
	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}
	public void print(){
		System.out.println("I am a Person!");
	}
}
class Student extends Person{
	public Student(String name, int age) {
		super(name, age);
	}
	public void print(){           // Method override
		System.out.println("I am a student!");
	}
}
class Teacher extends Person{
	public Teacher(String name, int age) {
		super(name, age);
	}
	public void print(){           // Method override
		System.out.println("I am a teacher!");
	}
}
public class Test {
	public static void main(String[] args) {
		fun(new Student("Bob", 12));  // Subclass upward transformation
		fun(new Teacher("LIi", 22));  // Subclass upward transformation
		// Through upward transformation, if there are n subclasses, when calling,
		// You only need fun
	}
	public static void fun(Person person){
		person.print();
	}
}

16.3 object downward transformation

Upward describes some common features, while downward describes the subclass's own special definition environment. However, it should be clear that downward transformation is not a safe thing. Because the upward transformation must take place before the downward transformation.

class Person{
	public void print(){
		System.out.println("I am a Person!");
	}
}
class Superman extends Person{
	public void print(){           
		System.out.println("I am a Superman!");
	}
	public void fly(){
		System.out.println("I can fly!");
	}
	public void fire(){
		System.out.println("I can fire!");
	}
}
public class Test {
	public static void main(String[] args) {
		Person person = new Superman();       // Upward transformation
		person.print(); // First of all, he is a superman, but under normal circumstances, he is in a normal state
		// Once there is the need of Superman, it will deform (transform downward) and can fly and spit fire
		Superman superman = (Superman)person; // Downward transformation
		superman.fly();
		superman.fire();
	}
}

The downward transformation is to use the functions of subclasses

16.4 instanceof keyword

In order to ensure the security of downward transformation, instanceof needs to be used for judgment.

public class Test {
	public static void main(String[] args) {
		Person person = new Superman();       // Upward transformation
		if(person instanceof Superman){      // Judge before transformation
			Superman superman = (Superman)person; // Downward transformation
			superman.fly();
			superman.fire();
		}
	}
}

17 Object class

17.1 basic concepts of object class

The main feature of the Object class is that it can solve the problem of parameter unification, that is, using the Object class can receive all data types.

In Java, there is only one class that has no inheritance relationship, so this class is Object.

If the method of a program requires that it can receive all class objects, it can use Obiect to realize processing. However, it should be noted that in Java design, the Object class can be used to receive all reference data types, including arrays.

17.2 obtaining object information

toString(); // Used to obtain object information. It is not written by default

17.3 object comparison equals()

18 definition and use of abstract classes

18.1 basic concepts of abstract classes

When designing parent classes, give priority to using abstract classes

The main function of an abstract class is to make conventions on overriding methods in subclasses. Some abstract methods can be defined in an abstract class to implement such conventions. Abstract methods refer to methods defined with the abstract keyword and without a method body. (adding an abstract method to a common class is an abstract class)

Abstract classes cannot be instantiated directly

  • Abstract classes must provide subclasses, which inherit an abstract class using extensions;
  • Subclasses of abstract classes (not abstract classes) must override all abstract methods in the abstract class;
  • The object instantiation of abstract classes can be completed by subclass upward transformation by using object polymorphism

18.2 description of abstract classes

  1. Abstract classes cannot be defined with final
  2. Abstract classes allow no abstract methods
  3. Abstract classes can have static methods
  4. static is never affected by the class structure

18.3 template design mode

19 packaging

19.1 analysis on implementation principle of packaging

The main function of wrapper class is implemented for object conversion of basic data types, and changes with the change of JDk.

class Int{
	private int data;  // Wrap a basic data type
	public Int(int data){
		this.data = data;
	}
	public int intValue(){
		return this.data;
	}
}
public class Test {
	public static void main(String[] args) {
		Object obj = new Int(10);  // Packing: basic data type packing
		int x = ((Int)obj).intValue();// Unpacking: remove the data type from the package class
		System.out.println(x);
	}
}

Now you can find that there are two types of wrapper classes in Java:

  • Object wrapper class (direct subclass of object): Boolean, Character;
  • Numeric packing class (direct subclass of Number): Byte, Short, Integer, Long, Float

The Number class is an abstract class with six methods.

19.2 packing and unpacking

Data packing: save the basic data type into the packing class, which can generally be completed by using the construction method

  • Integer class: public Integer(int value);
  • Double class: public Double(double value);
  • Boolean class: public Boolean(boolean value);

Data unpacking: get the basic data type from the package class:

  • The unpacking method has been defined by the Number class for the numerical packaging class;

  • Boolean type: public Boolean Boolean value();

public class Test {
	public static void main(String[] args) {
		Integer obj = new Integer(10); // Packing
		int x = obj.intValue();  // Unpacking
		System.out.println(x);
	}
}
public class Test {
	public static void main(String[] args) {
		Integer obj = 10; //Automatic packing
		int x = obj; // Automatic unpacking
		System.out.println(x);
	}
}

You must use equals() to judge the equality of wrapper classes in the future

Topics: Java OOP