8, Object oriented programming

Posted by astaroth on Mon, 25 Oct 2021 10:09:34 +0200

1. Introduction of static keyword

  • When we write a class, we are actually describing the properties and behavior of its object, without producing a substantial
    Object, only through new Keyword will generate the object, and then the system will allocate memory space to the object,
    Its method can be called externally. We sometimes hope that no matter whether objects are generated or how many are generated
    In the case of objects, There is only one copy of certain data in the memory space For example, all Chinese have one
    Country name. Every Chinese shares this country name, which does not have to be in every Chinese instance object
    A variable representing the name of the country is assigned separately. (original content of PPT)

2. Comparison between static variables and instance variables (see the code below)

3. Other descriptions of static modifier attribute (see the code below)

4. Memory parsing of class variables and instance variables (see the code below)

5.static modification method (see the code below)

6. Experience on whether attributes or methods should be static

package com.atshangguigu.java;
/*
 * static Use of keywords
 * 1.static:Static
 * 2.static Can be used to modify: attribute method code block internal class
 * 3.Use static to modify attributes: static variables (or class variables)
 * 		3.1 Attribute: static attribute vs non static attribute (instance variable) according to whether static modification is used
 * 			    	Instance variables: we have created multiple objects of the class. Each object has an independent set of instance variables and non static attributes in the class
 * 							Modifying the non - static property of one object will not change the same property value of other objects
 *                  Static variable: we create multiple objects of the class, and multiple objects share the same static variable. When modifying a static variable through an object
 *                          Variable will cause other objects to be modified when calling (kitchen and toilet can be understood as this)
 *	    3.2 static Additional description of modified attributes:
 *				1.Static variables are loaded with class loading and can be called by "class. Static variables"
 *				2.The loading of static variables is earlier than the creation of objects, and instance objects appear only after objects
 *				3.Since the class is loaded only once, there will be only one static variable in memory - cached: in the static field of the method area
 *				4.  Class variable instance variable
 *				Class ok      
 *				Object ok ok	        
 * 		3.3 Examples of static attributes: system.out;Math.PI;
 * 
 * 
 * 4.Using static to decorate methods: static methods
 * 		1.Static methods are loaded with the loading of classes, and can be called through "class. Static method"
 	    2.            Static method non static method
 *				Class ok      
 *				Object ok ok	  
 *		3.Static methods can only call static methods or properties
 *		    In non static methods, you can call either non static methods or properties, or static methods or properties
 * 5.static Note:
 * 		1.this keyword super keyword cannot be used within a static method
 * 		2.The use of static attributes and methods is understood from the perspective of life cycle
 * 6. How to determine whether a property should be declared as a static during development?
 * 		A: (student No. 5 Qian, please answer [why did you take off your glasses], and will not answer: not for the time being)
 * 		Properties can be shared by multiple objects and will not vary with different objects

 *    During the development process, how to determine whether a method should declare a static?
 *    	A: the method of operating static attributes is usually set to static
 *    	      The methods of tool classes are generally declared as static, such as Math Arrays Collections 

 */
public class Static 
{
	public static void main(String[] args) {
		
		Chinese.nation = "China";//The meaning here is to load as the class is loaded,
		//Chinese.name = "SpongeBob"// Using this class to call this property cannot be called, and the compilation does not pass
		Chinese.show();
		Chinese c1 = new Chinese();
		c1.name = "a brand of instant noodles";
		c1.age = 41;
		
		Chinese c2 = new Chinese();
		c2.name = "Baoqiang";
		c2.age = 38;
		
		c1.nation = "CHN";//Modification of Static --- Beijing, Shanghai, Guangzhou and Shenzhen, and now Hangzhou is rising
		System.out.println(c2.nation);//(the teacher said Tianjin is also good! --- the sky is confused)
	}
}
//Chinese
class Chinese
{
	String name;
	int age;
	static String nation;
	
	public void eat()
	{
		System.out.println("Mutton steamed buns in Shaanxi are delicious");
		//Call non static structure
		this.info();
		//Call static structure
		fly();
		System.out.println("nation:" + nation);//The nation here is equivalent to Chinese.nation
	}
	public static void show()//Load as the class loads --- call through the class
	{
		System.out.println("I am a decent Chinese");
		//You can call static structures, not non static structures
		System.out.println(nation);//What is omitted here is not this. But Chinese
		fly();
	}
	public void info()
	{
		System.out.println("name:" + name + ",age:" + age);
	}
	public static void fly()
	{
		System.out.println("I can fly");
	}
}

7. Optimization of custom ArrayUtil tool class

  • Do a small exercise (improve on the previous basis)
  • ArrayUtil.java
package com.atshangguigu.java;
/*
 * Tool class for custom array
 */
public class ArrayUtil {

	//Find the maximum value
	public static int getMax(int[] arr)
	{
		int max = arr[0];//Maximum
		for(int i = 0;i < arr.length;i++)
		{
			if(max < arr[i])
			{
				max = arr[i];
			}

		}

		return max;
		
	}
	//Find the minimum value
	public static int getMin(int[] arr)
	{

		int min = arr[0];//minimum value
	
		for(int i = 0;i < arr.length;i++)
		{
		
			if(min > arr[i])
			{
				min = arr[i];
			}
			
		}
	
		return min;
	}
	//Sum
	public static int getSum(int[] arr)
	{

		int add = 0;
	
		for(int i = 0;i < arr.length;i++)
		{
		
			add += arr[i];
			
		}

		return add;
		
	}
	//Average
	public static double getAvg(int[] arr)
	{
	
		int add = 0;
		double ava;
		for(int i = 0;i < arr.length;i++)
		{
			
			add += arr[i];
			
		}
		ava = add/(arr.length);
		return ava;
		
	}
	//reversal
	public static void reverse(int[] arr)
	{
		for(int i = 0,j = arr.length-1;i < j;i++,j--)  
		{
			int temp = arr[i];
			arr[i] = arr[j];
			arr[j] = temp;
		}
		
	}
	//copy
	public static int[] copy(int[] arr)
	{
		int[] arr1 = new int[arr.length];
		for(int i = 0;i < arr.length;i++)
		{
			arr1[i] = arr[i];
		}
		return arr1;
		
	}
	//sort
	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;
					*/
					swap(arr,j,j+1);
				}
			}
		}
	}
	public static void swap(int[] arr,int i,int j)
	{
		int temp = arr[i];
		arr[i] = arr[j];
		arr[j] = temp;
	}
	//ergodic
	public static void print(int[] arr)
	{
		for(int i = 0;i < arr.length;i++)
		{
			System.out.print(arr[i] + "\t");
		}
	}
	//lookup
	public static int getIndex(int[] arr,int dest)
	{
		
		for(int i = 0;i < arr.length;i++ )
		{
			if(dest == arr[i])//Note the use of equals()
			{
				System.out.println("congratulations,Found it!");
			
				return i;//Replace break
			}
		}
		return -1;//Returns a negative number indicating that it was not found
		
		
	}
}
  • ArrayUtilTest.java

package com.atshangguigu.java;

public class ArrayUtilTest {
public static void main(String[] args) {
	
	//ArrayUtil util = new ArrayUtil();
	int[] arr = new int[]{32,3,1,64,56,5,6,99,56,102,95,88,213,1,23,465,114,954};
	int max = ArrayUtil.getMax(arr);
	System.out.println("The maximum value is" + max);
	System.out.print("Before sorting:");
	ArrayUtil.print(arr);
	System.out.println();
	System.out.print("After sorting:");
	ArrayUtil.sort(arr);
	ArrayUtil.print(arr);
	
	System.out.println("lookup");
	int index = ArrayUtil.getIndex(arr, 5);
	if(index != 0)
	{System.out.println("eureka,The index address is:" + index);
	}
	else
	{System.out.println("Can't find");
	}
	
}
}

8. Application examples of static

package com.atshangguigu.java;
/*
 * static Use of keywords
 */
public class CircleTest {
public static void main(String[] args) {
	Circle c1 = new Circle();
	Circle c2 = new Circle(); 
	Circle c3 = new Circle(3.4);
	System.out.println("c1 of id yes:" + c1.getId());
	System.out.println("c2 of id yes:" + c2.getId());
	System.out.println("c3 of id yes:" + c3.getId());
	System.out.println("Number of circles created:"  + Circle.getTotal());
	//final is a constant flag: it will be mentioned later: constants in classes are generally declared as static
}
}
class Circle
{   //attribute
	private double radius;
	private int id;
	//An added method was called
	public Circle()
	{
		id = into++;//The withdrawal here is to increase in the static state
		total ++;
	}
	public Circle(double radius)
	{
		this();//Equivalent to the code written below
		/*id = into++;//The withdrawal here is to increase in the static state
		total ++;//((note here)
		*/
		this.radius = radius;
	}
	//Private properties
	private static int total;//Record the number of circles
	private static int into = 1000;//static declared properties are shared by all objects
	//method
	public double findArea()
	{
		return Math.PI * radius * radius;
	}
	//A method of get and set
	public double getRadius() {
		return radius;
	}
	public void setRadius(double radius) {
		this.radius = radius;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public static int getTotal() {//If a property is static, its method defaults to static
		return total;
	}

}

9.static after class exercise: account information

  • Account.java
package com.atshangguiguexer;
/*
        Write a class to realize the concept of bank account. The attributes include "account number", "password", "deposit balance", "interest rate" and "minimum balance". Define and encapsulate these attributes
 Property. 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 {
	//1. Properties
	private int id;
	private String pwd = "19991123";//password
	private double banlance;
	
	private static double interestRate;//interest rate
	private static double minMoney = 1.0;
	private static int init = 1001;//Auto generate id
	//2. Statement of method of conduct
	//If the original attribute is static, its method is still static
	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 getBanlance() {
		return banlance;
	}
	//3. Constructor
	public Account()
	{
		id = init++;
	}
	public Account(String pwd,double banlance)
	{
		this();
		this.pwd = pwd;
		this.banlance = banlance;
		}
	@Override
	public String toString() {
		return "Account [id=" + id + ", pwd=" + pwd + ", banlance=" + banlance + "]";
	}
	
}
  • AccountTest.java
package com.atshangguiguexer;

public class AccountTest {
public static void main(String[] args) {
	Account acct1 = new Account();
	Account acct2 = new Account("350340",500000.0);
	Account.setInterestRate(0.012);
	Account.setMinMoney(10);
	System.out.println(acct1);
	System.out.println(acct2);
}
}

10. Design mode and single case design mode

  • Design pattern It is the preferred code structure, programming style
    And how to think about solving problems . The design of mold eliminates our own thinking and exploration. It's like a classic
    Different chess scores, different chess games, we use different chess scores. " tricks ”----There are 23 modes in total
  • Different languages have different design patterns -- java uses more design patterns (not considered at the primary stage)
  • Later, you can buy a book to have a look --- boasting design mode     23 design modes     Head First Design Patterns
  • The so-called class singleton design pattern is to take certain methods to ensure that in the whole software system, the
    A class Only one object instance can exist And this class only provides a method to get its object instance.
    If we want a class to produce only one object in a virtual machine, we must first structure
    The access rights of the builder are set to private In this way, it can't be used new Operators are generated outside the class
    Class, but objects of this class can still be generated inside the class. Because there is nothing to start with outside the class
    Method to get the object of the class. You can only Call a static method of this class To return the object created inside the class,
    Static methods can only access static member variables in the class, so they point to the variables generated inside the class This kind of object
    Variables must also be defined as static . (content of PPT)

11. Implementation of hungry Han style of single instance

package com.atshangguiguexer;
/*
 * 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 for a class in the whole software system
 * 2.How?
 */
public class SingletonTest1 {
public static void main(String[] args) {
	Bank bank1 = Bank.getInstance();
	Bank bank2 = Bank.getInstance();
	//Here to determine whether it is a hungry man style
	System.out.println(bank1 == bank2);
}
}
//Hungry Han style
class Bank
{
	//Step 1. Privatize the constructor of the class: avoid constructing multiple objects outside
	private Bank()
	{
	}
	//Step 2. Create an internal class object
	//Step 4. The object must also be static
	private static Bank instance = new Bank();
	//Step 3. Provide a public method to return the object of the class
	public static Bank getInstance()
	{
		return instance;//Static methods can only call static objects
	}
}

12. Lazy implementation of singleton

package com.atshangguiguexer;
/*
 * Lazy implementation of singleton mode
 */
public class SingleTest2 {
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. The object declaring the current class is not initialized
	//4. This object must also be declared as static type
	private static Order instance = null;
	
	//3. Declare a method of public static's return class object
	public static Order getInstance()
	{
		if(instance == null) 
		{
		instance = new Order();//Create multiple current objects, not the only one before, so you need to make a judgment
		}
		return instance;
	}
}
  •   The lazy type is used when and when to create an object. However, the hungry type is to create an object first and then use it. This is the difference between the hungry type and the lazy type ---------- this is my own understanding
  • Note: during the interview, you should be careful not to reverse the two

13. Comparison between hungry and lazy

 * 3.Distinguish the difference between hungry and lazy.
 * 	(1)Hungry Han style:(Created in advance)              
 *  Disadvantages:Object took too long to load.
 *  benefit:Threads are safe---Threads need to pay attention to what needs to be learned later[The problem of bank withdrawal and ticket grabbing]
 * 	(2)Lazy style:(Non must not create the corresponding object) 
 *  benefit:Delay the creation of an object.--
 *  Disadvantages:Threads are unsafe---Is in null When blocked,It may cause two problems

14. Usage scenario of singleton mode

  • Advantages of singleton mode:
    Since the singleton mode generates only one instance, Reduced system performance overhead , when an object's
    When generating more resources, such as reading configuration and generating other dependent objects, you can
    To generate a singleton object directly when the application starts, and then permanently reside in memory
    To solve the problem. Example: java.lang.Runtime
  • Application scenario of singleton mode

15. Understand the syntax of the main() method

  • MainDemo.java
package com.atshangguiguexer;
public class MainDemo {
public static void main(String[] args) {
	for(int i = 0;i < args.length;i++)
	{
		System.out.println("The output is" + args[i]);	
	}
}
}

  •  MainTest.java
package com.atshangguiguexer;
/*
 * main()Instructions for use:
 * 1.main()Method appears as an entry to the program
 * 2.main()Method is also a static method, ordinary static method
 * 3.main()The formal parameters of can be used as a way to interact with the console (previously using Scanner)
 */
public class MainTest {
	//Because main() is static, why do we call it directly at first? The corresponding properties are useless, and then we must access them through objects
public static void main(String[] args) {//It is an entrance
	Main.main(new String[100]);
	
}
}
class Main
{
	
public static void main(String[] args) {
	
	for(int i = 0; i < 120; i++)
	{
		System.out.println(i);
	}	

	
}}
  • It should be noted here that the interaction with the system: the interaction process is related to the content mentioned in the first lesson -- first punch in the compiler -- copy the source code -- delete the beginning of the source code -- javac xxx.java -- Java XXX "X", "X" and "X"

16. Use of code block structure in class

package com.atshangguigu.java3;
/*
 * Class: code block (or initialization block)
 * 1.Function of code block: used to initialize class objects
 * 2.If the code block is decorated, you can only use static
 * 3.Classification: static code block pk non static code block
 * 4.Static code block
 * 		There can be output statements inside
 * 		Execute as the class is loaded - this is excessive (automatic) and only executed once
 * 		If multiple code blocks are defined in a class, they are executed in the order of declaration
 * 		Static code blocks are executed with non static code blocks (only related to objects)
 * 		Only static attributes and methods can be called in static code blocks, and non static attributes and methods cannot be called
 * 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 (once every time the object is created)
 * 		If multiple non static code blocks are defined in a class, they are executed in sequence
 * 		Non static code blocks can call static properties, static methods, or non static properties and methods
 * Where attributes can be assigned:
 * a.Default initialization
 * b.Explicit initialization
 * c.Initializes in the constructor
 * d.After you have an object, you can assign values through object. Attribute or object. Method
 * e.Assign values in code blocks	
 */
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 = 23;
	static String desc = "I am a rookie,A rookie who can't eat worms";
	//constructor 
	public Person()
	{}
	public Person(String name,int age)
	{
		this.name = name;
		this.age = age;	
	}
	
	//static code block: just a pair of braces
	static{
		System.out.println("I am a pig");
		desc = "I need to make money";//Static attributes in the class are assigned values
	}
	static{
		System.out.println("I'm a pig man");
		desc = "I need to make a lot of money";//Static attributes in the class are assigned values
		info();//Only static structures can be called
	}
	//Non static code block
	{
		System.out.println("I am a cat");
	}
	{
		System.out.println("I am a happy star cat");
		info();//Call static structure
		eat();//Call non static structure
	}
	//method
	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("There are no tasks these two days");
	}
}

17. Use examples of code blocks in development

  • Property cannot be called
  • I didn't understand this class

18. After class exercises of code blocks

19. Order of attribute assignment

package com.atshangguigu.java3;
/*
 * Where attributes can be assigned:
 * a.Default initialization
 * b.Explicit initialization
 * c.Initializes in the constructor
 * d.After you have an object, you can assign values through object. Attribute or object. Method
 * e.Assign values in code blocks	
 * 
 * Order of execution a b / E (see who wrote b and e later) c d 
 */
public class OrderTest {
public static void main(String[] args) {
	Order order = new Order();
    System.out.println(order.orderId);//The result is 4
}
}
class Order
{
	
	{
		orderId = 4;
	}
	int orderId = 3;
}

20. Method of final modifier class

21.final modifier attribute

22.final modifier local variable

package com.atshangguigu.java3;
/*
 * final:Final
 * 1.final Structure that can be modified: class method variable 
 * 
 * 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 Used to modify a method to indicate that the method cannot be rewritten - and then? Then he resigned
 * 					    For example: getClass() in Object class;
 * 4.final Used to modify a variable: the variable at this time is called a constant
 * 4.1  final Modified attribute: the positions where assignment can be considered are: (1) explicit initialization (2) assignment in code block and external initialization 
 *                                      (3)Initializes in the constructor  
 *      final cannot be called in the method. The object calling method is generally to modify the corresponding value
 * 4.2  final Modify local variables:
 * 		When final modifies a 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 the value is assigned
 * 		This parameter can only be used inside the method body, but it cannot be re assigned
 * static final :Used to modify attributes: global constants
 */
public class FinalTest {
	final int width = 10;
	final int WIDTH = 0;
	final int LEFT;
	final int ZUIYOU;
	{
		LEFT = 1;
	}
	public FinalTest()
	{
		ZUIYOU = 20;
	}
	public FinalTest(int n)
	{
		//this();
		ZUIYOU = n;
	}
	public void doWidth()
	{
		//width = 20;
	}
	public void show()
	{
		final int NUM = 0;//constant
	}
	public void show (final int num)
	{
		//num = 20; Compilation does not pass
		System.out.println(num);
	}
public static void main(String[] args) {
	int num = 10;
	num += 5;
	FinalTest test = new FinalTest();
	test.show(12);
}

}
final class  FinalA//The meaning here is that there can be no subclasses (that is, only seedlings, absolutely)
{
	
}
/*class B extends FinalA//The meaning here is that the above class cannot be inherited
{
	
}*/
class aa
{
	final public void show()
	{}
}
class BB extends aa
{/*
	public void show()
	{}
*/
}

23.final after class exercises

  • Title 1: the comment is right, return ++x; Is wrong;

  • Topic 2: you can think of o.i + + as your object. Finally, its age changes

24. Daily test

  • one   What are the special features of static modified attributes compared with instance variables (> = 3 points)

Load with class loading;

Earlier than the creation of the object;

As long as the permission allows, it can be called through the "object. static attribute"; static domain that exists in the method area

  • 2. What structures can final be used to modify and what do they mean

(Chen Zhou: not here) (Zhang Yining) see the previous code for more clarity

  • 3. The code implements the starving Han style of singleton mode (thread is safer)
  • 4. The code implements the lazy style of singleton mode   
  • 5. What are the locations of class attribute assignment? In what order?

Default initialization

Explicit initialization  , Initialization in code block

Initialization in constructor

Assignment by "object. Property" or "object. Method"

25. Use of abstract classes and methods

package day15;
/*
 * abstract Use of keywords
 * 1.abstract:Abstract
 * 2.abstract Structure that can be modified: class method
 * 3.abstract Decoration class: abstract class
 * 		This class cannot be instantiated
 * 		There is a constructor in the abstract class, which is convenient for calling when subclass objects are instantiated (the whole process of subclass object instantiation)
 * 		During development, subclasses of abstract classes will be provided, and subclasses will be instantiated to complete corresponding operations (barrage: all for son)
 * 4.abstract Modification method: abstract method
 * 		Abstract methods have only method names and no method bodies
 * 		A class containing abstract methods must be an abstract class. On the contrary, a class is an abstract class and does not necessarily have an abstract method
 * 		If the subclass overrides all abstract classes in the parent class, the subclass can be instantiated. If the subclass is not overridden, the subclass needs to be declared as abstract
 * 
 */
public class AbstractTest {
public static void main(String[] args) {
	//Person p1 = new Person();  // Can't make objects
}
}
abstract class Creature
{
	public abstract void breath();
}
abstract class Person extends Creature
{
    //attribute
	String name;
	int age;
	
	//constructor 
	public Person()
	{}
	public Person(String name,int age)
	{
	this.name = name;
	this.age = age;
	}
	
	//method
	public void eat()
	{
		System.out.println("I just ate three fried dumplings from the school five canteen in the morning,But I'm not full");
	}

	public void walk()
	{
		System.out.println("I haven't run recently");
	}
	//The abstract method is (error reporting: the solution is as follows)
	public abstract void abs();
}
class Student extends Person//Solution 2: inherit and declare it abstract
{
	public Student(String name,int age)
	{
		super();
	}
	public void abs()
	{
		System.out.println("Solution 1:rewrite");
	}
	
	public void breath() 
	{
		System.out.println("catch a cold,have difficulty in breathing");
	}
	
	}

26. Use of abstract application scenarios

  • This section explains the previous problem of calculating the area, that is, abstract is added to the area, that is, its subclasses need to be rewritten

27. Precautions in the use of abstract

  •  * Notes on the use of abstract:
     * 1.abstract cannot be used to modify: attribute   Constructors and other structures
     * 2.abstract cannot be used to modify private methods (because private methods cannot be overridden)   Static methods (static methods cannot be overridden)   final method
     

28. Basic exercise of abstraction: basic operation

  • The above thinking questions were mentioned in the above three classes  
  • Employee.java
package day15;
/*
 * 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().
 */
public abstract class Employee {
		private String name;
		private int id;
		private double salary;
		public Employee()
		{
			super();
		}
		public Employee(String name,int id,double salary)
		{
			this.name = name;
			this.id = id;
			this.salary = salary;
		}
		public abstract void work();
	
}
  • Manager.java
package day15;
/*
 * 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("Give money to employees");
	}
}
  • Commenemployee.java
package day15;

public class CommonEmployee extends Employee{

	@Override
	public void work() {
		System.out.println("Work hard,work");	
	}
}
  • EmployeeTest.java
package day15;
/*
 * 
 */
public class EmployeeTest {
public static void main(String[] args) {
	Employee manager = new Manager("Yang",0102, 12345, 153);//Use of polymorphism
	manager.work();
	CommonEmployee commonEmployee = new CommonEmployee();
	commonEmployee.work();
}
}

29. Create anonymous subclass operation of abstract class

  • 12
  • 12
  • 12

30. Design mode and application scenario of template method

package day15;
/*
 * Application of abstract classes: design patterns of template methods
 */
public class Template {
public static void main(String[] args) {
	TemplateTest t = new SubTemplate();
	t.spendTime();
}
}
abstract class TemplateTest
{	//It is used to calculate the time spent in the execution of a code
	public void spendTime()
	{
		long start = System.currentTimeMillis();
		code();
		long end = System.currentTimeMillis();
	    System.out.println("The time spent is" + (end-start));
	}
	public abstract void code();
}
class SubTemplate extends TemplateTest
{

	@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);
			}
		}
		
	}
	
}
  •   The following code directly copies the teacher's for operation
package day15;
//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!!");
	}
}

31. After class exercises of abstract classes

32. Understanding of interfaces

  •   The following picture illustrates the difference between interface and inheritance

33. Definition of interface

package com.atshangguigu.java;
/*
 * Use of interfaces
 * 1.Interfaces are defined using interface s
 * 2.Java In, interface and juxtaposition are two structures
 * 3.How to define an interface: define members in an interface
 * 		3.1 JDK7 Previously: only global constants and abstract methods could be defined
 * 				Global constant: public static final, but it can be omitted when writing
 * 				Abstract method: public abstract
 * 		3.2 JDK8 Later: in addition to defining global constants and abstract methods, you can also define static methods and default methods
 * 4.Constructors cannot be defined in interfaces! It means that the interface can not be instantiated. -- it is related to the class
 * 5.Java In the process of development, interfaces are implemented through classes, not inheritance
 * 	  If the implementation class covers (overrides) all the abstract 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
 * 
 * 
 * 
 */
public class InterfaceTest {
public static void main(String[] args) {
	System.out.println(Flyable.MAX_SPEED);
	System.out.println(Flyable.MIN_SPEED);
	//Flyable.MIN_APEED = 2.0;
	Plane plane = new Plane();
	plane.fly();
}
}
interface Flyable
{
	//Global constant
	public static final int MAX_SPEED = 7000;//First cosmic velocity
	int MIN_SPEED = 1;//Only public static final is omitted here
	
	//Abstract method
	public abstract void fly();
	void stop();//public abstract is omitted
	
	//constructor 
	/*public Flyable()
	{}*/
}
class Plane implements Flyable
{

	@Override
	public void fly() {
		System.out.println("Fly through the wing");
		
	}

	@Override
	public void stop() {
		System.out.println("By landing on the ground,Brake stop");
	}
	
}
abstract class kite implements Flyable
{

	@Override
	public void fly() {
		System.out.println("Fly, fly");	
	}
}

34. Multiple implementations of interfaces and interface inheritance

  • String and Integer are like this
package com.atshangguigu.java;
/*
 * Use of interfaces
 * 1.Interfaces are defined using interface s
 * 2.Java In, interface and juxtaposition are two structures
 * 3.How to define an interface: define members in an interface
 * 		3.1 JDK7 Previously: only global constants and abstract methods could be defined
 * 				Global constant: public static final, but it can be omitted when writing
 * 				Abstract method: public abstract
 * 		3.2 JDK8 Later: in addition to defining global constants and abstract methods, you can also define static methods and default methods
 * 4.Constructors cannot be defined in interfaces! It means that the interface can not be instantiated. -- it is related to the class
 * 5.Java In the process of development, interfaces are implemented through classes, not inheritance
 * 	  If the implementation class covers (overrides) all the abstract 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 -- >, which makes up for the limitation of Java single inheritance
 * 	    Format: Class A ends B implements C, D, e {}
 * 7. Interfaces can be inherited from one another, and they are multi inheritance
 * ***************************************************************************
 * 8. The specific use of the interface reflects the problem of polymorphism
 * 9. The essence of an interface is a specification and a rule
 * 
 * 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(Flyable.MAX_SPEED);
	System.out.println(Flyable.MIN_SPEED);
	//Flyable.MIN_APEED = 2.0;
	Plane plane = new Plane();
	plane.fly();
}
}
interface Flyable
{
	//Global constant
	public static final int MAX_SPEED = 7000;//First cosmic velocity
	int MIN_SPEED = 1;//Only public static final is omitted here
	
	//Abstract method
	public abstract void fly();
	void stop();//public abstract is omitted
	
	//constructor 
	/*public Flyable()
	{}*/
}
interface Attackable
{
	void attack();
}
class Plane implements Flyable
{

	@Override
	public void fly() {
		System.out.println("Fly through the wing");
		
	}

	@Override
	public void stop() {
		System.out.println("By landing on the ground,Brake stop");
	}
	
}
abstract class kite implements Flyable
{

	@Override
	public void fly() {
		System.out.println("Fly, fly");	
	}
}
class Bullet extends Object implements Flyable,Attackable
{

	@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
		
	}
	
}
/**********************************************/
//The following is a process of multi inheritance
interface AA
{
	void method();
}
interface BB
{
	void method1();	
}
interface CC extends AA,BB
{}

35. The example demonstration interface is a specification

  • Drive - Specification
  • Interface oriented programming
package day15;
/*
 * Use of interfaces
 * 1.The interface meets polymorphism
 * 2.An interface actually defines a specification
 */
public class UsbTest {
public static void main(String[] args) {
	Computer com = new Computer();
	Flash flash = new Flash();
	com.transferData(flash);//It reflects
}
}
interface USB
{
//Constant: defines the maximum and minimum transmission rates of length and width
	void start();
	void stop();
}
class Computer  //USB usb = new flash();
{
	public void transferData(USB usb)
	{
		usb.start();
		System.out.println("Specific transmission details");
		usb.stop();
	}
}
class Flash implements USB
{
	@Override
	public void start() {
		System.out.println("U Disc opening operation");
	}
	@Override
	public void stop() {
		System.out.println("U The disc is broken");
	}	
}
class Printer implements USB
{
	@Override
	public void start() {
		System.out.println("The printer starts working");
	}
	@Override
	public void stop() {
		System.out.println("The printer is out of ink");
	}
}

36. Create an object of interface anonymous implementation class

package day15;
/*
 * Use of interfaces
 * 1.The interface meets polymorphism
 * 2.An interface actually defines a specification
 * 3.Withdrawal of 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);//It reflects
	
	//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("Mobile phone off");
		}};
		com.transferData(phone);
		//4. Create an anonymous object of the anonymous implementation class of the interface
		com.transferData(new USB(){

			@Override
			public void start() {
				System.out.println("Play and start working");
			}

			@Override
			public void stop() {
			System.out.println("The game console is broken");
			}});
}
}
interface USB
{
//Constant: defines the maximum and minimum transmission rates of length and width
	void start();
	void stop();
}
class Computer  //USB usb = new flash();
{
	public void transferData(USB usb)
	{
		usb.start();
		System.out.println("Specific transmission details");
		usb.stop();
	}
}
class Flash implements USB
{
	@Override
	public void start() {
		System.out.println("U Disc opening operation");
	}
	@Override
	public void stop() {
		System.out.println("U The disc is broken");
	}	
}
class Printer implements USB
{
	@Override
	public void start() {
		System.out.println("The printer starts working");
	}
	@Override
	public void stop() {
		System.out.println("The printer is out of ink");
	}
}

37. Interface application: proxy mode

  • I'll call you uncle this time. I'll call you uncle next time. Don't understand the principle. After a long time, I'll call you uncle
  • Concept:
    The agent mode is Java A design pattern used more in development. Agent design is for its
    It provides a proxy to control access to this object.
  • Looking for a house: I am the agent; Intermediary is the agent class; Just like a star or an agent

 

package com.atshangguigu.java;
/*
 * Application of interface: proxy mode
 */
public class NetWorkTest {
public static void main(String[] args) {
	Server server = new Server();
	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 server access network");
	}
}
//proxy class
class ProxyServer implements NetWork
{	
	private NetWork work;
	public ProxyServer(NetWork work)
	{
		this.work = work;
	}
	public void check()
	{
		System.out.println("Check network status");
	}
	@Override
	public void browse() {
		check();
		work.browse();
	}
	}
  •   One proxy class for each interface
package com.atshangguigu.java;

public class StaticProxyTest {

	public static void main(String[] args) {
		Star 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");
	}
}

38. Interface application: factory mode

  •   Factory mode: it realizes the separation of creator and caller, that is, the specific process of creating objects is shielded and isolated, so as to improve flexibility.

1. No factory mode (copy)

package com.atguigu.pattern.factory.nofactory;
interface Car{
void run();
}
class Audi implements Car{
public void run() {
System.out.println("Audi is running");
}
}
class BYD implements Car{
public void run() {
System.out.println("BYD is running");
}
}
public class Client01 {
public static void main(String[] args) {
Car a = new Audi();
Car b = new BYD();
a.run();
b.run();
}
}

2. Simple factory mode     Disadvantages: for adding new products, it cannot be extended without modifying the code. Violation of the opening and closing principle (right)       Open for extension; closed for modification).

package com.atguigu.pattern.factory.simple;
interface Car {
void run();
}
class Audi implements Car {
public void run() {
System.out.println("Audi is running");
}
}
class BYD implements Car {
public void run() {
System.out.println("BYD is running");
}
}
//Factory class
class CarFactory {
//Mode 1
public static Car getCar(String type) {
if ("audi".equals(type)) {
return new Audi();
} else if ("BYD".equals(type)) {
return new BYD();
} else {
return null;
}
}
//Mode II
// public static Car getAudi() {
// return new Audi();
// }
//
// public static Car getByd() {
// return new BYD();
// }
}
public class Client02 {
public static void main(String[] args) {
Car a = CarFactory.getCar("audi");
a.run();
Car b = CarFactory.getCar("BYD");
b.run();
}
}

3. Factory method mode

package com.atguigu.pattern.factory.method;
interface Car{
void run();
}
//Two implementation classes
class Audi implements Car{
public void run() {
System.out.println("Audi is running");
}
}
class BYD implements Car{
public void run() {
System.out.println("BYD is running");
}
}
//Factory interface
interface Factory{
Car getCar();
}
//Two factory classes
class AudiFactory implements Factory{
public Audi getCar(){
return new Audi();
}
}
class BydFactory implements Factory{
public BYD getCar(){
return new BYD();
}
}
public class Client {
public static void main(String[] args) {
Car a = new AudiFactory().getCar();
Car b = new BydFactory().getCar();
a.run();
b.run();
}
}

4. Abstract Factory Pattern: the difference between abstract factory pattern and factory method pattern lies in the complexity of creating objects.

39. Two written questions after interface class

  •   Systemout.println(x) in the above question; It is ambiguous because there is x in both the parent class and the interface     The interface is regarded as the same line. If you want to call X in the parent class, the code should be changed to                 Sysout.out.println(super.x); If you want to call in the interface, you should change to     Sysout.out.println(A.x);

  •   Public static final ball = new ball ('pingpang ') in the above interfaces; omitted

40. Interface exercise: comparing object sizes

 

41. New features of Java 8 interface

  • CompareA.java
package com.atshangguigu.exer1;
/*
 * jdk8 In addition to defining global constants and abstract methods, static methods and default methods can also be defined
 */
public interface CompareA {
	//Static method --- called directly through the interface
	public static void method1()
	{
		System.out.println("Compare:Xi'an");
	}
	//Default method --- through implementation class
	public default void method2()
	{
		System.out.println("Compare:Tianjin");
	}
	default void method3()
	{
		System.out.println("Compare:Cangzhou");
	}
}
  • CompareB.java
package com.atshangguigu.exer1;

public interface CompareB {
	default void method3()
	{
		System.out.println("CompareB:Tianda");
	}
}
  • SuperClassTest1.java
package com.atshangguigu.exer1;

public class SuperClassTest1 {
	public void method3()
	{
		System.out.println("SuperCompare:Hebei");
	}
}
  • SuperClass.java
package com.atshangguigu.exer1;

public class SubClass {
public static void main(String[] args) {
	SubClassTest s = new SubClassTest();
	//s.method1(); / / completely ignore the static methods in the interface
	//Knowledge point 1: static methods in the interface can only be called through the interface
	CompareA.method1();
	//Knowledge point 2: you can call the default method in the interface through the object of the class, or override it. You can't use class call
	//If the implementation class overrides the default method in the interface, the overridden method will still be called when calling
	s.method2();
	//Knowledge point 3: if a method with the same name and parameter is declared in the parent class inherited by the subclass (or implementation class) and the implemented interface,
	//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
	//The above is only for classes, not for attributes
	s.method3();
	//Knowledge point 4: if the implementation class implements multiple interfaces, the default method with the same name and parameter is defined
	//If the implementation class does not override this method, an error will be reported. -- this is a phenomenon of interface conflict
	//This requires us to override this method in the class
}
}
class SubClassTest extends SuperClassTest1 implements CompareA,CompareB
{
	public void method2()
	{
		System.out.println("SubCompare:Hebei Province");
	}
	
	public void method3()
	{
		System.out.println("SubCompare:Hebei Province");
	}
	
	
	//Knowledge point 5: how to invoke a method that is rewritten in the parent class interface by subclass or implementing the class method.
	public void myMethod()
	{
		method3();//Call your own
		super.method3();//Call in the parent class
		CompareA.super.method3();
		CompareB.super.method3();
	}
}

42. Application of new features of Java 8 interface

  • This is a process to supplement the above. The video is very interesting. There is no rewriting code here

43. Classification of internal classes

  • The relationship between human and brain, brain is an internal class, human is an external class
package com.atshangguigu.java2;
/*
 * Inner member of class 5: inner class
 * 1.Java Class A is allowed to be declared in another class B, so class A is the inner class and class B is the outer class
 * 2.Classification of internal classes: member internal classes (static and non static) pk local internal classes (within methods, code blocks, constructors)
 * 
 */
public class InnerClass {

}
class Person
{
	//Non static member inner class
	class Dog
	{
		
	}
	//Static member inner class
	static class Cat
	{
		
	}
	
	
	public void method()
	{
		//Local inner class
		class A
		{
			
		}
	}
		{
			class B
			{}
		}
		public Person()
		{
			class C
			{}
		}	
		
}

44. Characteristics of internal classes of members

package com.atshangguigu.java2;
/*
 * Inner member of class 5: inner class
 * 1.Java Class A is allowed to be declared in another class B, so class A is the inner class and class B is the outer class
 * 2.Classification of internal classes: member internal classes (static and non static) pk local internal classes (within methods, code blocks, constructors)
 * 3.Member inner class:
 * 		On the one hand: as a member of an external class:
 * 			(1)You can call a structure of an external class
 * 			(2)Can be modified by abstract
 * 			(3)Can be modified by four permissions
 * 		On the other hand: as a class:
 * 			(1)Properties, methods, constructors, etc. can be defined in the class
 * 			(2)Final modification can be used to indicate that this class cannot be inherited. The implication is whether final can be inherited
 * 			(3)It can be modified by abstract and cannot be instantiated
 */
public class InnerClass {

}
class Person
{
	String name;
	int age;
	public void eat()
	{
		System.out.println("People can eat just right");
	}
	//Non static member inner class
	class Dog
	{
		String name;
		public void shot()
		{
			System.out.println("Ma Xiaodong is my son");
			Person.this.eat();//Calling properties of an external class
			
		}
	
		public Dog()
		{
			
		}
	}
	//Static member inner class
	static class Cat
	{
		String name;
		int age;
		public void show()
		{
			System.out.println("Meow meow");
		}
		public Cat()
		{}
		//eat();
	}
	
	
	public void method()
	{
		//Local inner class
		class A
		{
			
		}
	}
		{
			class B
			{}
		}
		public Person()
		{
			class C
			{}
		}	
		
}

45. How to instantiate member inner classes

package com.atshangguigu.java2;
/*
 * Inner member of class 5: inner class
 * 1.Java Class A is allowed to be declared in another class B, so class A is the inner class and class B is the outer class
 * 2.Classification of internal classes: member internal classes (static and non static) pk local internal classes (within methods, code blocks, constructors)
 * 3.Member inner class:
 * 		On the one hand: as a member of an external class:
 * 			(1)You can call a structure of an external class
 * 			(2)Can be modified by abstract
 * 			(3)Can be modified by four permissions
 * 		On the other hand: as a class:
 * 			(1)Properties, methods, constructors, etc. can be defined in the class
 * 			(2)Final modification can be used to indicate that this class cannot be inherited. The implication is whether final can be inherited
 * 			(3)It can be modified by abstract and cannot be instantiated
 * 4.Focus on the following three issues
 * 		4.1 How to instantiate an object of a member's inner class
 * 		4.2 How to distinguish the structure of calling external classes among member internal classes
 * 		4.3 Use of local internal classes in development
 */
public class InnerClass {
public static void main(String[] args) {
	//Create a Dog instance (static member inner class)
	Person.Cat cat = new Person.Cat();
	cat.show();
	//Create Cat instance (non static member inner class)
	Person p = new Person();
	Person.Dog dog = p.new Dog();
	dog.shot();
	
	
}
}
class Person
{
	String name;
	int age;
	public void eat()
	{
		System.out.println("People can eat just right");
	}
	//Non static member inner class
	class Dog
	{
		String name;
		public void shot()
		{
			System.out.println("Ma Xiaodong is my son");
			Person.this.eat();//Calling properties of an external class
			
		}
	
		public Dog()
		{
			
		}
	}
	//Static member inner class
	static class Cat
	{
		String name;
		int age;
		public void show()
		{
			System.out.println("Meow meow");
		}
		public Cat()
		{}
		//eat();
	}
	
	
	public void method()
	{
		//Local inner class
		class A
		{
			
		}
	}
		{
			class B
			{}
		}
		public Person()
		{
			class C
			{}
		}	
		
}

46. the structure of the external class is called in the member's inner class.

package com.atshangguigu.java2;
/*
 * Inner member of class 5: inner class
 * 1.Java Class A is allowed to be declared in another class B, so class A is the inner class and class B is the outer class
 * 2.Classification of internal classes: member internal classes (static and non static) pk local internal classes (within methods, code blocks, constructors)
 * 3.Member inner class:
 * 		On the one hand: as a member of an external class:
 * 			(1)You can call a structure of an external class
 * 			(2)Can be modified by abstract
 * 			(3)Can be modified by four permissions
 * 		On the other hand: as a class:
 * 			(1)Properties, methods, constructors, etc. can be defined in the class
 * 			(2)Final modification can be used to indicate that this class cannot be inherited. The implication is whether final can be inherited
 * 			(3)It can be modified by abstract and cannot be instantiated
 * 4.Focus on the following three issues
 * 		4.1 How to instantiate an object of a member's inner class
 * 		4.2 How to distinguish the structure of calling external classes among member internal classes
 * 		4.3 Use of local internal classes in development
 */
public class InnerClass {
public static void main(String[] args) {
	//Create a Dog instance (static member inner class)
	Person.Cat cat = new Person.Cat();
	cat.show();
	//Create Cat instance (non static member inner class)
	Person p = new Person();
	Person.Dog dog = p.new Dog();
	dog.shot();
	
	System.out.println("***********************************");
	dog.display("Small building");
	
	
}
}
class Person
{
	String name = "ODA";
	int age;
	public void eat()
	{
		System.out.println("People can eat just right");
	}
	//Non static member inner class
	class Dog
	{
		String name = "chinese rhubarb";
		public void shot()
		{
			System.out.println("see,Small building");
			Person.this.eat();//Calling properties of an external class
			System.out.println(age);//This is the case without duplicate names
			
		}
		public void display(String name)
		{
			System.out.println(name);//In method parameters
			System.out.println(this.name);//Properties of inner classes
			System.out.println(Person.this.name);//Properties of external classes
		}
		public Dog()
		{
			
		}
	}
	//Static member inner class
	static class Cat
	{
		String name;
		int age;
		public void show()
		{
			System.out.println("Meow meow");
		}
		public Cat()
		{}
		//eat();
	}
	
	
	public void method()
	{
		//Local inner class
		class A
		{
			
		}
	}
		{
			class B
			{}
		}
		public Person()
		{
			class C
			{}
		}	
		
}

47. Use of local internal classes

package com.atshangguigu.java2;
/*
 * Use of local internal classes under development
 */
public class InnerClassTest1 {

	//It is rare in the development process
	public void method()
	{
		//Local inner class
		class AA
		{}
	}
	//Method returns an object that implements the Comparable interface class
	public Comparable getComparable()
	{
		//Create a class that implements the Comparable interface: the local inner class
		//Mode 1:
		/*
		class MyComparable implements Comparable
		{

			@Override
			public int compareTo(Object o) {
				
				return 0;
			}
		}
		return new Comparable();
		*/
		//Mode 2:
		return new Comparable()
		{

					@Override
					public int compareTo(Object o) {
						// TODO Auto-generated method stub
						return 0;
					}
		}
	}
	
}

48. Daily test

  • What structures can abstract modify? After modification, what are the characteristics?

         A: modification classes and methods; Class cannot be instantiated, and subclasses (overrides) are provided; The class of the method modified by abstract must be an abstract class. The abstract method only defines the standard of a function. The specific implementation needs to be implemented by subclasses

  • Can an interface inherit an interface? Can abstract classes implement interfaces? Can abstract classes inherit non abstract classes? (yes)

Topics: Java