8: Object oriented

01. Keyword: static

1.1 use of static

When we write a class, we are actually describing the properties and behavior of its object without generating a substantive object. Only through the new keyword can we generate an object. At this time, the system will allocate memory space to the object and its methods can be called externally.

We sometimes hope that no matter whether objects are generated or how many objects are generated, there is only one copy of some specific data in the memory space.

For example, all Chinese have a country name, and each Chinese shares the country name. There is no need to assign a variable representing the country name to each Chinese instance object.

/*
 * static Use of keywords
 * 
 * 1.static:Static.
 * 2.static Can be used to modify: attributes, methods, code blocks, internal classes.
 * 
 * 3.Use static to modify attributes: static variables (or class variables).
 * 		3.1  Attribute: whether to use static modification, which is divided into static attribute VS non static attribute (instance variable)
 * 		   Instance variable: we have created multiple objects of the class, and each object independently has a set of non static properties in the class.
 * 				When one of the non static attributes is modified, it will not lead to the modification of the same attribute value in other objects.
 * 		   Static variable: we create multiple objects of the class, and multiple objects share the same static variable. When modifying a variable through a static variable,
 * 				Will cause other objects to call this static variable, which is modified.
 * 		3.2 static Additional description of modified attributes:
 * 			① Static variables are loaded as the class is loaded. It can be called by "class. Static variable".
 * 			② Static variables are loaded before objects are created.
 * 			③ Since the class will only be loaded once, the static variable will only exist once in memory. Exists in the static field of the method area.
 * 
 * 			④ 		Class variable 		 Instance variable
 * 			class 		 yes 			 no
 * 			object 		 yes 			 yes
 * 
 * 		3.3 Examples of static attributes: System.out.Math.PI;
 *  
 */
public class StaticTest {
	public static void main(String[] args) {
		
		Chinese.nation = "China";
		
		Chinese c1 = new Chinese();
		c1.name = "Yao Ming";
		c1.age = 40;
		c1.nation = "CHN";
		
		Chinese c2 = new Chinese();
		c2.name = "Malone";
		c2.age = 30;
		c2.nation = "CHINA";
		
		System.out.println(c1.nation); 
		
		//Compilation failed
//		Chinese.name = "Zhang Jike";
		
	}
}
//Chinese
class Chinese{
	
	String name;
	int age;
	static String nation;
}

1.2. Class variable vs instance variable memory resolution

1.3 static modification method

/* 
 * 4.Using static to decorate methods: static methods
 * 		① It is loaded as the class is loaded, and can be called through "class. Static method"
 * 		② 			Static method 		 Non static method
 * 			class 		 yes 			 no
 * 			object 		 yes 			 yes
 * 		③ In static methods, only static methods or properties can be called
 * 		  In non static methods, all methods or properties can be called
 * 
 * 5.static Note:
 * 	 5.1  this keyword and super keyword cannot be used in static methods
 *   5.2 The use of static attributes and static methods is understood from the perspective of life cycle.
 *   
 * 6.In development, how to determine whether a property needs to declare static?
 * 	 > Attributes can be shared by multiple objects and will not vary with different objects.
 * 	 > Constants in classes are also often declared as static
 *   
 *   During development, how to determine whether a method should be declared as static?
 *   > The method for operating static properties is usually set to static
 *   > Methods in tool classes are traditionally declared as static. For example: Math, Arrays, Collections
 * 	 
 */
public class StaticTest {
	public static void main(String[] args) {
		
		Chinese.nation = "China";
		
		Chinese c1 = new Chinese();
		
		//Compilation failed
//		Chinese.name = "Zhang Jike";
		
		c1.eat();
		
		Chinese.show();
		//Compilation failed
//		chinese.eat();
//		Chinese.info();
	}
}
//Chinese
class Chinese{
	
	String name;
	int age;
	static String nation;
	
	public void eat(){
		System.out.println("Chinese people eat Chinese food");
		//Call non static structure
		this.info();
		System.out.println("name : " + name);
		//Call static structure
		walk();
		System.out.println("nation : " + Chinese.nation);
	}
	
	public static void show(){
		System.out.println("I am a Chinese!");
//		eat();
//		name = "Tom";
		//Static structures can be called
		System.out.println(Chinese.nation);
		walk();
	}
	
	public void info(){
		System.out.println("name : " + name + ",age : " + age);
	}
	
	public static void walk(){
		
	}
}

1.4. Optimization of custom ArrayUtil

/*
 * Custom array utility class
 */
public class ArrayUtil {

	// Find the maximum value of the array
	public static int getMax(int[] arr) {
		int maxValue = arr[0];
		for (int i = 1; i < arr.length; i++) {
			if (maxValue < arr[i]) {
				maxValue = arr[i];
			}
		}
		return maxValue;
	}

	// Find the minimum value of the array
	public static int getMin(int[] arr) {
		int minValue = arr[0];
		for (int i = 1; i < arr.length; i++) {
			if (minValue > arr[i]) {
				minValue = arr[i];
			}
		}
		return minValue;
	}

	// Sum arrays
	public static int getSum(int[] arr) {
		int sum = 0;
		for (int i = 0; i < arr.length; i++) {
			sum += arr[i];
		}
		return sum;
	}

	// Average array
	public static int getAvg(int[] arr) {
		int avgValue = getSum(arr) / arr.length;
		return avgValue;
	}

	//The following two methods with the same name constitute an overload
	// Invert array
	public static void reverse(int[] arr) {
		for (int i = 0; i < arr.length / 2; i++) {
			int temp = arr[i];
			arr[i] = arr[arr.length - i - 1];
			arr[arr.length - i - 1] = temp;
		}
	}
	
	public void reverse(String[] arr){
		
	}

	// Copy array
	public static int[] copy(int[] arr) {
		int[] arr1 = new int[arr.length];
		for (int i = 0; i < arr1.length; i++) {
			arr1[i] = arr[i];
		}
		return null;
	}

	// Array sorting
	public static void sort(int[] arr) {
		for (int i = 0; i < arr.length - 1; i++) {
			for (int j = 0; j < arr.length - 1 - i; j++) {
				if (arr[j] > arr[j + 1]) {
//					int temp = arr[j];
//					arr[j] = arr[j + 1];
//					arr[j + 1] = temp;
					//FALSE:
//					swap(arr[j],arr[j+1]);
					
					swap(arr,j ,j+1);
				}
			}
		}
	}
	
	//Error: swapping the values of two elements at the specified position in the array
//	public void swap(int i,int j){
//		int temp = i;
//		i = j;
//		j = temp;
//	}
	
	//correct:
	private static void swap(int[] arr,int i,int j){
		int temp = arr[i];
		arr[i] = arr[j];
		arr[j] = temp;
	}

	// Traversal array
	public static void print(int[] arr) {
		System.out.print("[");
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + ",");
		}
		System.out.println("]");
	}

	// Find the specified element
	public static int getIndex(int[] arr, int dest) {
		//Linear search
		for (int i = 0; i < arr.length; i++) {

			if (dest==arr[i]) {
				return i;
			}

		}
		return -1;
	}

}

Test class

public class ArrayUtilTest {

	public static void main(String[] args) {
//		ArrayUtil util = new ArrayUtil();
		int[] arr = new int[]{32,5,26,74,0,96,14,-98,25};
		int max = ArrayUtil.getMax(arr);
		System.out.println("The maximum value is:" + max);
		
		System.out.print("Before sorting:");
		ArrayUtil.print(arr);
		
		ArrayUtil.sort(arr);
		System.out.print("After sorting:");
		ArrayUtil.print(arr);
		
//		System.out.println("find:");
//		int index = util.getIndex(arr, 5);
//		if(index > 0){
//			System.out.println("found, index address:" + index);
//		}else{
//			System.out.println("not found");
//		}
	}
}

1.5 application examples of static

//Application of static keyword
public class CircleTest {
	public static void main(String[] args) {
		
		Circle c1 = new Circle();
		
		Circle c2 = new Circle();
		
		Circle c3 = new Circle();
		
		System.out.println("c1 of ID:" + c1.getId());
		System.out.println("c2 of ID:" + c2.getId());
		System.out.println("c3 of ID:" + c3.getId());
		
		System.out.println("Number of circles created: " + Circle.getTotal());
		
	}
	
}

class Circle{
	
	private double radius;
	private int id;	//Automatic assignment required
	
	public Circle(){
		id = init++;
		total++;
	}
	
	public Circle(double radius){
		this();
		//or
//		id = init++;
//		total++;
		this.radius = radius;
	}
	
	private static int total;//Record the number of circles created
	private static int init = 1001;//static declared properties are shared by all objects
	
	public double findArea(){
		return 3.14 * radius * radius;
	}

	public double getRadius() {
		return radius;
	}

	public void setRadius(double radius) {
		this.radius = radius;
	}

	public int getId() {
		return id;
	}

	public static int getTotal() {
		return total;
	}
	
}

1.6 practice of static

/*
 * Write a class to realize the concept of bank account. The attributes include "account number", "password", "deposit balance"
 * "Interest rate and minimum balance define methods to encapsulate these attributes.
 * The account number should be generated automatically. Write the main class and use the bank account class to input and output the above information of three depositors.
 * Consideration: which attributes can be designed as static attributes.
 * 
 */
public class Account {
	
	private int id;	//account number
	private String pwd = "000000";	//password
	private double balance; //Deposit balance
	
	private static double interestRate; //interest rate
	private static double minMoney = 1.0;  //Minimum balance
	private static int init = 1001;	//Used to automatically generate id
	
	public Account(){	//Automatic account generation
		id = init++;
	}
	
	public Account(String pwd,double balance){
		id = init++;
		this.pwd = pwd;
		this.balance = balance;
	}
	
	public String getPwd() {
		return pwd;
	}
	
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	
	public static double getInterestRate() {
		return interestRate;
	}
	
	public static void setInterestRate(double interestRate) {
		Account.interestRate = interestRate;
	}
	
	public static double getMinMoney() {
		return minMoney;
	}
	
	public static void setMinMoney(double minMoney) {
		Account.minMoney = minMoney;
	}
	
	public int getId() {
		return id;
	}
	
	public double getBalance() {
		return balance;
	}

	@Override
	public String toString() {
		return "Account [id=" + id + ", pwd=" + pwd + ", balance=" + balance + "]";
	}
	
}

Test class

public class AccountTest {
	public static void main(String[] args) {
		
		Account acct1 = new Account();
		Account acct2 = new Account("qwerty",2000);
		
		Account.setInterestRate(0.012); 
		Account.setMinMoney(100);
		
		System.out.println(acct1);
		System.out.println(acct2);
		
		System.out.println(acct1.getInterestRate()); 
		System.out.println(acct1.getMinMoney());
	}
}

1.7. Singleton design mode

Design pattern is the preferred code structure, programming style and thinking way to solve problems after summarizing and theorizing in a large number of practice** The design of mold eliminates our own thinking and exploration. It's like a classic chess score. We use different chess scores for different chess games. " "Routine"

The so-called class singleton design pattern is to take certain methods to ensure that there can only be one object instance for a class in the whole software system. And this class only provides a method to get its object instance. If we want a class to generate only one object in a virtual machine, we must first set the access permission of the class constructor to private. In this way, we can't generate class objects outside the class with the new operator, but we can still generate objects of the class inside the class. Because you can't get the object of the class from the outside of the class, you can only call a static method of the class to return the object created inside the class. The static method can only access the static member variables in the class. Therefore, the variables pointing to the object of the class generated inside the class must also be defined as static.

1. Hungry Chinese style of singleton mode

/*
 * Single example design mode:
 * 1.The so-called class singleton design pattern is to take certain methods to ensure that there can only be one object instance of a class in the whole software system
 *  
 * 2.How?
 *   Hungry Han style 	 VS 	 Lazy style
 * 
 * 3.Distinguish between hungry and lazy.
 * 	   Hungry Chinese style: disadvantage: the object loading time is too long.
 * 	 	       Benefit: hungry Chinese style is thread safe.
 * 
 *   Lazy: benefit: delay the creation of objects.
 * 		       Disadvantages: the current writing method will make the thread unsafe. - -- When the multithreaded content is, modify it again
 */
public class SingletonTest {
	public static void main(String[] args) {
//		Bank bank1 = new Bank(); 
//		Bank bank2 = new Bank(); 
		
		Bank bank1 = Bank.getInstance();
		Bank bank2 = Bank.getInstance();
		
		System.out.println(bank1 == bank2);
		
	}
}

//Single case hungry Chinese style
class Bank{
	
	//1. Constructor of privatization class
	private Bank(){
		
	}
	
	//2. Internal creative objects
	//4. This object must also be declared static
	private static Bank instance = new Bank();
	
	//3. Provide public static methods to return class objects.
	public static Bank getInstance(){
		return instance;
	}
}

2. Lazy style of singleton mode

/*
 * Lazy implementation of singleton
 * 
 */
public class SingletonTest2 {
	public static void main(String[] args) {
		
		Order order1 = Order.getInstance();
		Order order2 = Order.getInstance();
		
		System.out.println(order1 == order2);
	}
}
class Order{
	//1. Constructor of privatization class
	private Order(){
		
	}
	
	//2. Declare the current class object without initialization.
	//This object must also be declared static
	private static Order instance = null;
	
	//3. Declare public and static methods that return the current class object
	public static Order getInstance(){
		if(instance == null){
			instance = new Order();			
		}
		return instance;
	}
}

3. Advantages of singleton mode

Since the singleton mode only generates one instance, the system performance overhead is reduced. When more resources are required for the generation of an object, such as reading the configuration and generating other dependent objects, it can be solved by directly generating a singleton object when the application is started, and then permanently resident in memory.

4. Singleton design pattern - application scenario

  • The counter of the website is generally implemented in singleton mode, otherwise it is difficult to synchronize.
  • The log application of the application is generally implemented in the single instance mode. This is generally because the shared log file is always open, because there can only be one instance to operate, otherwise the content is not easy to add.
  • The design of database connection pool generally adopts single instance mode, because database connection is a kind of database resource.
  • In the project, the class that reads the configuration file usually has only one object. There is no need to generate an object to read every time the configuration file data is used.
  • Application is also a typical application of singleton
  • The * * Task Manager * * of Windows is a typical singleton mode
  • The * * recycle bin * * of Windows is also a typical singleton application. During the operation of the whole system, the recycle bin maintains only one instance.

02. Understand the syntax of main method (understand)

Because the Java virtual machine needs to call the main() method of the class, the access permission of the method must be public. Because the Java virtual machine does not need to create an object when executing the main() method, the method must be static. The method receives an array parameter of String type, which stores the parameters passed to the running class when executing Java commands.

Because the main() method is static, we cannot directly access the non static members of the class. We must create an instance object of the class before we can access the non static members of the class through this object. We have encountered this situation many times in the previous examples.

/*
 * main()Instructions for using the method
 * 1.main()Method as the entry of the program;
 * 2.main()Method is also a common static method
 * 3.main()Method can also be used as a way for us to interact with the console. (previously, using Scanner)
 * 
 * 
 */
public class MainTest {
	public static void main(String[] args) {	//entrance
		
		Main.main(new String[100]);
		
		MainTest test = new MainTest();
		test.show();
	}
	
	public void show(){
		
	}
}

class Main{
	public static void main(String[] args) {
		args = new String[100];
		for(int i = 0;i < args.length;i++){
			args[i] = "args_" + i;
			System.out.println(args[i]);
		}
	}
}

Example of command line parameter usage

public class MainDemo {
	public static void main(String[] args) {
		
		for(int i = 0;i < args.length;i++){
			System.out.println("/*/*/*/"+ args[i]);
		}	
	}
}

//Run the program MainDemo.java

javac MainDemo.java
java MainDemo "Tom" "Jerry" "Shkstart"

03. Class member 4: code block

/*
 * Class: code block (or initialization block)
 * 
 * 1.Function of code block: used to initialize classes and objects
 * 2.If the code block is decorated, only static can be used
 * 3.Classification: static code block vs non static code block
 * 
 * 4.Static code block
 * 	>There can be output statements inside
 *  >Executes as the class loads, and only once
 *  >Function: initialize class information
 *  >If multiple static code blocks are defined in a class, they are executed in the order of declaration
 *  >The execution of static code blocks takes precedence over the execution of non static code blocks
 *  >Static code blocks can only call static attributes and static methods, not non static structures
 * 
 * 5.Non static code block
 *  >There can be output statements inside
 *  >Executes as the object is created
 *  >Each time an object is created, a non static block of code is executed.
 *  >Function: you can initialize the properties of the object when creating the object.
 *  >If multiple non static code blocks are defined in a class, they are executed in the order of declaration
 *  >Static attributes, static methods, or non static attributes and non static methods can be called in non static code blocks.
 *  
 * Where attributes can be assigned:
 *  ①Default initialization
 *  ②Explicit initialization
 *  ③Initialization in constructor
 *  ④After you have an object, you can assign values through "object. Attribute" or "object. Method".
 *  ⑤Assignment in code block
 */
public class BlockTest {
	public static void main(String[] args) {
		
		String desc = Person.desc;
		System.out.println(desc);
		
		Person p1 = new Person();
		Person p2 = new Person();
		System.out.println(p1.age);
		
		Person.info();
	}
}

class Person{
	//attribute
	String name;
	int age;
	static String desc = "I am a young man";
	
	//constructor 
	public Person(){
		
	}
	
	//static code block
	static{
		System.out.println("hello,static block-1");
		//Call static structure
		desc = "I am a novel lover";
		info();
		//Non static structures cannot be called
//		eat();
//		name = "Tom";
	}
	
	static{
		System.out.println("hello,static block-2");
	}
	
	//Non static code block
	{
		System.out.println("hello,block-2");
	}
	{
		System.out.println("hello,block-1");
		//Call non static structure
		age = 1;
		eat();
		//Call static structure
		desc = "I am a novel lover 1";
		info();
	}	
	
	//method
	public Person(String name,int age){
		this.name = name;
		this.age = age;
	}
	
	public void eat(){
		System.out.println("having dinner");
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}
	public static void info(){
		System.out.println("I am a happy person.");
	}
	
}

Static initialization block example 1

//Summary: from parent class to child class, static first
class Root{
	static{
		System.out.println("Root Static initialization block for");
	}
	{
		System.out.println("Root Normal initialization block");
	}
	public Root(){
		System.out.println("Root Parameterless constructor for");
	}
}
class Mid extends Root{
	static{
		System.out.println("Mid Static initialization block for");
	}
	{
		System.out.println("Mid Normal initialization block");
	}
	public Mid(){
		System.out.println("Mid Parameterless constructor for");
	}
	public Mid(String msg){
		//Call overloaded constructors in the same class through this
		this();
		System.out.println("Mid A constructor with parameters, whose parameter values are:"
			+ msg);
	}
}
class Leaf extends Mid{
	static{
		System.out.println("Leaf Static initialization block for");
	}
	{
		System.out.println("Leaf Normal initialization block");
	}	
	public Leaf(){
		//Call the constructor with a string parameter in the parent class through super
		super("Shang Silicon Valley");
		System.out.println("Leaf Constructor for");
	}
}
public class LeafTest{
	public static void main(String[] args){
		new Leaf(); 
		//new Leaf();
	}
}

Static initialization block example 2

class Father {
	static {
		System.out.println("11111111111");
	}
	{
		System.out.println("22222222222");
	}

	public Father() {
		System.out.println("33333333333");

	}

}

public class Son extends Father {
	static {
		System.out.println("44444444444");
	}
	{
		System.out.println("55555555555");
	}
	public Son() {
		System.out.println("66666666666");
	}

	public static void main(String[] args) { // Statically preceded by parent and child
		System.out.println("77777777777");
		System.out.println("************************");
		new Son();
		System.out.println("************************");

		new Son();
		System.out.println("************************");
		new Father();
	}

}

Summary: execution sequence of assignment of member variables in the program

/*
 * Where attributes can be assigned:
 *  ①Default initialization
 *  ②Explicit initialization / ⑤ assignment in code block
 *  ③Initialization in constructor
 *  ④After you have an object, you can assign values through "object. Attribute" or "object. Method".
 *  
 *  Order of execution: ① - ② / ⑤ - ③ - ④
 */
public class OrderTest {
	public static void main(String[] args) {
		Order order = new Order();
		System.out.println(order.orderId);
	}
}
class Order{
	
	int orderId = 3;
	{
		orderId = 4;
	}
	
}

04. Keyword: final

/*
 * final:Final
 * 
 * 1.final Structures that can be modified: classes, methods, variables
 * 
 * 2.final Used to decorate a class: this class cannot be inherited by other classes.
 * 		  For example: String class, System class, StringBuffer class
 * 3.final Modify a method: a method marked final cannot be overridden by a subclass.
 * 		  For example: getClass() in Object class. 
 * 4.final Used to modify a variable: at this time, the "variable" (member variable or local variable) is a constant. The name is capitalized and can only be assigned once.
 * 	 4.1 final Modify attributes. The positions where assignment can be considered are: explicit initialization, initialization in code block and initialization in constructor
 *   4.2 final Modify local variables:
 *   	 Especially when final is used to modify the formal parameter, it indicates that the formal parameter is a constant. When we call this method, we assign an argument to the constant formal parameter.
 *      Once assigned, this parameter can only be used in the method body, but it cannot be re assigned.
 *      
 * static final Used to modify: global constant
 */
public class FinalTest {
	
	final int WIDTH = 0;
	final int LEFT;
	final int RIGHT;
//	final int DOWN;
	
	{
		LEFT = 1;
	}
	
	public FinalTest(){
		RIGHT = 2;
	}
	
	public FinalTest(int n){
		RIGHT = n;
	}
	
//	public void setDown(int down){
//		this.DOWN = down;
//	}
	
	public void dowidth(){
//		width = 20;	//width cannot be resolved to a variable
	}
	
	public void show(){
		final int NUM = 10;	//constant
//		num += 20;
	}
	
	public void show(final int num){
		System.out.println(num);
	}
	
	public static void main(String[] args) {
		
		int num = 10;
		
		num = num + 5;
		
		FinalTest test = new FinalTest();
//		test.setDown(5);
		
		test.show(10);
	}
}

final class FianlA{
	
}

//class B extends FinalA {/ / error, unable to inherit.
//	
//}

//class C extends String{
//	
//}

class AA{
	public final void show(){
		
	}
}

//class BB extends AA{ 	//  Error, cannot be overridden.
//	public void show(){
//		
//	}
//}

1. Interview question 1

public class Something {
	public int addOne(final int x) {
		return ++x; // return x + 1;
	}
}

2. Interview question 2

public class Something {

	public static void main(String[] args) {
		Other o = new Other();
		new Something().addOne(o);
	}

	public void addOne(final Other o) {
		// o = new Other();
		o.i++;
	}
}

class Other {
	public int i;
}

05. Abstract classes and abstract methods

With the definition of new subclasses in the inheritance hierarchy, classes become more and more specific, while parent classes are more general and general. Class design should ensure that parent and child classes can share features. Sometimes a parent class is designed so abstract that it has no specific instances. Such a class is called an abstract class.

/*
 * abstract Use of keywords
 * 
 * 1.abstract:Abstract
 * 2.abstract Structures that can be modified: classes, methods
 * 3.abstract Decoration class: abstract class
 * 	> This class cannot be instantiated
 *  > There must be a constructor in the abstract class, which is convenient for calling when subclass instantiation (involving the whole process of subclass object instantiation)
 *  > During development, subclasses of abstract classes will be provided to instantiate subclass objects and realize relevant operations
 * 
 * 4.abstract Modification method: abstract method
 *  > Abstract method, only method declaration, no method body.
 *  > A class containing abstract methods must be an abstract class. Conversely, there can be no abstract methods in an abstract class
 *  > If a subclass overrides all the abstract methods in the parent class, the subclass,
 *
 * abstract Notes on use:
 * 1.abstract It cannot be used to modify variables, code blocks and constructors;
 * 
 * 2.abstract It cannot be used to modify private methods, static methods, final methods, and final classes.
 * 
 */
public class AbstractTest {
	public static void main(String[] args) {
		//Once the Person class is abstract, it cannot be instantiated
//		Person p1 = new Person();
//		p1.eat();
		
	}
}

abstract class Creature{
	public abstract void breath();
}

abstract class Person extends Creature{
	String name;
	int age;
	
	public Person(){
		
	}
	
	public Person(String name,int age){
		this.name = name;
		this.age = age;
	}
	
	//Not an abstract method
//	public void eat(){
//		System.out.println("people eat");
//	}
	
	//Abstract method
	public abstract void eat();
	
	public void walk(){
		System.out.println("People walk");
	}
}

class Student extends Person{
	public Student(String name,int age){
		super(name,age);
	}
	public void eat(){
		System.out.println("Students should eat more nutritious food.");
	}
	@Override
	public void breath() {
		System.out.println("Students should breathe fresh haze free air");
	}
}

5.1 abstract class application

Abstract classes are used to model objects whose parent class cannot determine all implementations, but whose child classes provide concrete implementations.

Problem: the calculation methods of fuel efficiency and driving distance of trucks and barges are completely different. The Vehicle class cannot provide calculation methods, but subclasses can.

/* Java Allows the class designer to specify that a superclass declares a method but does not provide an implementation, and the implementation of the method is provided by a subclass. Such methods are called abstract methods. A class with one or more abstract methods is called an abstract class.
 * Vehicle Is an abstract class with two abstract methods.
 * Note: abstract classes cannot instantiate new Vihicle(), which is illegal
 */
public abstract class Vehicle{
	public abstract double calcFuelEfficiency();//Abstract method for calculating fuel efficiency
	public abstract double calcTripDistance();//Abstract method for calculating driving distance
}
public class Truck extends Vehicle{
	public double calcFuelEfficiency(){ 
		//Write a specific method for calculating the fuel efficiency of trucks
	}
	public double calcTripDistance(){ 
		//Write down the specific method of calculating the distance traveled by the truck
	}
}
public class RiverBarge extends Vehicle{
	public double calcFuelEfficiency() { 
		//Write a specific method for calculating the fuel efficiency of the barge
	}
	public double calcTripDistance( )  {  
		//Write down the specific method for calculating the distance traveled by the barge
	}
}

5.2 practice

/*
 * Write an Employee class and declare it as an abstract class,
 * It contains the following three attributes: name, id and salary.
 * Provide the necessary constructor and abstract method: work().
 * For the Manager class, it is not only an employee, but also has the attribute of bonus.
 * Please use the idea of inheritance to design CommonEmployee class and Manager class,
 * Require the class to provide the necessary methods for property access.
 * 
 */
public abstract class Employee {
	
	private String name;
	private int id;
	private double salary;
	
	public Employee(){
		super();
	}

	public Employee(String name, int id, double salary) {
		super();
		this.name = name;
		this.id = id;
		this.salary = salary;
	}
	
	public abstract void work();	
}

Manager class

/*
 * For the Manager class, it is not only an employee, but also has the attribute of bonus.
 * 
 */
public class Manager extends Employee{

	private double bonus;	//bonus
	
	public Manager(double bonus) {
		super();
		this.bonus = bonus;
	}
	
	public Manager(String name, int id, double salary, double bonus) {
		super(name, id, salary);
		this.bonus = bonus;
	}


	@Override
	public void work() {
		System.out.println("Manage employees and improve the operation efficiency of the company.");		
	}
}

CommonEmployee class

public class CommonEmployee extends Employee {

	@Override
	public void work() {
		System.out.println("Employees produce products in the front-line workshop.");
	}

}

Test class

/*
 * Please use the idea of inheritance to design CommonEmployee class and Manager class,
 */
public class EmployeeTest {
	public static void main(String[] args) {
		
		Employee manager = new Manager("Cook",1001,5000,50000);
		
		manager.work();
		
		CommonEmployee commonEmployee = new CommonEmployee();
		commonEmployee.work();
	}
}

5.3. Create anonymous subclass objects of abstract classes

public class Num {

}

abstract class Creature{
	public abstract void breath();
}

abstract class Person extends Creature{
	String name;
	int age;
	
	public Person(){
		
	}
	
	public Person(String name,int age){
		this.name = name;
		this.age = age;
	}
	
	//Not an abstract method
//	public void eat(){
//		System.out.println("people eat");
//	}
	
	//Abstract method
	public abstract void eat();
	
	public void walk(){
		System.out.println("People walk");
	}
}

class Student extends Person{
	public Student(String name,int age){
		super(name,age);
	}
	public Student(){

	}
	public void eat(){
		System.out.println("Students should eat more nutritious food.");
	}
	@Override
	public void breath() {
		System.out.println("Students should breathe fresh haze free air");
	}
}

PersonTest class

/*
 * Anonymous subclass of abstract class
 * 
 */
public class PersonTest {
	public static void main(String[] args) {
		
		method(new Student());	//Anonymous object
		
		Worker worker = new Worker(); 
		method1(worker);	//Non anonymous class non anonymous object
		
		method1(new Worker());	//Non anonymous class object
		
		System.out.println("*********************");
		
		//Created an object with an anonymous subclass: p
		Person p = new Person(){

			@Override
			public void eat() {
				System.out.println("Eat something");
			}

			@Override
			public void breath() {
				System.out.println("Breathe air");
			}
			
		};
		method1(p);
		System.out.println("**********************"); 
		//Create anonymous objects of anonymous subclasses
		method1(new Person(){

			@Override
			public void eat() {
				System.out.println("eat snacks between meals");
			}

			@Override
			public void breath() {
				System.out.println("Air in Yunnan");
			}
			
		});
	}
	
	public static void method1(Person p){
		p.eat();
		p.walk();
	}
	
	public static void method(Student s){
		
	}
}
class Worker extends Person{
	
	@Override
	public void eat() {
	}

	@Override
	public void breath() {
	}
}

5.4. Application of polymorphism: template method

Abstract class embodies the design of a template pattern. Abstract class is the general template of multiple subclasses. Subclasses expand and transform on the basis of abstract class, but subclasses will retain the behavior of abstract class as a whole.

Problems solved:

When part of the internal implementation of a function is certain, part of the implementation is uncertain. At this time, you can expose the uncertain part and let the subclass implement it.
In other words, when implementing an algorithm in software development, the overall steps are fixed and general, and these steps have been written in the parent class. However, some parts are changeable, and the changeable parts can be abstracted for different subclasses to implement. This is a template pattern.

1. Example 1

/*
 * Application of abstract classes: design patterns of template methods
 */
public class TemplateTest {
	public static void main(String[] args) {
		
		SubTemlate t = new SubTemlate();
		
		t.sendTime();
	}
}
abstract class Template{
	
	//Calculate the time it takes for a piece of code to execute
	public void sendTime(){
		
		long start = System.currentTimeMillis();
		
		code();	//Uncertain part
		
		long end = System.currentTimeMillis();
		
		System.out.println("Time spent is:" + (end - start));
	}
	
	public abstract void code();
}

class SubTemlate extends Template{
	
	@Override
	public void code() {
		
		for(int i = 2;i <= 1000;i++){
			boolean isFlag = true;
			for(int j = 2;j <= Math.sqrt(i);j++){
				if(i % j == 0){
					isFlag = false;
					break;
				}
			}
			if(isFlag){
				System.out.println(i);
			}
		}
	}
}

2. Example 2

//Application of abstract classes: design patterns of template methods
public class TemplateMethodTest {

	public static void main(String[] args) {
		BankTemplateMethod btm = new DrawMoney();
		btm.process();

		BankTemplateMethod btm2 = new ManageMoney();
		btm2.process();
	}
}
abstract class BankTemplateMethod {
	// Specific method
	public void takeNumber() {
		System.out.println("Number queuing");
	}

	public abstract void transact(); // Handle specific business / / hook method

	public void evaluate() {
		System.out.println("Feedback score");
	}

	// Template method, which combines basic operations together. Subclasses generally cannot be overridden
	public final void process() {
		this.takeNumber();

		this.transact();// Like a hook, the implementation code of the subclass will be executed when the subclass is hung

		this.evaluate();
	}
}

class DrawMoney extends BankTemplateMethod {
	public void transact() {
		System.out.println("I want to withdraw money!!!");
	}
}

class ManageMoney extends BankTemplateMethod {
	public void transact() {
		System.out.println("I want money! I have $20 million here!!");
	}
}

Template method design pattern is often used in programming. His shadow can be found in various frameworks and class libraries. For example, the common ones are:

  • Encapsulation of database access
  • Junit unit test
  • On doGet/doPost method call in Java Web Servlet
  • Template program in Hibernate
  • JDBC te mlate, hibernate template, etc. in Spring

5.5 practice of abstract class


1. Employee class

/*
 * Define an Employee class,
 * This class contains: private member variables name,number,birthday,
 * Where birthday is the object of MyDate class;
 * abstract Methods learning ();
 * toString()Method outputs the name,number, and birthday of the object.
 * 
 */
public abstract class Employee {
	private String name;
	private int number;
	private MyDate birthday;
	
	public Employee(String name, int number, MyDate birthday) {
		super();
		this.name = name;
		this.number = number;
		this.birthday = birthday;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getNumber() {
		return number;
	}

	public void setNumber(int number) {
		this.number = number;
	}

	public MyDate getBirthday() {
		return birthday;
	}

	public void setBirthday(MyDate birthday) {
		this.birthday = birthday;
	}

	public abstract double earnings();

	@Override
	public String toString() {
		return "name=" + name + ", number=" + number + ", birthday=" + birthday.toDateString() + "]";
	}
	
}

2. MyDate class

/*
 * MyDate Class contains: private member variables year,month,day;
 * toDateString()Method returns the string corresponding to the date: xxxx mm / DD / yyyy
 */
public class MyDate {
	private int year;
	private int month;
	private int day;
	
	public MyDate(int year, int month, int day) {
		super();
		this.year = year;
		this.month = month;
		this.day = day;
	}

	public int getYear() {
		return year;
	}

	public void setYear(int year) {
		this.year = year;
	}

	public int getMonth() {
		return month;
	}

	public void setMonth(int month) {
		this.month = month;
	}

	public int getDay() {
		return day;
	}

	public void setDay(int day) {
		this.day = day;
	}

	public String toDateString(){
		return year + "year" + month + "month" + day + "day";
	}
}

3. SalariedEmployee class

/*
 * Define the SalariedEmployee class, inherit the Employee class, and realize the employee processing of monthly salary calculation.
 * This class includes: private member variable monthlySalary; Implement the abstract method of the parent class, ears(),
 * This method returns the value of monthlySalary;
 * toString()Method to output employee type information and employee name, number,birthday.
 * 
 */
public class SalariedEmployee extends Employee{
	private double monthlySalary;	//Monthly salary

	public SalariedEmployee(String name,int number,MyDate birthday) {
		super(name,number,birthday);
	}
	
	public SalariedEmployee(String name, int number, MyDate birthday, double monthlySalary) {
		super(name, number, birthday);
		this.monthlySalary = monthlySalary;
	}

	@Override
	public double earnings() {
		return monthlySalary;		
	}

	@Override
	public String toString() {
		return "SalariedEmployee [" + super.toString() + "]";
	}	
}

4. HourlyEmployee class

/*
 * Define HourlyEmployee class by referring to SalariedEmployee class,
 * Realize the processing of employees whose wage s are calculated by hour. This class includes: private member variables, wave and hour;
 * Implement the abstract method of the parent class, ears (), which returns the value of wait * hour;
 * toString()Method to output employee type information and employee name, number,birthday.
 * 
 */
public class HourlyEmployee extends Employee{
	private int wage;	//Hourly wage
	private int hour;	//Working hours per month
	
	public HourlyEmployee(String name, int number, MyDate birthday) {
		super(name, number, birthday);
	}

	public HourlyEmployee(String name, int number, MyDate birthday, int wage, int hour) {
		super(name, number, birthday);
		this.wage = wage;
		this.hour = hour;
	}

	@Override
	public double earnings() {
		return wage*hour;
	}

	public int getWage() {
		return wage;
	}

	public void setWage(int wage) {
		this.wage = wage;
	}

	public int getHour() {
		return hour;
	}

	public void setHour(int hour) {
		this.hour = hour;
	}
	
	public String toString(){
		return "HourlyEmployee[" + super.toString() + "]"; 
	}
}

5. Payroll system class

import java.util.Calendar;
import java.util.Scanner;
/*
 * Define the payroll system class, create and initialize the Employee variable array,
 * This array holds references to various employee objects. Use the loop structure to traverse the array elements,
 * Output the type, name,number,birthday, and birthday of each object.
 * When the current month value is entered on the keyboard,
 * If this month is the birthday of an Employee object, you should also output salary increase information.
 * 
 */
public class PayrollSystem {
	public static void main(String[] args) {
		//Mode 1:
//		Scanner scanner = new Scanner(System.in);
//		System.out.println("please enter the month of the current month:");
//		int month = scanner.nextInt();
		
		//Mode 2:
		Calendar calendar = Calendar.getInstance();
		int month = calendar.get(Calendar.MONTH);//Gets the current month
//		System.out.println(month);// January: 0
		
		Employee[] emps = new Employee[2];
		
		emps[0] = new SalariedEmployee("maleonn ", 1002,new MyDate(1992, 2, 28),10000);
		emps[1] = new HourlyEmployee("Bossy ", 2001, new MyDate(1991, 1, 6),60,240);
		
		for(int i = 0;i < emps.length;i++){
			System.out.println(emps[i]);
			double salary = emps[i].earnings();
			System.out.println("The monthly salary is:" + salary);
			
			if((month+1) == emps[i].getBirthday().getMonth()){
				System.out.println("Happy birthday! Reward 100 yuan");
			}
			
		}
	}
}

06. Interface

6.1 overview

On the one hand, sometimes you must derive a subclass from several classes and inherit all their properties and methods. However, Java does not support multiple inheritance. With an interface, you can get the effect of multiple inheritance.

On the other hand, sometimes we must extract some common behavior characteristics from several classes, and there is no is-a relationship between them, just have the same behavior characteristics. For example, USB connection is supported for mouse, keyboard, printer, scanner, camera, charger, MP3 player, mobile phone, digital camera, mobile hard disk, etc.

An interface is a specification. It defines a set of rules, which embodies the idea of "if you are / want to..., you must be able to..." in the real world. Inheritance is a yes / no relationship, while interface implementation is a yes / no relationship.

The essence of interface is contract, standard and specification, just like our law. After making it, everyone should abide by it.

/* An interface is a collection of abstract methods and constant value definitions.
 * Interface features:
 * Defined by interface.
 * All member variables in the interface are modified by public static final by default.
 * All abstract methods in the interface are modified by public abstract by default.
 * There is no constructor in the interface.
 * The interface adopts multi inheritance mechanism.
 */

/*
 * Use of interfaces
 * 1.Interfaces are defined using interface s.
 * 2.In Java: interface and class are two structures in parallel
 * 3.How to define two interfaces: define the members in the interface
 * 	>3.1 JDK7 And before: only global constants and abstract methods can be defined
 * 		>Global constant: public static final, but it can be omitted from writing.
 * 		>Abstract method: public abstract
 * 
 *  >3.2 JDK8:In addition to global constants and abstract methods, static methods and default methods can also be defined (omitted).
 * 
 * 4.Constructor cannot be defined in interface! This means that the interface cannot be instantiated.
 * 
 * 5.Java In development, interfaces are used by letting classes implement.
 *   If the implementation class covers all the methods in the interface, the implementation class can be instantiated
 *   If the implementation class does not cover all the abstract methods in the interface, the implementation class is still an abstract class
 * 
 * 6.Java Class can implement multiple interfaces -- "makes up for the limitation of Java single inheritance
 *  Format: Class AA extends BB implemented CC, DD, EE
 *  
 *  7.There is inheritance between interfaces, and multiple inheritance is allowed
 *  
 **********************************
 * 8.The specific use of the interface reflects polymorphism
 * 	   The main purpose of the interface is to be implemented by the implemented class. (interface oriented programming)
 * 9.Interface can actually be regarded as a specification
 * 
 * Interview question: what are the similarities and differences between abstract classes and interfaces?
 *  
 */
public class InterfaceTest {
	public static void main(String[] args) {
		System.out.println(Flayable.MAX_SPEED);
		System.out.println(Flayable.MIN_SPEED);
	}
}
interface Flayable{
	
	//global variable
	public static final int MAX_SPEED = 7900;	
	int MIN_SPEED = 1;//public static final is omitted 
	
	//Abstract method
	public abstract void fly();
	
	void stop();//public abstract is omitted 
	//Interfaces cannot have constructors
//	public Flayable(){
//		
//	}	
}
interface Attackable{
	void attack();
}

class Plane implements Flayable{

	@Override
	public void fly() {
		System.out.println("The plane took off by engine");
		
	}

	@Override
	public void stop() {
		System.out.println("Driver deceleration stop");
	}
	
}
abstract class Kite implements Flayable{

	@Override
	public void fly() {
		
	}
}

class Bullet extends Object implements Flayable,Attackable,CC{

	@Override
	public void attack() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void fly() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void stop() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void method1() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void method2() {
		// TODO Auto-generated method stub
		
	}
}

//*********************************
interface AA{
	void method1();
}
interface BB{
	void method2();
}
interface CC extends AA,BB{
	
}


6.2 examples

/*
 * Use of interfaces
 * 1.The interface also meets polymorphism
 * 2.Interface actually defines a specification
 * 3.Experience interface oriented programming in development!
 * 
 */
public class USBTest {
	public static void main(String[] args) {
		
		Computer com = new Computer();
		//1. Create a non anonymous object of the non anonymous implementation class of the interface
		Flash flash = new Flash();
		com.transferData(flash); 
		//2. Create the anonymous object of the non anonymous implementation class of the interface
		com.transferData(new Printer());
		//3. Create a non anonymous object of the anonymous implementation class of the interface
		USB phone = new USB(){

			@Override
			public void start() {
				System.out.println("The phone starts working");
			}

			@Override
			public void stop() {
				System.out.println("End of mobile phone work");
			}
			
		};
		com.transferData(phone);
		//4. Create the anonymous object of the anonymous implementation class of the interface
		com.transferData(new USB(){
			@Override
			public void start() {
				System.out.println("mp3 start-up");
			}

			@Override
			public void stop() {
				System.out.println("mp3 power cut-off");
			}
		});
	}
}

class Computer{
	
	public void transferData(USB usb){//USB usb = new Flash();
		usb.start();
		
		System.out.println("Details of specific transmission data");
		
		usb.stop();
	}
	
}

interface USB{
	//Constant: defines the length and width
	void start();
	
	void stop();
}
class Flash implements USB{

	@Override
	public void start() {
		System.out.println("U The disk starts working");
	}

	@Override
	public void stop() {
		System.out.println("U Disk end work");
	}
}
class Printer implements USB{
	@Override
	public void start() {
		System.out.println("Printer on");
	}

	@Override
	public void stop() {
		System.out.println("Printer finished working");
	}
	
}

6.3. Interface application: proxy mode

Proxy pattern is a design pattern used more in Java development. Proxy design is to provide a proxy for other objects to control access to this object.

/*
 * Application of interface: proxy mode
 * 
 * 
 */
public class NetWorkTest {
	public static void main(String[] args) {
		
		Server server = new Server();
//		server.browse();
		ProxyServer proxyServer = new ProxyServer(server);
		
		proxyServer.browse();
	}
}
interface NetWork{
	public void browse();
	
}
//Proxy class
class Server implements NetWork{


	@Override
	public void browse() {
		System.out.println("Real servers to access the network");
	}
}
//proxy class
class ProxyServer implements NetWork{
	
	private NetWork work;
	
	public ProxyServer(NetWork work){
		this.work = work;
	}
	
	public void check(){
		System.out.println("Inspection before networking");
	}

	@Override
	public void browse() {
		check();
		
		work.browse();
	}
	
}

Application scenario:

  • Security proxy: block direct access to real roles.
  • Remote proxy: Handling remote method calls (RMI) through proxy classes
  • Delayed loading: load lightweight proxy objects first, and then load real objects if you really need to. For example, if you want to develop a large document viewing software, there are large pictures in a large document, maybe a picture has 100MB. When you open a file, it is impossible to display all the pictures. In this way, you can use the proxy mode. When you need to view pictures, Use proxy to open large pictures.

classification

  • Static proxy (statically defined proxy class)
  • Dynamic proxy (dynamically generate proxy classes)
    • JDK's own dynamic agent requires reflection and other knowledge
public class StaticProxyTest {

	public static void main(String[] args) {
		Proxy s = new Proxy(new RealStar());
		s.confer();
		s.signContract();
		s.bookTicket();
		s.sing();
		s.collectMoney();
	}
}

interface Star {
	void confer();// interview

	void signContract();// sign a contract

	void bookTicket();// booking

	void sing();// sing

	void collectMoney();// Collect money
}
//Proxy class
class RealStar implements Star {

	public void confer() {
	}

	public void signContract() {
	}

	public void bookTicket() {
	}

	public void sing() {
		System.out.println("Star: singing~~~");
	}

	public void collectMoney() {
	}
}

//proxy class
class Proxy implements Star {
	private Star real;

	public Proxy(Star real) {
		this.real = real;
	}

	public void confer() {
		System.out.println("Broker interview");
	}

	public void signContract() {
		System.out.println("Broker sign contract");
	}

	public void bookTicket() {
		System.out.println("Broker Booking");
	}

	public void sing() {
		real.sing();
	}

	public void collectMoney() {
		System.out.println("Brokers collect money");
	}
}

6.4 interface application: factory mode

expand: Factory design pattern.pdf

Comparison between interface and abstract class

 No. | Distinguishing points    | abstract class                                             | Interface                        
 --- | ------ | ----------------------------------------------- | -------------------------- 
 1   | definition     | Class containing abstract methods                                        | It is mainly a collection of abstract methods and global constants           
 2   | form     | Construction method, abstract method, ordinary method, constant, variable                            | Constants, abstract methods(jdk8.0:Default method, static method)
 3   | use     | Subclasses inherit abstract classes(extends)                                | Subclass implementation interface(implements)        
 4   | relationship     | Abstract classes can implement multiple interfaces                                     | Interfaces cannot inherit abstract classes&#xff0c; However, it is allowed to inherit multiple interfaces
 5   | Common design patterns | Template method                                            | Simple factory, factory method, agent model            
 6   | object     | Instantiated objects are generated through the polymorphism of objects                                |                           
 7   | limit     | Abstract classes have the limitation of single inheritance                                      | Interfaces do not have this limitation                   
 8   | actual     | As a template                                          | Is it a standard or a capability           
 9   | choice     | If both abstract classes and interfaces can be used&#xff0c;Preferred interface&#xff0c; Because of the limitations of avoiding single inheritance|                           

In development, we often see that a class does not inherit an implemented class, but either inherits an abstract class or implements an interface.
-[interview questions] Troubleshooting:

interface A {
	int x = 0;
}
class B {
	int x = 1;
}
class C extends B implements A {
	public void pX() {
//		Compilation failed, x ambiguous
		System.out.println(x);
//		System.out.println(super.x); //1
//		System.out.println(A.x);//0
	}
	public static void main(String[] args) {
		new C().pX();
	}
}

Troubleshooting 2:

interface Playable {
	void play();
}
interface Bounceable {
	void play();
}
interface Rollable extends Playable, Bounceable {
	Ball ball= new Ball("PingPang"); //public static final is omitted
}
public class Ball implements Rollable {
	private String name;
	public String getName() {
		return name;
	}
	public Ball(String name) {
		this.name= name;
	}
	public void play() {
		ball = new Ball("Football"); //The final field Rollable.ball cannot be assigned	
		System.out.println(ball.getName());
	}
}

practice

CompareObject class

/*
 * Define an interface to compare two objects.
 * 
 */
public interface CompareObject {
	public int compareTo(Object o);
	//If the return value is 0, it means equal; If it is a positive number, it means that the current object is large; A negative number indicates that the current object is small
	
}

Circle class

/*
 * Define a Circle class, declare the redius attribute, and provide getter and setter methods
 */
public class Circle {
	
	private Double radius;

	public Double getRadius() {
		return radius;
	}

	public void setRadius(Double radius) {
		this.radius = radius;
	}

	public Circle() {
		super();
	}

	public Circle(Double radius) {
		super();
		this.radius = radius;
	}
		
}

ComparableCircle class

/*
 * Define a ComparableCircle class, inherit the Circle class and implement the CompareObject interface. Give the implementation body of the method compareTo in the interface in the ComparableCircle class,
 * Used to compare the radius of two circles.
 */
public class ComparableCircle extends Circle implements CompareObject{

	public ComparableCircle(double radius) {
		super(radius);
	}
	@Override
	public int compareTo(Object o) {
		if(this == o){
			return 0;
		}
		if(o instanceof ComparableCircle){
			ComparableCircle c = (ComparableCircle)o;
			//Wrong writing
//			return (int)(this.getRedius() - c.getRedius());
			//Correct way 1:
//			if(this.getRadius() > c.getRadius()){
//				return 1;
//			}else if(this.getRadius() < c.getRadius()){
//				return -1;
//			}else{
//				return 0;
//			}
			//When the attribute radius is declared as a Double type, the method of the wrapper class can be called
			//Correct way 2:
			return this.getRadius().compareTo(c.getRadius());
		}else{
			return 0;
//			throw new RuntimeException("incoming data type mismatch");
		}
	}
}

InterfaceTest class

/*
 * Define a test class InterfaceTest and create two ComparableCircle objects,
 * Call the compareTo method to compare the radius of the two classes.
 * 
 */
public class InterfaceTest {
	public static void main(String[] args) {
		
		ComparableCircle c1 = new ComparableCircle(3.4);
		ComparableCircle c2 = new ComparableCircle(3.6);
		
		int compareValue = c1.compareTo(c2);
		if(compareValue > 0){
			System.out.println("c1 Large object");
		}else if(compareValue < 0){
			System.out.println("c2 Large object");
		}else{
			System.out.println("Two of the same");
		}
		
		int compareValue1 = c1.compareTo(new String("AA"));
		System.out.println(compareValue1);
	}
}

07. Improvement of interface in Java 8

In Java 8, you can add static methods and default methods for interfaces. From a technical point of view, this is completely legal, but it seems to violate the concept of interface as an abstract definition.

Static method:

Use the static keyword to decorate. You can call static methods directly through the interface and execute their method bodies. We often use static methods in classes that work with each other. You can find paired interfaces and classes such as Collection/Collections or Path/Paths in the standard library.

Default method:

The default method is decorated with the default keyword. Can be called by implementing class objects. We provide new methods in the existing interfaces while maintaining compatibility with the old version of the code. For example, the java 8 API provides rich default methods for interfaces such as Collection, List and Comparator.

Example 1

interface class

/*
 * JDK8:In addition to global constants and abstract methods, static methods and default methods can also be defined (omitted).
 * 
 * 
 */
public interface CompareA {

	//Static method
	public static void method1() {
		System.out.println("CompareA:Xi'an");
	}
	
	//Default method
	public default void method2(){
		System.out.println("CompareA:Shenzhen");
	}
	
	default void method3(){
		System.out.println("CompareA:Hangzhou");
	}
}

SubClassTest class

public class SubClassTest {

	public static void main(String[] args) {
		SubClass s = new SubClass();
//		s.method1();
//		SubClass.method1();
//		Knowledge point 1: static methods defined in the interface can only be called through the interface.
		CompareA.method1();
//		Knowledge point 2: by implementing the object of the class, you can call the default method in the interface.
//		If the implementation class overrides the default method in the interface, the overridden method will still be called
		s.method2();
//		Knowledge point 3: if the parent class inherited by the subclass (or implementation class) and the implemented interface declare a default method with the same name and parameter,
//		If the subclass does not override this method, it will call the method with the same name and parameter in the parent class by default. -- > Class priority principle
//		Knowledge point 4: if the implementation class implements multiple interfaces and default methods with the same name and parameters are defined in these interfaces,
//		If the implementation class does not override this method, an error will be reported. -- > Interface conflict.
//		This requires that we must override this method in the implementation class
		s.method3();
		
	}
}
class SubClass extends SuperClass implements CompareA,CompareB{
	
	public void method2(){
		System.out.println("SubClass: Shanghai");
	}
	
	public void method3(){
		System.out.println("SubClass: Shenzhen");
	}
	
//	Knowledge point 5: how to call the parent class in the subclass (or implementation class) method and the method to be rewritten in the interface.
	public void myMethod(){
		method3(); //Call your own defined overridden method
		super.method3(); //Called is declared in the parent class
//		Call the default method in the interface
		CompareA.super.method3();
		CompareB.super.method3();
	}
}

SuperClass class

public class SuperClass {
	public void method3(){
		System.out.println("SuperClass:Beijing");
	}
}

CompareB class

public interface CompareB {
	default void method3(){
		System.out.println("CompareB: Shanghai");
	}
}

Example 2

/*
 * Exercise: resolving interface conflicts
 */
interface Filial {// filial
	default void help() {
		System.out.println("Mom, I'm here to save you");
	}
}

interface Spoony {// Infatuated
	default void help() {
		System.out.println("Daughter in law, don't be afraid, I'm coming");
	}
}

class Father{
	public void help(){
		System.out.println("Son, save my daughter-in-law!");
	}
}

class Man extends Father implements Filial, Spoony {

	@Override
	public void help() {
		System.out.println("Who should I be?");
		Filial.super.help();
		Spoony.super.help();
	}
	
}

08. Internal member 5 of class: internal class

When there is an internal part of a thing that needs a complete structure to describe, and the internal complete structure only provides services for external things, it is best to use the internal class for the whole internal complete structure.

/*
 * Inner member of class 5: inner class
 * 
 * 1.Java Class A is allowed to be declared in another class B, then class A is the inner class and class B is the outer class
 * 
 * 2.Classification of internal classes: member internal classes 	 VS 	 Local internal classes (within methods, code blocks, constructors)
 * 		
 * 3.Member inner class
 * 	>As a member of an external class,
 * 		- Calling the structure of an external class
 * 		- Can be modified by static
 * 		- It can be modified by four different permissions
 * 
 *  >As a class,
 *  	- Properties, methods, constructors, etc. can be defined within a class
 *  	- Can be modified by final to indicate that this class cannot be inherited. The implication is that you can inherit without using final
 *  	- Can be abstract modified
 * 
 * 4.Focus on the following three issues
 *   > How to instantiate an object of a member's inner class
 *   > How to distinguish the structure of calling external classes in member internal classes
 *   > See InnerClassTest1.java for the use of local internal classes during development
 */
public class InnerClassTest {
	public static void main(String[] args) {
		
		//Create a Dog instance (static member inner class)
		Person.Dog dog = new Person.Dog();
		dog.show();
		
		//Create Bird instance (non static member inner class)
//		Person.Bird bird = new Person.Bird();
		Person p = new Person();
		Person.Bird bird = p.new Bird();
		bird.sing();
		
		System.out.println();
		
		bird.display("Magpie");
	}
}
class Person{
	String name = "Li Lei";
	int age;
	
	public void eat(){
		System.out.println("People, eat");
	}
	
	//Static member inner class
	static class Dog{
		String name;
		int age;
		
		public void show(){
			System.out.println("Carla is a dog");
//			eat();
		}
	}
	
	//Non static member inner class
	class Bird{
		String name = "cuckoo";
		public Bird(){
			
		}
		
		public void sing(){
			System.out.println("i'm an owl ");
			Person.this.eat();//Calling non static properties of an external class
			eat();
			System.out.println(age);
		}
		
		public void display(String name){
			System.out.println(name);	//Formal parameters of method
			System.out.println(this.name);	//Properties of inner classes
			System.out.println(Person.this.name);	//Properties of external classes
		}
	}
	public void method(){
		//Local inner class
		class AA{
			
		}
	}
	
	{
		//Local inner class
		class BB{
			
		}
	}
	
	public Person(){
		//Local inner class
		class CC{
			
		}
	}
}

InnerClassTest1 class

public class InnerClassTest1 {
	
//	Rare in development
	public void method(){
//		Local inner class
		class AA{
			
		}
	}
	
//	Returns an object of a class that implements the Comparable interface
	public Comparable getComparable(){
		
//		Create a class that implements the Comparable interface: a local inner class
		//Mode 1:
//		class MyComparable implements Comparable{
//
//			@Override
//			public int compareTo(Object o) {
//				return 0;
//			}
//			
//		}
//		
//		return new MyComparable();
		
		//Mode 2:
		return new Comparable(){


			@Override
			public int compareTo(Object o) {
				return 0;
			}
			
		};
		
	}
}

8.1. Anonymous inner class

/*
 * 1.Anonymous inner classes cannot define any static members, methods and classes. Only one instance of anonymous inner classes can be created.
 * An anonymous inner class must be behind new, which implicitly implements an interface or class.
 * 
 * 2.Format:
 * 		new Parent class constructor (argument list) | implementation interface (){
 * 				//The body part of an anonymous inner class
 * 		}
 * 
 * 3.Characteristics of anonymous inner classes
 * 		> Anonymous inner classes must inherit from parent classes or implement interfaces
 * 		> An anonymous inner class can only have one object
 * 		> Anonymous inner class objects can only be referenced in polymorphic form
 */
interface Product{
	public double getPrice();
	public String getName();
}
public class AnonymousTest{
	public void test(Product p){
		System.out.println("Bought one" + p.getName() + ",It's gone" + p.getPrice());
	}
	public static void main(String[] args) {
		AnonymousTest ta = new AnonymousTest();
		//When calling the test method, you need to pass in a Product parameter,
		//Pass in an instance of its anonymous implementation class here
		ta.test(new Product(){
			public double getPrice(){
				return 567.8;
			}
			public String getName(){
				return "AGP Graphics card";
			}
		});
	}
}

8.2. Precautions for the use of local internal classes

public class InnerClassTest {
	
//	public void onCreate(){
//	
//	int number = 10;
//	
//	View.OnClickListern listener = new View.OnClickListener(){
//		
//		public void onClick(){
//			System.out.println("hello!");
//			System.out.println(number);
//		}
//		
//	}
//	
//	button.setOnClickListener(listener);
//	
//}

	/*
	 * In the method of the local inner class (for example, show), if you call the local variable (for example, num) in the method declared by the local inner class (for example, method),
	 * This local variable is required to be declared final.
	 * 
	 * jdk 7 And previous versions: this local variable is required to be explicitly declared final
	 * jdk 8 And later versions: the declaration of final can be omitted
	 * 
	 */
	public void method(){
		//local variable
		int num = 10;
		
		class AA{
			
			public void show(){
//				num = 20;	//Local variable num defined in an enclosing scope must be final or effectively final
				System.out.println(num);
			}
		}
	}
}

Tags: Java

Posted on Sun, 03 Oct 2021 19:41:13 -0400 by Stanza