This is the 16th day of my participation in the August Text Challenge.More challenges in August
1. Keywords: static
1.1. Use of static
When we write a class, we are actually describing the properties and behavior of its object, and do not generate the actual object, only through the new keyword will generate the object, then the system will allocate memory space for the object, its method can be called externally.
We sometimes want to have only one copy of a particular piece of data in memory regardless of whether or not objects are generated, or regardless of how many objects are generated.
For example, all Chinese people have a country name, and each Chinese person shares the country name. There is no need to assign a variable representing the country name to each Chinese instance object.
/* * static use of the keyword * * 1. * 2. Static can be used to modify properties, methods, code blocks, inner classes. * * 3. Use static to modify properties: static variables (or class variables). * Instance variables: We create multiple objects of the class, and each object has a separate set of non-static properties of the class. * Modifying one of the non-static attributes does not result in the modification of the same attribute value in other objects. * Static variables: We create multiple objects of the class that share the same static variable. When a variable is modified using a static variable, * causes other objects to call the static variable, which is modified. Static variables are loaded as the class loads. It can be called as class.static variable. * ② Static variables are loaded before objects are created. * ③ Since the class is only loaded once, the static variable will only exist in memory once. There are static fields for method areas. * * ④ Class variable instance variable * Class yes no * Object yes yes * * 3.3 Static properties Example: System.out.math.pi; * * /
public class StaticTest {
public static void main(String[] args) {
Chinese.nation = "China";
Chinese c1 = new Chinese();
c1.name = "Yao";
c1.age = 40;
c1.nation = "CHN";
Chinese c2 = new Chinese();
c2.name = "Malone";
c2.age = 30;
c2.nation = "CHINA";
System.out.println(c1.nation);
// Failed to compile
// Chinese. Name = "zhang ";}}/ / the Chinese
class Chinese{
String name;
int age;
static String nation;
}
Copy the code
1.2. Class variable vs instance variable memory parsing
1.3, static modify method
/* * static (); /* * static (); Static method "method call * ② static method non-static method * class yes no * object yes yes * ③ Static method can only call static method or attribute * * non-static method can call all methods or attribute * * 5. * 5.2 The use of static attributes and static methods, we understand from the perspective of the life cycle. * * 6. In development, how do I determine if a property needs to be declared static? * "attributes can be shared by multiple objects and do not vary from object to object. * * Class constants are often declared static * * In development, how to determine whether a method should be declared static? * "methods that operate on static properties, usually set to static *" methods in the utility class, conventionally declared static. Examples: Math, Arrays, Collections * */
public class StaticTest {
public static void main(String[] args) {
Chinese.nation = "China";
Chinese c1 = new Chinese();
// Failed to compile
// Chinese. Name = "zhang ";
c1.eat();
Chinese.show();
// Failed to compile
// chinese.eat();
// Chinese.info();}}/ / the Chinese
class Chinese{
String name;
int age;
static String nation;
public void eat(a){
System.out.println("Chinese people eat Chinese food");
// Call a non-static structure
this.info();
System.out.println("name : " + name);
// Call the static structure
walk();
System.out.println("nation : " + Chinese.nation);
}
public static void show(a){
System.out.println("I am a Chinese!");
// eat();
// name = "Tom";
// Static structures can be called
System.out.println(Chinese.nation);
walk();
}
public void info(a){
System.out.println("name : " + name + ",age : " + age);
}
public static void walk(a){}}Copy the code
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;
}
// find the sum of the array
public static int getSum(int[] arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
// Average the 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 the 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 the 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 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;
// Error:
// swap(arr[j],arr[j+1]);
swap(arr,j ,j+1); }}}}// Error: Swap the values of two elements in the array at specified positions
// 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;
}
// go through the number group
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]) {
returni; }}return -1; }}Copy the code
The 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("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 :"); // system.out.println (" find :");
// int index = util.getIndex(arr, 5);
// if(index > 0){
// system.out. println(" find, index :" + index);
// }else{
// system.out.println (" not found ");
/ /}}}Copy the code
1.5. Static Example
// Application of the 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 ID." + c1.getId());
System.out.println("C2 ID." + c2.getId());
System.out.println("C3 ID." + c3.getId());
System.out.println("Number of circles created:"+ Circle.getTotal()); }}class Circle{
private double radius;
private int id; // Automatic assignment is required
public Circle(a){
id = init++;
total++;
}
public Circle(double radius){
this(a);/ / 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(a){
return 3.14 * radius * radius;
}
public double getRadius(a) {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public int getId(a) {
return id;
}
public static int getTotal(a) {
returntotal; }}Copy the code
1.6. Static exercises
/* * Write a class that implements the concept of a bank account with attributes such as "account", "password", "deposit balance", "interest rate", and "minimum balance", and define the methods that encapsulate these attributes. * The account is automatically generated. Write the main class, using the bank account class, input and output the above information of the three depositors. * Consider: which properties can be designed to be static. * * /
public class Account {
private int id; / / account
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 ids
public Account(a){ // The account is automatically generated
id = init++;
}
public Account(String pwd,double balance){
id = init++;
this.pwd = pwd;
this.balance = balance;
}
public String getPwd(a) {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public static double getInterestRate(a) {
return interestRate;
}
public static void setInterestRate(double interestRate) {
Account.interestRate = interestRate;
}
public static double getMinMoney(a) {
return minMoney;
}
public static void setMinMoney(double minMoney) {
Account.minMoney = minMoney;
}
public int getId(a) {
return id;
}
public double getBalance(a) {
return balance;
}
@Override
public String toString(a) {
return "Account [id=" + id + ", pwd=" + pwd + ", balance=" + balance + "]"; }}Copy the code
The 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()); }}Copy the code
1.7. Singleton design pattern
Design pattern is the preferred code structure, programming style, and way of thinking to solve problems after summarizing and theorizing in a large number of practices. Design models save us from thinking and fumbling. It’s like a classic board game. We use different boards for different games.” Routine”
The so-called class singleton design pattern is to take a certain method to ensure that in the whole software system, there can only be one object instance for a certain class. And the class only provides a method to get an instance of its object. If we want a class to produce only one object in a virtual machine, we must first set access to the constructor of the class to private, so that we cannot use the new operator to produce objects of the class outside the class, but can still produce objects of the class inside the class. Since you can’t get an object of the class from outside the class, you can only call a static method of the class to return an object created inside the class. Static methods can only access static member variables of the class. Therefore, variables that point to objects of the class generated inside the class must also be defined as static.
1, singleton mode hungry
/* * Singleton design pattern: * * 1. The singleton design pattern of classes takes certain methods to ensure that only one object instance of a class can exist in the entire software system * * 2. How to do that? 3. Distinguish between hungry and lazy. * Hungry: Bad: Objects take too long to load. * Benefits: Hungry is thread-safe. * * Lazy: Benefit: Delays object creation. Disadvantages: The current way of writing, will not be thread safe. -- "to multithreaded content, then modify */
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 example hungry
class Bank{
//1. Privatize class constructor
private Bank(a){}//2. Internal creation class object
//4. This object must also be declared static
private static Bank instance = new Bank();
//3. Provide public static methods that return class objects.
public static Bank getInstance(a){
returninstance; }}Copy the code
2. Slacker singleton patterns
/* * lazy implementation of singletons * */
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. Privatize class constructor
private Order(a){}//2. Declare the current class object, not initialized.
// This object must also be declared static
private static Order instance = null;
//3. Declare a public, static method that returns the current class object
public static Order getInstance(a){
if(instance == null){
instance = new Order();
}
returninstance; }}Copy the code
3. Advantages of singleton pattern
Since the singleton pattern generates only one instance,Reduces system performance overheadWhen the generation of an object requires a lot of resources, such as reading configuration and generating other dependent objects, it can be solved by directly generating a singleton object when the application is started and then permanently residing in memory.
4. Singleton design pattern – Application Scenario
- The counters of the website are generally implemented in singleton mode, otherwise it is difficult to synchronize.
- Application logging is generally implemented in singleton mode, usually because the shared log file is always open, because only one instance can operate, otherwise the content cannot be appended.
- Database connection pooling is also typically designed in a singleton pattern because a database connection is a database resource.
- In a project, the class that reads the configuration file generally has only one object. It is not necessary to generate an object to read every time configuration file data is used.
- Application is also a typical Application of singletons
- The Windows Task Manager is a typical singleton
- Windows’ **Recycle Bin ** is also a typical singleton application. The recycle bin maintains only one instance throughout the entire system operation.
2. Understand the syntax of the main method.
Since the Java virtual machine calls the main() method of the class, the method’s access must be public, and since the Java virtual machine does not have to create objects when executing the main() method, the method must be static. This method takes an array of arguments of type String that hold the arguments passed to the class being run when the Java command is executed.
Since the main() method is static, we cannot access the non-static members of the class directly. We must create an instance object of the class to access the non-static members of the class, as we have seen several times in previous examples.
* 1. The main() method is used as the entrance of the program; The * 2.main() method is also a normal static method * 3.main() method can also be used as the way we interact with the console. (Previously, use Scanner) * * */
public class MainTest {
public static void main(String[] args) { / / the entry
Main.main(new String[100]);
MainTest test = new MainTest();
test.show();
}
public void show(a){}}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]); }}}Copy the code
Example of command line parameters
public class MainDemo {
public static void main(String[] args) {
for(int i = 0; i < args.length; i++){ System.out.println("/ * / * / * /"+ args[i]); }}}Copy the code
//运行程序 MainDemo.java
Javac MainDemo. Java Java MainDemo "Tom" "Jerry" "Shkstart"Copy the code
Class member 4: code block
/* * class member 4: code block (or initializer block) * * 1. Code blocks, if decorated, must be static * 3. Classification: static code blocks vs. non-static code blocks * * 4. If a class defines multiple static code blocks, execute the static code blocks in the order in which they are declared. Precedence over execution of non-static code blocks * * static code blocks can only call static properties, static methods, not non-static structures * * 5. Non-static code blocks * > can have internal output statements * > execute as an object is created * > Execute a non-static code block once each object is created. * > Function: You can initialize the properties of an object when creating it. * > If more than one non-static code block is defined in a class, the order in which it is declared is executed. * > Non-static code blocks can call static properties and methods, or non-static properties and methods. * * Where attributes can be assigned: * ① default initialization * ② explicit initialization * ③ constructor initialization * ④ Once you have an object, you can pass "object". Property "or" object. Method "to perform the assignment. * ⑤ Assign the value */ in the 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 = newPerson(); System.out.println(p1.age); Person.info(); }}class Person{
/ / property
String name;
int age;
static String desc = "I am a young man";
/ / the constructor
public Person(a){}// Static code block
static{
System.out.println("hello,static block-1");
// Call the static structure
desc = "I'm a person who loves novels.";
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 a non-static structure
age = 1;
eat();
// Call the static structure
desc = "I am a person who loves novels.";
info();
}
/ / method
public Person(String name,int age){
this.name = name;
this.age = age;
}
public void eat(a){
System.out.println("Eat");
}
@Override
public String toString(a) {
return "Person [name=" + name + ", age=" + age + "]";
}
public static void info(a){
System.out.println("I am a happy man."); }}Copy the code
Static initialization block Example 1
// Summary: from parent to child class, static first
class Root{
static{
System.out.println("Static initialization block for Root");
}
{
System.out.println("Common initialization block for Root");
}
public Root(a){
System.out.println("No-argument constructor for Root"); }}class Mid extends Root{
static{
System.out.println("Static initializer block for Mid");
}
{
System.out.println("Common initialization block for Mid");
}
public Mid(a){
System.out.println("Parameterless constructor for Mid");
}
public Mid(String msg){
Call an overloaded constructor in the same class through this
this(a); System.out.println("Mid with parameter constructor, whose parameter value:"+ msg); }}class Leaf extends Mid{
static{
System.out.println("Static initializer block for Leaf.");
}
{
System.out.println("Common initializer block for Leaf.");
}
public Leaf(a){
// Call the constructor with a string argument in its parent class through super
super(Silicon Valley);
System.out.println("The Leaf constructor."); }}public class LeafTest{
public static void main(String[] args){
new Leaf();
//new Leaf();}}Copy the code
Static initialization block Example 2
class Father {
static {
System.out.println("11111111111");
}
{
System.out.println("22222222222");
}
public Father(a) {
System.out.println("33333333333"); }}public class Son extends Father {
static {
System.out.println("44444444444");
}
{
System.out.println("55555555555");
}
public Son(a) {
System.out.println("66666666666");
}
public static void main(String[] args) { // The parent and child are static first
System.out.println("77777777777");
System.out.println("* * * * * * * * * * * * * * * * * * * * * * * *");
new Son();
System.out.println("* * * * * * * * * * * * * * * * * * * * * * * *");
new Son();
System.out.println("* * * * * * * * * * * * * * * * * * * * * * * *");
newFather(); }}Copy the code
Summary: the execution order of member variable assignments in a program
/* * Where attributes can be assigned: * ① default initialization * ② explicit initialization / ⑤ Assignment in code block * ③ initialization in constructor * ④ Once you have an object, you can pass "object". Property "or" object. Method "to perform the assignment. * * Execution sequence :① - ② / ⑤ - ③ - ④ */
public class OrderTest {
public static void main(String[] args) {
Order order = newOrder(); System.out.println(order.orderId); }}class Order{
int orderId = 3;
{
orderId = 4; }}Copy the code
4. Keywords: final
/* * final: final * * 1. Final can be used to modify structures: classes, methods, variables * * 2. Final is used to modify a class: this class cannot be inherited by other classes. 3. Final Decorates a method: methods marked with the final flag cannot be overridden by subclasses. * For example, getClass() in Object. * 4. Final is used to modify variables: the "variable "(member or local) is a constant. The name is uppercase and can only be assigned once. * 4.1 Final modifier properties, where assignment can be considered: explicitly initialized, initialized ina code block, initialized ina constructor * 4.2 Final modifier local variables: * Especially when final modifier is used to indicate that the parameter is a constant. When we call this method, we assign an argument to the constant parameter. * Once assigned, the parameter can only be used inside the method body, but cannot be reassigned. * * static final is used to modify the global constant */
public class FinalTest {
final int WIDTH = 0;
final int LEFT;
final int RIGHT;
// final int DOWN;
{
LEFT = 1;
}
public FinalTest(a){
RIGHT = 2;
}
public FinalTest(int n){
RIGHT = n;
}
// public void setDown(int down){
// this.DOWN = down;
// }
public void dowidth(a){
// width = 20; //width cannot be resolved to a variable
}
public void show(a){
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.
//
/ /}
//class C extends String{
//
/ /}
class AA{
public final void show(a){}}//class BB extends AA{// Error, cannot be overridden.
// public void show(){
//
// }
/ /}
Copy the code
1
public class Something {
public int addOne(final int x) {
return ++x; // return x + 1;}}Copy the code
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;
}
Copy the code
5. Abstract classes and methods
Classes become more concrete as new subclasses are defined in the inheritance hierarchy, while superclasses become more general and generic. Classes should be designed so that the parent and child classes can share characteristics. Sometimes a parent class is designed so abstract that it has no concrete instance. Such a class is called an abstract class.
Abstract class: this class cannot be instantiated. Abstract classes must have constructors. Easy to call when subclass instantiation (involving: subclass object instantiation process) * "development, will provide abstract class subclass, let subclass object instantiation, implementation of related operations * * 4. * > A class that contains abstract methods must be an abstract class. If the abstract class overrides all the abstract methods in its parent class, the abstract class, * * abstract, cannot be used to modify variables, code blocks, or constructors. Abstract cannot be used to modify private methods, static methods, final methods, or 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(a);
}
abstract class Person extends Creature{
String name;
int age;
public Person(a){}public Person(String name,int age){
this.name = name;
this.age = age;
}
// Not an abstract method
// public void eat(){
// system.out.println (); // system.out.println ();
// }
// Abstract methods
public abstract void eat(a);
public void walk(a){
System.out.println("Man walks."); }}class Student extends Person{
public Student(String name,int age){
super(name,age);
}
public void eat(a){
System.out.println("Students should eat more nutritious food.");
}
@Override
public void breath(a) {
System.out.println("Students should breathe fresh, smog-free air."); }}Copy the code
5.1 Application of Abstract Classes
Abstract classes are classes that model objects whose parent class cannot determine the full implementation, but whose subclasses provide the concrete implementation.
Problem: Fuel efficiency and distance traveled are calculated completely differently for trucks and RiverBarge. The Vehicle class does not provide calculation methods, but subclasses do.
/* Java allows class designers to specify that a superclass declares a method but does not provide an implementation, which is provided by subclasses. Such methods are called abstract methods. Classes that have one or more abstract methods are called abstract classes. * Vehicle is an abstract class with two abstract methods. * Note: It is illegal for abstract classes not to instantiate new Vihicle() */
public abstract class Vehicle{
public abstract double calcFuelEfficiency(a);// An abstract method for calculating fuel efficiency
public abstract double calcTripDistance(a);// An abstract method for calculating distance traveled
}
public class Truck extends Vehicle{
public double calcFuelEfficiency(a){
// Write a specific method for calculating the fuel efficiency of a truck
}
public double calcTripDistance(a){
// Write a specific method to calculate the distance the truck travels}}public class RiverBarge extends Vehicle{
public double calcFuelEfficiency(a) {
// Write a specific method for calculating barge fuel efficiency
}
public double calcTripDistance( ) {
// Write a specific method for calculating barge distance}}Copy the code
5.2, practice
/* * Write an Employee class and declare it as an abstract class with three attributes: name, ID, salary. * Provide the necessary constructors and abstract methods: work(). * For the Manager class, it is both an employee and has the bonus attribute. Design the CommonEmployee and Manager classes with inheritance in mind and require that the necessary methods be provided for property access. * * /
public abstract class Employee {
private String name;
private int id;
private double salary;
public Employee(a){
super(a); }public Employee(String name, int id, double salary) {
super(a);this.name = name;
this.id = id;
this.salary = salary;
}
public abstract void work(a);
}
Copy the code
Manager class
/* * For the Manager class, it is both an employee and has the bonus attribute. * * /
public class Manager extends Employee{
private double bonus; / / bonus
public Manager(double bonus) {
super(a);this.bonus = bonus;
}
public Manager(String name, int id, double salary, double bonus) {
super(name, id, salary);
this.bonus = bonus;
}
@Override
public void work(a) {
System.out.println("Manage employees and improve the efficiency of the company."); }}Copy the code
CommonEmployee class
public class CommonEmployee extends Employee {
@Override
public void work(a) {
System.out.println("Employees produce products in the front-line workshop."); }}Copy the code
The test class
/* * Use inheritance to design the CommonEmployee and Manager classes, */
public class EmployeeTest {
public static void main(String[] args) {
Employee manager = new Manager("Cook".1001.5000.50000);
manager.work();
CommonEmployee commonEmployee = newCommonEmployee(); commonEmployee.work(); }}Copy the code
Create an anonymous subclass of an abstract class
public class Num {}abstract class Creature{
public abstract void breath(a);
}
abstract class Person extends Creature{
String name;
int age;
public Person(a){}public Person(String name,int age){
this.name = name;
this.age = age;
}
// Not an abstract method
// public void eat(){
// system.out.println (); // system.out.println ();
// }
// Abstract methods
public abstract void eat(a);
public void walk(a){
System.out.println("Man walks."); }}class Student extends Person{
public Student(String name,int age){
super(name,age);
}
public Student(a){}public void eat(a){
System.out.println("Students should eat more nutritious food.");
}
@Override
public void breath(a) {
System.out.println("Students should breathe fresh, smog-free air."); }}Copy the code
PersonTest class
/* * Anonymous subclass of the abstract class * */
public class PersonTest {
public static void main(String[] args) {
method(new Student()); // Anonymous objects
Worker worker = new Worker();
method1(worker); // Non-anonymous classes non-anonymous objects
method1(new Worker()); // Non-anonymous class anonymous objects
System.out.println("* * * * * * * * * * * * * * * * * * * * *");
// create an anonymous subclass of object :p
Person p = new Person(){
@Override
public void eat(a) {
System.out.println("吃东西");
}
@Override
public void breath(a) {
System.out.println("Breathe the air"); }}; method1(p); System.out.println("* * * * * * * * * * * * * * * * * * * * * *");
// Create an anonymous object for an anonymous subclass
method1(new Person(){
@Override
public void eat(a) {
System.out.println("Snacking");
}
@Override
public void breath(a) {
System.out.println("The 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(a) {}@Override
public void breath(a) {}}Copy the code
5.4. Application of polymorphism: TemplateMethod design pattern
Abstract class is a kind of template pattern design, abstract class as the general template of multiple subclasses, subclasses on the basis of the abstract class for extension, transformation, but the overall subclass will retain the behavior of the abstract class.
Problems solved:
While part of the implementation within a function is deterministic, part of the implementation is uncertain. At this point, you can expose the uncertain parts and let subclasses implement them. In other words, when an algorithm is implemented in software development, the overall steps are fixed and generic, and the steps are already written in the parent class. But some parts are mutable, and mutable parts can be abstracted out for different subclasses. This is a template pattern.
1, 1 case
/* * Application of abstract classes: design patterns for template methods */
public class TemplateTest {
public static void main(String[] args) {
SubTemlate t = newSubTemlate(); t.sendTime(); }}abstract class Template{
// Count the time it takes a piece of code to execute
public void sendTime(a){
long start = System.currentTimeMillis();
code(); // Uncertain part, changeable part
long end = System.currentTimeMillis();
System.out.println("The time spent is :" + (end - start));
}
public abstract void code(a);
}
class SubTemlate extends Template{
@Override
public void code(a) {
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); }}}}Copy the code
2. Case 2
// Application of abstract classes: design patterns for template methods
public class TemplateMethodTest {
public static void main(String[] args) {
BankTemplateMethod btm = new DrawMoney();
btm.process();
BankTemplateMethod btm2 = newManageMoney(); btm2.process(); }}abstract class BankTemplateMethod {
// Specific methods
public void takeNumber(a) {
System.out.println("Get your number in line");
}
public abstract void transact(a); // Handle specific business // hook method
public void evaluate(a) {
System.out.println("Feedback scoring");
}
// template methods that group basic operations together. Subclasses generally cannot be overridden
public final void process(a) {
this.takeNumber();
this.transact();// The implementation code of the subclass is executed according to the subclass
this.evaluate(); }}class DrawMoney extends BankTemplateMethod {
public void transact(a) {
System.out.println("I want a withdrawal!!"); }}class ManageMoney extends BankTemplateMethod {
public void transact(a) {
System.out.println("I want money! I have $20 million here!!"); }}Copy the code
The template method design pattern is a commonly used pattern in programming. Each framework, class library has his shadow, such as the common:
- Encapsulation of database access
- Junit unit tests
- JavaWeb Servlet about doGet/doPost method calls
- Hibernate template program
- Spring JDBCTemlate, HibernateTemplate, etc
5.5. Practice abstract classes
1, the Employee class
/* * Define an Employee class that contains the following private member variables: name,number,birthday, where birthday is an object of class MyDate; (1) Earnings (); The 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(a);this.name = name;
this.number = number;
this.birthday = birthday;
}
public String getName(a) {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber(a) {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public MyDate getBirthday(a) {
return birthday;
}
public void setBirthday(MyDate birthday) {
this.birthday = birthday;
}
public abstract double earnings(a);
@Override
public String toString(a) {
return "name=" + name + ", number=" + number + ", birthday=" + birthday.toDateString() + "]"; }}Copy the code
2, MyDate class
/* * MyDate class contains :private member variables year,month,day; * The toDateString() method returns a string corresponding to the date: XXXX year xx month xx day */
public class MyDate {
private int year;
private int month;
private int day;
public MyDate(int year, int month, int day) {
super(a);this.year = year;
this.month = month;
this.day = day;
}
public int getYear(a) {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth(a) {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay(a) {
return day;
}
public void setDay(int day) {
this.day = day;
}
public String toDateString(a){
return year + "Year" + month + "Month" + day + "Day"; }}Copy the code
3, SalariedEmployee class
/* * Define the SalariedEmployee class to inherit from the Employee class to implement monthly payroll Employee processing. * This class includes: private member variable monthlySalary; Implements the parent's abstract method earnings(), * which returns the value of monthlySalary; The toString() method outputs the employee type information and the employee's name, number, and birthday. * * /
public class SalariedEmployee extends Employee{
private double monthlySalary; / / monthly wages
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(a) {
return monthlySalary;
}
@Override
public String toString(a) {
return "SalariedEmployee [" + super.toString() + "]"; }}Copy the code
4, HourlyEmployee
/* * use the SalariedEmployee class to define HourlyEmployee, * to implement HourlyEmployee processing. This class includes: private member variables wage and hour; Implements the parent's abstract method earnings(), which returns the wage*hour value; The toString() method outputs the employee type information and the employee's name, number, and birthday. * * /
public class HourlyEmployee extends Employee{
private int wage; // Hourly wage
private int hour; // The number of hours worked 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(a) {
return wage*hour;
}
public int getWage(a) {
return wage;
}
public void setWage(int wage) {
this.wage = wage;
}
public int getHour(a) {
return hour;
}
public void setHour(int hour) {
this.hour = hour;
}
public String toString(a){
return "HourlyEmployee[" + super.toString() + "]"; }}Copy the code
5, PayrollSystem class
import java.util.Calendar;
import java.util.Scanner;
/* * Define the PayrollSystem class, create and initialize an array of Employee variables, * this array holds references to various Employee objects. Use a loop structure to iterate over a number of elements, * output each object's type,name,number,birthday, and the object's birthday. * When the keyboard enters a value for the month, * if the month is the birthday of an Employee object, it also outputs an increase in salary. * * /
public class PayrollSystem {
public static void main(String[] args) {
// Method 1:
// Scanner scanner = new Scanner(System.in);
// system.out. println(" Please enter the month of the month: ");
// int month = scanner.nextInt();
// Method 2:
Calendar calendar = Calendar.getInstance();
int month = calendar.get(Calendar.MONTH);// Get the current month
// System.out.println(month); // January: 0
Employee[] emps = new Employee[2];
emps[0] = new SalariedEmployee("Brush".1002.new MyDate(1992.2.28),10000);
emps[1] = new HourlyEmployee("Mr Bossi".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("Monthly salary is:" + salary);
if((month+1) == emps[i].getBirthday().getMonth()){
System.out.println("Happy birthday! 100 yuan"); }}}}Copy the code
6. Interface
6.1 overview,
On the one hand, it is sometimes necessary to derive a subclass from several classes, inheriting all of their properties and methods. However, Java does not support multiple inheritance. With interfaces, you get the effect of multiple inheritance.
On the other hand, it is sometimes necessary to extract some common behavior characteristics from several classes that do not have an IS-A relationship, but simply share the same behavior characteristics. For example: mouse, keyboard, printer, scanner, camera, charger, MP3 player, mobile phone, digital camera, and mobile hard disk all support USB connection.
An interface is a specification that defines a set of rules that represent the real world “if you are/want to… Must be able to…” Thoughts. Inheritance is a “no” relationship, whereas interface implementation is a “no” relationship.
Interfaces are essentially contracts, standards, specificationsJust like our laws. After the rules are made, everyone must abide by them.
/* An interface is a collection of abstract methods and constant value definitions. * Interface is defined by interface. * All member variables in an interface are modified by public static final by default. * All abstract methods in the interface are by default decorated with public Abstract. * There is no constructor in the interface. * The interface adopts multiple inheritance mechanism. * /
Copy the code
/* * Interface usage * 1. The interface is defined by interface. * 2. In Java: Interfaces and classes are juxtaposed constructs * 3. How to define two interfaces: define interface members * "3.1 JDK7 and previously: can only define global constants and abstract methods *" global constants :public static final, but write, can be omitted not write. 3.2 JDK8: In addition to global constants and abstract methods, static methods and default methods can be defined. * * 4. Constructors cannot be defined in interfaces! Means that the interface cannot be instantiated. * * 5. In Java development, interfaces are used by making classes implements. * If the implementation class does not override all abstract methods in the interface, then the implementation class can be instantiated. Class AA extends BB implementd CC,DD,EE * * 7 Interfaces and interface is inherited, but also can inherit more * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 8. The main purpose of an interface is to be implemented by an implementing class. * * 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 variables
public static final int MAX_SPEED = 7900;
int MIN_SPEED = 1;Public static final is omitted
// Abstract methods
public abstract void fly(a);
void stop(a);// public abstract is omitted
//Interfaces cannot have constructors
// public Flayable(){
//
// }
}
interface Attackable{
void attack(a);
}
class Plane implements Flayable{
@Override
public void fly(a) {
System.out.println("The plane takes off through its engines.");
}
@Override
public void stop(a) {
System.out.println("Driver slows down and stops."); }}abstract class Kite implements Flayable{
@Override
public void fly(a) {}}class Bullet extends Object implements Flayable.Attackable.CC{
@Override
public void attack(a) {
// TODO Auto-generated method stub
}
@Override
public void fly(a) {
// TODO Auto-generated method stub
}
@Override
public void stop(a) {
// TODO Auto-generated method stub
}
@Override
public void method1(a) {
// TODO Auto-generated method stub
}
@Override
public void method2(a) {
// TODO Auto-generated method stub}}/ / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
interface AA{
void method1(a);
}
interface BB{
void method2(a);
}
interface CC extends AA.BB{}Copy the code
6.2, for example,
/* * Interface usage * 1. Interface usage also satisfies polymorphism * 2. Interface, in fact, is the definition of a specification * 3. Development, experience interface programming! * * /
public class USBTest {
public static void main(String[] args) {
Computer com = new Computer();
//1. Create a non-anonymous object for the non-anonymous implementation class of the interface
Flash flash = new Flash();
com.transferData(flash);
//2. Create an anonymous object for the non-anonymous implementation class of the interface
com.transferData(new Printer());
//3. Create a non-anonymous object for the anonymous implementation class of the interface
USB phone = new USB(){
@Override
public void start(a) {
System.out.println("Cell phone starts working.");
}
@Override
public void stop(a) {
System.out.println("Phone off the clock."); }}; com.transferData(phone);//4. Create an anonymous object for the anonymous implementation class of the interface
com.transferData(new USB(){
@Override
public void start(a) {
System.out.println("Mp3 to work");
}
@Override
public void stop(a) {
System.out.println("Mp3 finished work"); }}); }}class Computer{
public void transferData(USB usb){//USB usb = new Flash();
usb.start();
System.out.println("Details of the transmission."); usb.stop(); }}interface USB{
// Constant: defines length and width
void start(a);
void stop(a);
}
class Flash implements USB{
@Override
public void start(a) {
System.out.println("Flash drive is working.");
}
@Override
public void stop(a) {
System.out.println("The usb flash drive is finished."); }}class Printer implements USB{
@Override
public void start(a) {
System.out.println("Printer start up");
}
@Override
public void stop(a) {
System.out.println("Printer finished working"); }}Copy the code
6.3 Application of Interfaces: Proxy Mode
The proxy pattern is one of the most commonly used design patterns in Java development. Proxy design is about providing a proxy for other objects to control access to that object.
/* * Interface application: proxy mode * * */
public class NetWorkTest {
public static void main(String[] args) {
Server server = new Server();
// server.browse();
ProxyServer proxyServer = newProxyServer(server); proxyServer.browse(); }}interface NetWork{
public void browse(a);
}
// Proxy class
class Server implements NetWork{
@Override
public void browse(a) {
System.out.println("Real servers to access the network."); }}/ / the proxy class
class ProxyServer implements NetWork{
private NetWork work;
public ProxyServer(NetWork work){
this.work = work;
}
public void check(a){
System.out.println("Check before networking");
}
@Override
public void browse(a) { check(); work.browse(); }}Copy the code
Application Scenarios:
- Security proxy: Blocks direct access to real roles.
- Remote proxy: Handles remote method calls (RMI) through proxy classes
- Lazy loading: Load the lightweight proxy object first, and then load the real object
For example, if you want to develop a large document viewing software, there are large pictures in the large document, and one picture may be 100MB, it is impossible to display all the pictures when opening the file. In this way, you can use proxy mode. When you need to view pictures, you can use proxy to open large pictures.
classification
- Static proxy (statically defining proxy classes)
- Dynamic proxy (dynamically generated proxy classes)
- JDK built-in dynamic proxy, need reflection and other knowledge
public class StaticProxyTest {
public static void main(String[] args) {
Proxy s = new Proxy(newRealStar()); s.confer(); s.signContract(); s.bookTicket(); s.sing(); s.collectMoney(); }}interface Star {
void confer(a);/ / interview
void signContract(a);/ / sign the contract
void bookTicket(a);/ / booking
void sing(a);/ / singing
void collectMoney(a);/ / collect money
}
// Proxy class
class RealStar implements Star {
public void confer(a) {}public void signContract(a) {}public void bookTicket(a) {}public void sing(a) {
System.out.println("Star: Sing ~~~");
}
public void collectMoney(a) {}}/ / the proxy class
class Proxy implements Star {
private Star real;
public Proxy(Star real) {
this.real = real;
}
public void confer(a) {
System.out.println("Agent interviews.");
}
public void signContract(a) {
System.out.println("Broker signs contract.");
}
public void bookTicket(a) {
System.out.println("Broker booking");
}
public void sing(a) {
real.sing();
}
public void collectMoney(a) {
System.out.println("Brokers take money."); }}Copy the code
6.4 Application of interface: Factory mode
Extension: Factory design pattern. PDF
Contrast between interfaces and abstract classes
No. | The mark | An abstract class | interface |
---|---|---|---|
1 | define | A class containing abstract methods | It is a collection of abstract methods and global constants |
2 | composition | Constructors, abstract methods, ordinary methods, constants, variables | Constants, abstract methods, (JDk8.0: Default methods, static methods) |
3 | use | Subclasses inherit abstract classes (extends) | Subclass implementation interface (implements) |
4 | Relationship between | Abstract classes can implement multiple interfaces | Interfaces cannot inherit from abstract classes, but can inherit from multiple interfaces |
5 | Common Design Patterns | Template method | Simple factory, factory method, agent pattern |
6 | object | Instantiation objects are generated by object polymorphism | |
7 | limited | Abstract classes have the limitation of single inheritance | Interfaces do not have this limitation |
8 | The actual | As a template | As a standard or as an expression of competence |
9 | choose | Interfaces are preferred if both abstract classes and interfaces are available to avoid the limitations of single inheritance |
In development, it is common to see a class that, instead of inheriting an already implemented class, either inherits an abstract class or implements an interface. -【 interview questions 】
interface A {
int x = 0;
}
class B {
int x = 1;
}
class C extends B implements A {
public void pX(a) {
// Failed to compile, x is not clear
System.out.println(x);
// System.out.println(super.x); / / 1
// System.out.println(A.x); / / 0
}
public static void main(String[] args) {
newC().pX(); }}Copy the code
Row 2: wrong
interface Playable {
void play(a);
}
interface Bounceable {
void play(a);
}
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(a) {
return name;
}
public Ball(String name) {
this.name= name;
}
public void play(a) {
ball = new Ball("Football"); //The final field Rollable.ball cannot be assigned System.out.println(ball.getName()); }}Copy the code
practice
CompareObject class
/* * Defines an interface to compare two objects. * * /
public interface CompareObject {
public int compareTo(Object o);
// If the return value is 0, equal; If the value is positive, the current object is large. A negative number indicates that the current object is small
}
Copy the code
Circle the class
/* * Defines a Circle class that declares redius properties and provides getter and setter methods */
public class Circle {
private Double radius;
public Double getRadius(a) {
return radius;
}
public void setRadius(Double radius) {
this.radius = radius;
}
public Circle(a) {
super(a); }public Circle(Double radius) {
super(a);this.radius = radius; }}Copy the code
ComparableCircle class
/* * Define a ComparableCircle class that extends from the Circle class and implements the CompareObject interface. In the ComparableCircle class, we give the implementation body of the interface method compareTo, which is used to compare the radii 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;
// This is not the case
// 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;
/ /}
// The method that wraps the class can be called when the attribute RADIUS is declared to be of type Double
// Correct way 2:
return this.getRadius().compareTo(c.getRadius());
}else{
return 0;
// throw new RuntimeException(" Incoming data type mismatch ");}}}Copy the code
InterfaceTest class
/* * Define a test class InterfaceTest, create two ComparableCircle objects, and call compareTo to compare the radius sizes 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 object is large");
}else if(compareValue < 0){
System.out.println("C2 object large");
}else{
System.out.println("Two of the same");
}
int compareValue1 = c1.compareTo(new String("AA")); System.out.println(compareValue1); }}Copy the code
Interface improvements in Java 8
In Java 8, you can add static methods and default methods to interfaces. Technically, this is perfectly legal, but it seems to violate the idea of an interface as an abstract definition.
Static method:
Use the static keyword. You can call a static method directly through an interface and execute its method body. We often use static methods in classes that we use together. You can find pairs of interfaces and classes like Collection/Collections or Path/Paths in the standard library.
Default method:
The default method is decorated with the default keyword. It can be called by implementing class objects. We provide new methods in existing interfaces while maintaining compatibility with older versions of the code. For example, the Java 8 API provides rich default methods for Collection, List, Comparator, and so on.
Case 1
Interface class
/* * JDK8: In addition to global constants and abstract methods, you can define static methods, default methods (omitted). * * * /
public interface CompareA {
// Static method
public static void method1(a) {
System.out.println("CompareA: xi 'an");
}
// The default method
public default void method2(a){
System.out.println("CompareA: shenzhen");
}
default void method3(a){
System.out.println("CompareA: hangzhou"); }}Copy the code
SubClassTest class
public class SubClassTest {
public static void main(String[] args) {
SubClass s = new SubClass();
// s.method1();
// SubClass.method1();
// Static methods defined in the interface can only be called through the interface.
CompareA.method1();
By implementing class objects, you can call the default methods in the interface.
// If the implementation class overrides the default method in the interface, it still calls the overridden method
s.method2();
If a subclass (or implementation class) inherits a parent class and implements an interface that declares a default method with the same name and argument,
// By default, a subclass calls a method with the same name and argument as the parent class without overriding this method. --> Class priority
// If the implementation class implements multiple interfaces that define default methods with the same name and argument,
// An error is reported if the implementation class does not override this method. --> Interface conflict.
// This requires that we override this method in the implementation classs.method3(); }}class SubClass extends SuperClass implements CompareA.CompareB{
public void method2(a){
System.out.println("SubClass: Shanghai");
}
public void method3(a){
System.out.println("SubClass: Shenzhen");
}
// How to call a method in a subclass (or implementation class) that is overridden in an interface
public void myMethod(a){
method3(); // Call your own overridden method
super.method3(); // the call is declared in the parent class
// Invoke the default method in the interface
CompareA.super.method3();
CompareB.super.method3(); }}Copy the code
SuperClass type
public class SuperClass {
public void method3(a){
System.out.println("SuperClass: Beijing"); }}Copy the code
CompareB class
public interface CompareB {
default void method3(a){
System.out.println("CompareB: Shanghai"); }}12345
Copy the code
Case 2
/* * Exercise: Interface conflict resolution */
interface Filial {/ / of filial piety
default void help(a) {
System.out.println("Mom, I'm here to save you."); }}interface Spoony {/ / spoony
default void help(a) {
System.out.println("Don't be afraid, daughter-in-law. I'm coming."); }}class Father{
public void help(a){
System.out.println("Son, save my wife!"); }}class Man extends Father implements Filial.Spoony {
@Override
public void help(a) {
System.out.println("Who shall I be?");
Filial.super.help();
Spoony.super.help(); }}Copy the code
Inner member of a class. Inner class
When there is an internal part of a thing that needs to be described by a complete structure that only serves the external thing, then the entire internal complete structure is best used by the inner class.
/* * 1.Java allows A class A to be declared in another class B, so that class A is an inner class and class B is an outer class. Classification of inner classes: member inner classes vs. local inner classes (inside methods, inside code blocks, inside constructors) * * 3. Member inner class * "as a member of an external class, * - calling the structure of the external class * - can be modified by static * - Can be modified by 4 different permissions * *" As a class, * - Can define properties, methods, constructors, etc. * - Can be modified by final, Indicates that this class cannot be inherited. The implication is that without using final, we can inherit * - we can abstract the modifier * * 4. Focus on the following three questions * "How to instantiate an object of an inner class of a member" * "How to distinguish between structures that call outer classes in an inner class of a member" * "See innerclasstest1.java for the use of local inner classes in development */
public class InnerClassTest {
public static void main(String[] args) {
// Create 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(a);
bird.sing();
System.out.println();
bird.display("Magpie"); }}class Person{
String name = "Li lei";
int age;
public void eat(a){
System.out.println("People, eat.");
}
// Static member inner class
static class Dog{
String name;
int age;
public void show(a){
System.out.println("Carla is a dog.");
// eat();}}// Non-static member inner class
class Bird{
String name = "Cuckoo";
public Bird(a){}public void sing(a){
System.out.println("I am an owl.");
Person.this.eat();// Invoke the non-static properties of the external class
eat();
System.out.println(age);
}
public void display(String name){
System.out.println(name); // Parameter to the method
System.out.println(this.name); // Inner class attributes
System.out.println(Person.this.name); // Attributes of the external class}}public void method(a){
// Local inner class
class AA{{}}// Local inner class
class BB{}}public Person(a){
// Local inner class
class CC{}}}Copy the code
InnerClassTest1 class
public class InnerClassTest1 {
// Very rare in development
public void method(a){
// Local inner class
class AA{}}// Return an object of a class that implements the Comparable interface
public Comparable getComparable(a){
Create a class that implements the Comparable interface: a local inner class
// Method 1:
// class MyComparable implements Comparable{
//
// @Override
// public int compareTo(Object o) {
// return 0;
/ /}
//
/ /}
//
// return new MyComparable();
// Method 2:
return new Comparable(){
@Override
public int compareTo(Object o) {
return 0; }}; }}Copy the code
8.1 anonymous Inner Classes
/* * 1. An anonymous inner class cannot define any static members, methods, or classes. Only one instance of an anonymous inner class can be created. * An anonymous inner class must be used after new to implicitly implement an interface or implement a class. * new * * 2. Format: the superclass constructor (argument list) | implementing an interface () {* / / class body part of the anonymous inner class *} * * 3. Characteristics of anonymous inner classes * > Anonymous inner classes must inherit a parent class or implement an interface * > Anonymous inner classes can only have one object * > Anonymous inner class objects can only use polymorphic form references */
interface Product{
public double getPrice(a);
public String getName(a);
}
public class AnonymousTest{
public void test(Product p){
System.out.println("Bought one" + p.getName() + "Spent." + p.getPrice());
}
public static void main(String[] args) {
AnonymousTest ta = new AnonymousTest();
// To call the test method, pass in the Product argument,
// Pass in an instance of its anonymous implementation class
ta.test(new Product(){
public double getPrice(a){
return 567.8;
}
public String getName(a){
return "AGP card"; }}); }}Copy the code
8.2. Pay attention to the use of local inner 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 a local inner class method (e.g. :show), if a local variable (e.g. : num) is called ina local inner class method (e.g. : method), * requires the local variable to be declared final. * * JDK 7 and earlier: requires that this local variable be explicitly declared final * * JDK 8 and later: can omit the final declaration * */
public void method(a){
// Local variables
int num = 10;
class AA{
public void show(a){
// num = 20; //Local variable num defined in an enclosing scope must be final or effectively finalSystem.out.println(num); }}}}Copy the code