Detailed Java object-oriented core technology (Java essential knowledge)

Object-oriented has four basic characteristics: encapsulation, inheritance, abstraction, and polymorphism. To write programs using object-oriented thinking, the entire program architecture can become very flexible without reducing code redundancy.

Class encapsulation

Encapsulation is the core idea of ​​object-oriented transformation. The carrier of encapsulation is a class, and the attributes and behaviors of the object are encapsulated in this class.

Class inheritance

The basic idea of ​​inheritance is based on the extension of a parent class and formulate a new subclass. The subclass can inherit the original properties and methods of the parent class, or add properties and methods that the original parent class does not have, or Directly override some methods in the parent class. Java only supports single inheritance, that is, a class can only have one parent class.

extends keyword

Child extends Parents

While the child class Child class inherits the parent class Parents class, it also inherits the properties and methods of the parent class Parents class.

Method rewriting

The members of the parent class will be inherited by the child class. When a method in the parent class is not applicable to the child class, you need to override this method of the parent class in the child class.

Keep the name of the member method of the parent class in the subclass, rewrite the implementation content of the member method, change the storage permission of the member method, or modify the return value type of the member method.

public class Computer {
    
    
	String screen = "液晶显示屏";
	void startup(int a) {
    
    
		System.out.println("我有" + a + "台" + screen);
	}
}

public class Pad extends Computer{
    
    
	String battery = "500毫安电池";

	@Override
	void startup(int a) {
    
    
		super.startup(a);
	}
}

Method refactoring

There is also a special rewriting method in inheritance. The return value, method name, parameter type and number of member methods of the subclass and the parent class are exactly the same. The only difference is the content of the method. This special rewriting method is Called refactoring.

public class Computer {
    
    
	String screen = "液晶显示屏";
	void startup(int a) {
    
    
		System.out.println("我有" + a + "台" + screen);
	}
}

public class Pad extends Computer{
    
    
	String battery = "500毫安电池";
	
	// 重构:返回值、方法名称、参数类型及个数完全相同,唯一不同的方法实现内容
	@Override
	void startup(int a) {
    
    
		System.out.println("我有" + a + "台" + screen + ",和" + a + "个" + battery);
	}
}

Note: When overriding the parent class method, the modification authority of the modified method can only be changed from a small range to a large range.

super keyword

Java provides the super keyword. The super keyword represents the parent object. The use of the super keyword is as follows:

super.property;	// 调用父类的属性
super.method;		// 调用父类的方法

Object class, the parent class of all classes

In Java, all classes directly or indirectly inherit the java.lang.Object class, such as String, Integer and other classes are inherited from the Object class, because all classes are Object subclasses, so when defining the class, omit extends Obejct statement.

The two most commonly used methods in the Object class are equals() and toString() and the getClass() method. Since all classes are subclasses of the Object class, any class can override the methods of the Object class.

1. The getClass() method The
getClass method returns the Class instance when an object is executed, and then the name of the class can be obtained through getName.

getClass().getName();

2. toString() method The
toString method returns the string representation of an object. When printing an object, the overridden toString method is automatically called.

3. The equals() method The equals() method in the
Object class compares whether the reference addresses of the two objects are equal.

Class polymorphism

In Java, the meaning of polymorphism is "one definition, multiple implementations". The polymorphism of a class can be embodied from two aspects, one is the overloading of methods, and the other is the up-and-down transformation of the class.

Method overloading

More than one method with the same name is allowed in the same class, as long as the number or types of the parameters of these methods are different.

public class Pad extends Computer{
    
    
	void startup(int a,int b) {
    
    
		System.out.println("我有大宝" );
	}
	
	void startup(int a) {
    
    
		super.startup(a);
	}
}

Upward transformation

In Java, the technique of assigning subclass objects to superclass objects is called upcasting. Objects of the parent class cannot call unique properties or methods of the subclass.

public class Computer {
    
    
	static void startup(Computer computer) {
    
    
		System.out.println(computer);
	}
}
public class Pad extends Computer{
    
    
	public static void main(String[] args) {
    
    
		Pad pc = new Pad();
		startup(pc);
	}
}

Downcast

The method of forcing a parent class object into a subclass object is called display type conversion.

public class Pad extends Computer{
    
    
	public static void main(String[] args) {
    
    
		Pad pc = new Pad();
		startup(pc);
		
		Computer computer = new Pad();
		// 父类转子类需要(显示类型)强制转换才能实现
		Pad pad = (Pad)computer;	
	}
}

instanceof keyword

When performing downcast operations in the program, if the parent class object is not an instance of the subclass, a ClassCastException will be sent. So it is necessary to judge whether the parent class is an instance of the subclass, instanceof can judge whether a certain class implements a certain interface.

public class Computer {
    
    

}

public class Pad extends Computer{
    
    
	public static void main(String[] args) {
    
    
		Computer computer = new Computer();
		// 判断computer是不是Pad的实例
		if (computer instanceof Pad) {
    
    
			Pad pad = (Pad)computer;	
		}
	}
}

Abstract classes and interfaces

Abstract class and abstract method

Abstract classes cannot generate object instances. When defining abstract classes, you need to use the abstract keyword.

权限修饰符 abstract class 类名 {
    
    
	类体
}

Methods defined using abstract are called abstract methods.

权限修饰符 abstract 方法返回值类型 方法名(参数列表); 

The abstract method ends directly with a semicolon, there is no method body, and the abstract method itself has no meaning unless it is overridden, and the abstract class that carries this abstract method must be inherited. Subclasses that inherit the abstract class need to override the abstract methods in the abstract class.

public abstract class Market {
    
    
	public String name;
	public String goods;
	public abstract void shop(); //抽象方法
}
public class TaobaoMarket extends Market{
    
    
	@Override
	public void shop() {
    
    
		System.out.println(name + "网购" + goods);
	}
	
	public static void main(String[] args) {
    
    
		Market market = new TaobaoMarket(); // 派生类对象创建抽象类对象
		market.name = "仙宝";
		market.goods = "芭比娃娃";
		market.shop();
	}
}

Run results: Xianbao online shopping Barbie dolls

Abstract classes and abstract methods need to follow the following principles:
1. Abstract classes may or may not contain abstract methods, but the class that contains abstract methods must be abstract.
2. The abstract class cannot be instantiated directly, even if the abstract method is not declared in the abstract class.
3. After the abstract class is inherited, the subclass needs to re-abstract all the abstract methods in the class.
4. If the subclass that inherits the abstract class is also an abstract class, you don't need to rewrite all the abstract methods in the parent class. There will be too much redundant code in the use of abstract classes. A class cannot inherit multiple parent classes at the same time, and interfaces emerge as the times require.

Interface declaration and implementation

An interface is an extension of an abstract class. It can be regarded as a pure abstract class. All methods in the interface have no method body.

权限修饰符 interface 接口名 {
    
    
}

A class to implement an interface can use the implements keyword

public class Para implements draw {
    
    	
}

Any variable defined in the interface is automatically static and final, so when you define a constant in the interface, you must initialize it, and the subclass that implements the interface cannot reassign the variables in the interface.

Multiple inheritance

In Java, classes do not allow multiple inheritance, but multiple inheritance can be achieved with interfaces, because a class can implement multiple interfaces.

类名 implements  接口1,接口2,接口3 {
    
    
}

With multiple integration, there may be conflicts between variables or method names. If the variables conflict, you need to clearly specify the interface of the variable, that is, through "interface name. Variable", if the method conflicts, you only need to implement one method. .

Distinguish between abstract classes and interfaces

Inheritance: Subclasses can only inherit one abstract class, but can implement multiple interfaces.
Methods: Abstract classes can have non-abstract methods, and interfaces are all abstract methods.
Attribute: The abstract class can be any type, and the interface can only be static constants.
Code: Abstract classes can have static methods and static code blocks, but interfaces cannot.
Construction method: An abstract class can have a construction method, but an interface does not.

Access control

Java mainly controls the access scope of classes, methods, or variables through access control symbols, class packages, and final keywords.

Access control character

To hide the hidden and expose the exposed, both of these aspects need to be implemented through "access control symbols".

This category: one class file
Same package: one package package
Subcategory: Subcategories under other packages
Other: Non- subcategories under other packages

When declaring a class, if you do not use the public modifier to set the permissions of the class, the default is default.

In the Java language, the permission setting of a class restricts the permission setting of class members. For example, to define a default class, no matter whether the method is added or not, its access modifier is default.

Most classes use public, except for static or global variables, all properties use private.

Java class package

Every time a class is defined in Java, after being compiled by the Java compiler, a file with an extension of .class will be generated. When the primary key of the scale is expanded, class name conflicts are prone to occur.

Java provides a mechanism for managing class files-class packages. It is very important to adopt the class package mechanism in Java. The class package can solve the problem of class name conflicts.

The naming rule for Java packages is to use all lowercase letters. If you want to use a class that takes care, you can specify it using the import keyword in Java.

When using the import keyword, you can specify the complete description of the class, but in order to use more classes in the package, you can add ".*" after the package name, which means that all classes of the package are used in the program. When the class in the package is specified by import, the sub-package class of this package is not specified. If the sub-class is used, it needs to be quoted again.

final keyword

The meaning of final is final and final, and the classes, methods and variables that are modified by final cannot be changed.

1. Final class
When a class is set to a final class, the method in the class will be implicitly set to final form, but the member variables in the final class can be defined as either final or non-final form.

2. Final method The method
modified by final cannot be rewritten. Defining the method as final can prevent subclasses from modifying the definition and implementation of the method. At the same time, the execution efficiency of final methods is higher than that of non-final methods. When a subclass inherits a parent class, after the parent class method is modified with final, the subclass cannot be overridden.

3. Final variable The
final keyword can be used to modify the variable. Once the variable is final modified, the value of the variable can no longer be changed. Variables that are usually final modified are called constants. The final modified variable must be assigned a value when it is declared. Regardless of whether it is a constant or a final modified object reference, it cannot be reassigned.

Inner class

Define a class in a class, then call the class defined in the class an inner class.

Member inner class

In addition to member variables, methods, and constructors that can be used as members of a class, member inner classes can also be used as members of a class. The syntax is as follows:

public class OtherClass {
    
    		// 外部
	public class InnerClass {
    
    	// 内部

	}
}

Although the member methods and member variables of the outer class are decorated with private, the inner class can also be used.
Initialize an inner class object in the outer class, then the inner class object will be bound to the outer class object.

public class OtherClass {
    
    		// 外部
	private String name;
	
	public OtherClass(String name) {
    
    
		this.name = name;
	}
	
	public void name() {
    
    
		System.out.println(this.name);
	}

	public class InnerClass {
    
    	// 内部
		private Integer age;

		public InnerClass(Integer age) {
    
    
			this.age = age;
		}
		public void age() {
    
    
			System.out.println(this.age);
		}
	}
	
	public static void main(String[] args) {
    
    
		OtherClass otherClass = new OtherClass("张三");
		otherClass.name();
		InnerClass innerClass = otherClass.new InnerClass(22);
		innerClass.age();
	}
}

The inner class object is very dependent on the outer class object otherClass.new InnerClass(22), unless an outer class object already exists.

Anonymous inner class

The feature of anonymous inner classes is that they only need to be used once, that is, they cannot be reused. The most common way to create an anonymous inner class is to create an object of an interface type or abstract class. The syntax is as follows:

new A(){
    
    
	// 匿名内部类的类体
};

Anonymous inner class should follow the following principles:
1. Anonymous class has no construction method.
2. An anonymous class cannot define static members.
3. Anonymous classes cannot be modified with private, public, protected, static, final, abstract, etc.
4. Only one anonymous class instance can be created.

public abstract class Market {
    
    
	public abstract void shop(); //抽象方法
}
public class TaobaoMarket{
    
    
	public static void main(String[] args) {
    
    
		new Market() {
    
    
			@Override
			public void shop() {
    
    
				System.out.println("去超市买东西");
			}
		}.shop();
	}
}

Operation result: go to the supermarket to buy things

In fact, anonymous inner classes have the same memory structure as other classes, but the objects created by anonymous inner classes are not referenced by specific variables, so anonymous inner classes are disposable. If the created class object is only used once, an anonymous inner class can be considered in this scenario.

Guess you like

Origin blog.csdn.net/weixin_43888891/article/details/113488684