Java learning record (abstract class)

abstract class

The core of object-oriented programming is abstract oriented programming, which generally depends on abstraction rather than concrete in the development process

public class A{
	public void pp(Pig pig)}//If you use concrete classes, there is no flexibility. If Cat is required, only the source code can be modified

public class A{
	public void pp(Animal obj){}//When calling a method, you can actually pass in any subclass of Animal, such as Pig or cat
}

class Animal{}
class Pig extends Anima1{}
class cat extends Animal{}

Classes that contain abstract methods are called abstract classes. Abstract classes are not allowed to create instances directly. Objects can only be created through subclasses after methods are provided and implemented by subclasses

Abstract method refers to the method without method body. The method is only declared without specific implementation. Abstract methods must provide concrete implementations in subclasses

  • Abstract classes can contain abstract methods, not necessarily abstract methods

Syntax:

public abstract class Anima1{}

public class Dog extends Anima1{}

Animal an=new Dog();//If you directly new Anima1, a syntax error is reported

characteristic:

  • A class containing abstract methods is an abstract class, but an abstract class can have no abstract methods
public abstract class Animal {
	//Methods are implemented concretely, but they are empty, not without a method body
	public void pp(){}
	public abstract void cc();//Abstract methods. Note that abstract methods cannot contain method objects
}
  • Abstract classes cannot directly perform new operations. They can only perform new operations after defining subclasses of concrete implementations
    • Constructors can be defined or not defined in abstract classes, and parameterless constructors are automatically provided by the system
    • Abstract classes do not allow new operations, regardless of whether there is a constructor
public abstract class Animal {}//abstract class is used to declare abstract classes

public class pig extends Animal{}//The concrete class must implement all abstract methods in the abstract class, otherwise the class is still an abstract class
    
Animal an=new Pig();
  • Abstract classes, like ordinary classes, can define member methods and member properties, as well as constructors and destructors. Only abstract classes are allowed to contain abstract methods
  • If a normal class inherits an abstract class, it must provide a concrete implementation for all abstract methods in the abstract class
public abstract class animal{
	private String name;
	protected int age;
    
    //constructor 
	public animal(){}
	public animal(int age){}
	//Common member method
	public void Broken sleep(){
		System.out.println("Close your eyes...");
    }
	public abstract void walk();//Abstract method
	public abstract class mammal extends animal{
		//If no implementation is provided for this method, the current subclass can only be an abstract class
    }
    public class class human beings extends mammal{
		public void walk(){}//Null implementation is allowed, but it cannot be implemented without
    }

In specific applications, abstract classes are generally used to define specifications or general methods

  • The common method is to share and avoid repeated definition of subclasses
  • The specification is to strictly require that subclasses must provide implementations

Characteristics of abstract classes

  • If a method has only a declaration but no concrete implementation, the method is an abstract method

    • It is not an empty implementation method body, there is no method body
    • You need to use abstract to modify, otherwise the syntax will report an error
    • Abstract methods must be defined in abstract classes, which must also be decorated with abstract
  • Abstract methods can only use the public/protected/package default in the scope qualifier, and cannot use private

    • public void pp() this is a method containing an empty implementation, not an abstract method
    • public void pp(); This is a method without method implementation. Abstract modifier is required in abstract class
public abstract void pp();
  • It is not allowed to define abstract constructor public abstract animml(); Syntax error.
    • Constructors can be defined or not defined in abstract classes. The system automatically provides a default parameterless constructor. However, if the constructor is customized, the constructor is not allowed
abstract class Animal{
	private Animal(){}
}

class Dog extends Animal{
	//Because there is only one private constructor in Anima1, when Dog constructs an object, it cannot call the parent constructor, so an error is reported
}   

If you need to define a private constructor, you must provide a non private constructor with parameters

abstract class Parent2 {

	private Parent2() {}
	public Parent2 (int age) {
	 //this();
	}
}

class son2 extends Parent2 {
	public son2() {
		super(10);
	}
}
  • Abstract class or abstract method is not allowed to be final

    • If the final class does not allow inheritance, you cannot define a subclass
    • The final method does not allow the definition to be overridden in subclasses, so the final abstract method cannot be defined
  • Static methods can be defined in abstract classes

public class Test3 {
	public static void main(String[] args) {
		Parent3.pp();//There is no way to call directly with Parent3 object
		Parent3 p3=new son3(;
		p3.pp();
	}
}
                            
abstract class Parent3 {
	public static void pp() {
		System.out.println( "Parent. ..pp");
	}
}
                            
class son3 extends Parent3 {}
  • Abstract static methods are not allowed to be defined
abstract class Parent3 {
	//The abstract method dd in type Parent3 can only set avisibility modifier´╝îone of public or protected
	public static abstract void dd();//abstract is not allowed
}

Static methods can be called directly using abstract classes

  • Abstract classes cannot create objects directly. They can only define subclasses by inheritance, and then create subclass objects. Subclass objects can be assigned to the variable Animal a=new Dog() declared by the abstract class;
  • In addition to abstract methods, abstract classes can also have non abstract methods

problem

The abstract class cannot be instantiated. Is it because there is no constructor defined in the abstract class?

  • Abstract classes cannot be instantiated. It is a syntax rule and has nothing to do with whether there is a constructor or not

  • Constructors can be defined or not defined in abstract classes. If no constructor is defined, the system automatically provides a parameterless constructor

  • When creating a subclass object, the constructor of the abstract parent class will also be called and executed automatically

Abstract classes cannot be instantiated. Is it because calling abstract methods is meaningless?

Abstract classes can contain or have no abstract methods. Abstract classes cannot be instantiated without abstract methods. An abstract class can only be instantiated after all the abstract methods of the parent class are defined by the subclass. Otherwise, the subclass is still an abstract class

Usage scenarios of abstract classes

  • When one or more methods in a class are abstract methods
  • When a class is a subclass of an abstract class, it does not provide implementation or method body for all abstract methods
  • When a class implements an interface, it does not provide implementation details or method bodies for all methods in the interface

Abstract class vs ordinary class

  • Abstract classes cannot be instantiated directly, but can only be instantiated through subclasses; Ordinary classes can be instantiated directly

  • Abstract classes are allowed to contain Abstract member methods; Abstract methods are not allowed in normal classes

  • Abstract classes are not allowed to be sealed. final sealed classes cannot be inherited to prevent malicious derivation

Template mode

It belongs to behavioral design pattern

Specific programming

First, define an abstract class to publicly define the overall algorithm [algorithm skeleton], but some methods that need to be used in the overall algorithm cannot be implemented, so they can be delayed to subclasses

Abstract parent class: provides algorithm skeleton and defines abstract methods

public abstract class Bubb1esorter{
	//The algorithm implementation is defined in the parent class. There is no way to delay the defined comparison method to be provided in the child class
	public final void sort(object[] arr){
		for(int i=1;i<arr.length;i++){
			for(int k=0 ; k<arr.length-i ; k++){
				//How to compare two objects
				if(bigger(arr[k],arr[k+1])){
					object tmp=arr[k];
					arr[k]=arr[k+1];
    				arr[k+1]=tmp;
				}
			}
		}
	}
	//Since there is no way to determine how to compare in the parent class, the definition of abstract methods requires that subclasses must provide and implement protected Abstract Boolean bigger (object ob1, object ob2);
}

Specific comparison methods are provided in specific subclasses

public class Pig{//Compare and sort objects
	private double weight;
}

Define the corresponding sorter for Pig

public class Pigsorter extends Bubblesorter{
	protected boo1ean bigger(object obj1,object obj2){
		if(obj1!=null && obj1 instanceof Pig){
			Pig p1=(Pig)obj1;
			if(obj2 !=null && obj2 instanceof Pig){
				Pig p2=(Pig)obj2;
				return p1.getWeight()>p2.getWeight();
			}
		}
		return false;
	}
}

Application scenario

When to use: there are some general methods

How to solve: Abstract these general algorithms.

1. There are methods shared by multiple subclasses, and the logic is the same.

2. Important and complex methods can be considered as template methods.

advantage

1. Encapsulate the invariant part and expand the variable part.

2. Extract common codes for easy maintenance.

3. The behavior is controlled by the parent class and implemented by the child class.

shortcoming

Each different implementation needs a subclass to implement, resulting in an increase in the number of classes and a larger system.

Role of abstract classes

The main purpose is to hide the type. Construct a fixed abstract description of a group of behaviors, but this group of behaviors can have any possible concrete implementation.

public void pp(animal obj){
	obj.work();
	obj.Public method();
}

public abstract class animal{
	public void Public method(){
		Concrete implementation;
	}
	public abstract void work();
}
class dog extends animal{
	public void work(){
		System.out.println("Look at the gate!");
	}
}

Abstract classes are generally used to represent the analysis of problem domain. Design species often obtain abstract classes first, and then define specific classes

Abstract oriented programming is the core of OOP

  • Solidify the algorithm skeleton in the parent class and implement special methods in the child class

common problem

1. What kind of constructor does an abstract class have?

  • Yes, used to initialize subclass objects
  • When new subclasses, the constructor of the abstract parent class must be executed

2. Can abstract classes not define abstract methods?

  • Yes, but it usually happens less

  • The purpose is not to allow the construction of such objects, which can only be inherited by subclasses

  • Only through subclasses can we build objects of abstract parent classes

3. Abstract class - must be the parent class?

  • yes

  • Because the subclass needs to provide the implementation of the parent class abstract method, it can be instantiated

4. When creating objects, the order in which they are loaded:

  • Load parent class first

    • Handle the static attributes and static initialization blocks of the parent class. The status of the two is equal, and the execution order depends on the definition order
    • Static code blocks are consistent with static methods, requiring that only static members can be accessed directly
    • If you need to access non static members in static code blocks and static methods, you must build objects
  • Load subclasses

    • Handle static attributes and static initialization blocks of subclasses. They have equal status, and the execution order depends on the definition order.
    • Static code blocks are consistent with static methods, requiring that only static members can be accessed directly
    • If you need to access non static members in static code blocks and static methods, you must build objects
  • Load parent class first

    • Member attributes and initialization blocks have equal status, and the execution order depends on the definition order.
    • Parent constructor
  • Load subclasses

    • The member attribute and initialization block have equal status, and the execution order depends on the definition order
    • Subclass constructor

Coupling problem

OOP requires high cohesion within classes and weak coupling between classes - changes in customer requirements

public class farm{
	private Bubble sorter sorter;//Farm classes and abstract classes are coupled, but not specific implementation classes, so you can switch between multiple implementation classes
}

Tags: Java

Posted on Mon, 06 Dec 2021 23:24:15 -0500 by justice1