Home Java javaTutorial Anonymous inner classes in depth

Anonymous inner classes in depth

Dec 15, 2016 pm 12:25 PM
anonymous inner class

Anonymous inner classes are suitable for creating classes that only need to be used once, such as the Command object required in command mode. The syntax of anonymous inner classes is a bit strange. When an anonymous inner class is created, an instance of the class is immediately created. The class definition disappears immediately, and the anonymous inner class cannot be reused.
The format for defining anonymous inner classes is as follows:

new 父类构造器(参数列表)|实现接口()  
{  
 //匿名内部类的类体部分  
}
Copy after login

As can be seen from the above definition, anonymous inner classes must inherit a parent class or implement an interface, but they can only inherit at most one parent class or implement an interface.
There are two more rules about anonymous inner classes:
1) Anonymous inner classes cannot be abstract classes, because when the system creates an anonymous inner class, it will immediately create an object of the inner class. Therefore, anonymous inner classes are not allowed to be defined as abstract classes.
2) Anonymous inner classes do not define constructors. Because anonymous inner classes do not have a class name, they cannot define a constructor, but anonymous inner classes can define instance initialization blocks.
Use instance initialization blocks to complete what the constructor needs to accomplish.
The most common way to create an anonymous inner class is to create an object of an interface type, as shown in the following program:

interface Product{  
   public double getPrice();  
   public String getName();  
}  
public class TestAnonymous{  
   public void test(Product p){  
   System.out.println("购买了一个"+p.getName()+",花掉       了"+p.getPrice());  
  }  
 public static void main(String[]args){  
    TestAnonymous ta = new TestAnonymous();  
    ta.test(new Product(){  
    public double getPrice(){  
       return 567;  
    }  
   public String getName(){  
      return "AGP显卡";  
   }  
  });  
 }  
}
Copy after login

The TestAnonymous class in the above program defines a test method, which requires a Product object as a parameter, but Product is just an interface, and objects cannot be created directly. Therefore, consider creating an object of the Product interface implementation class and passing it into this method. --- If this Product interface implementation class needs to be used repeatedly, an independent object should be defined through the implementation class. class; if this Product interface implementation class only needs to be used once, you can use the method in the above program to define an anonymous inner class.

As you can see in the above program, the class keyword is not required to define an anonymous class. Instead, when defining an anonymous inner class, the object of the anonymous inner class is directly generated. The code part in bold above is the class body part of the anonymous class.
Since anonymous inner classes cannot be abstract classes, anonymous inner classes must implement all abstract methods contained in its abstract parent class or interface.
The above code for creating Product implementation class objects can be split into the following code:

class AnonymousProduct implements Product{  
  public double getPrice(){  
   return 567;  
    }  
  public String getName(){  
   return "AGP显卡";  
    }  
 }  
 ta.test(new AnonymousProduct());
Copy after login

When an anonymous inner class is created by implementing an interface, the anonymous inner class cannot explicitly create a constructor, so the anonymous inner class has only one implicit Parameterless constructor, so parameter values ​​cannot be passed in the brackets after the new interface name.
But if you create an anonymous inner class by inheriting the parent class, the anonymous inner class will have a similar constructor to the parent class. The similarity here refers to having the same list of formal parameters.
abstract class Device{  
  private String name;  
  public Device(){  
  }  
  public Device(String name){  
   this.name = name;  
  }  
  public abstract double getPrice();  
  //此处省略了name属性的setter和getter方法  
 }  
 public class AnonymousInner{  
  public void test(Device d){  
   System.out.println("购买了一个"+d.getName()+",花掉了"+d.getPrice());  
  }  
  public static void main(String[] args){  
   AnonymousInner ai = new AnonymousInner();  
   //调用有参数的构造器创建Device匿名实现类的对象  
   ai.test(new Device("电子示波器"){  
    public double getPrice(){  
     return 67;  
    }  
   });  
   //调用无参数的构造器创建Device匿名实现类的对象  
   Device d = new Device(){  
    //初始化块  
    {  
     System.out.println("匿名内部类的初始化块...");  
    }  
    //实现抽象方法  
    public double getPrice(){  
     return 56;  
    }  
    public Sting getName(){  
     return "键盘";  
    }  
   };  
   ai.test(d);  
  }  
 }
Copy after login

The above program creates an abstract parent class Device. This abstract parent class contains two constructors: one without parameters and one with parameters. When creating an anonymous inner class with Device

as the parent class, you can pass in parameters (such as the bold part in the first paragraph of the above program), or you can not pass in parameters (such as the second bold part in the above program) character part).

When creating an anonymous inner class, all abstract methods in the interface or abstract parent class must be implemented. If necessary, you can also override the ordinary methods in the parent class. For example, in the second bold code part of the program above, the anonymous inner class overrides the getName method of the abstract parent class Device class, and the getName method is not abstract. method.
If the anonymous inner class needs to access the local variables of the outer class, it must use the final modifier to modify the local variables of the outer class, otherwise the system will report an error.

interface A{  
  void test();  
 }  
 public class TestA{  
  public static void main(Strign[] args){  
   int age = 0;  
   A a = new A(){  
    public void test(){  
     //下面语句将提示错误:匿名内部类内访问局部变量必须使用final修饰  
     System.out.println(age);  
    }   
   };  
  }  
 }
Copy after login

The bold subcode in the above program is that the anonymous inner class accesses the local variables of the outer class. Since the age variable is not modified with the final modifier, the bold code will cause a compilation exception.





For more articles related to anonymous internal classes, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How does Java anonymous inner class solve memory leak problem? How does Java anonymous inner class solve memory leak problem? May 01, 2024 pm 10:30 PM

Anonymous inner classes can cause memory leaks. The problem is that they hold a reference to the outer class, preventing the outer class from being garbage collected. Solutions include: 1. Use weak references. When the external class is no longer held by a strong reference, the garbage collector will immediately recycle the weak reference object; 2. Use soft references. The garbage collector will recycle the weak reference object when it needs memory during garbage collection. Only then the soft reference object is recycled. In actual combat, such as in Android applications, the memory leak problem caused by anonymous inner classes can be solved by using weak references, so that the anonymous inner class can be recycled when the listener is not needed.

What are the design patterns for anonymous inner classes in Java? What are the design patterns for anonymous inner classes in Java? May 02, 2024 pm 04:42 PM

Anonymous inner classes are special inner classes in Java that have no explicit name and are created through the new expression. They are mainly used to implement specific interfaces or extend abstract classes and are used immediately after creation. Common anonymous inner class design patterns include: Adapter pattern: converts one interface into another interface. Strategy Pattern: Defining and Replacement Algorithms. Observer pattern: Register observers and handle events. It is very useful in practical applications, such as sorting a TreeSet by string length, creating anonymous threads, etc.

What are the advantages of anonymous inner classes in Java? What are the advantages of anonymous inner classes in Java? Apr 30, 2024 am 11:39 AM

Anonymous inner classes are used in Java as special inner classes that facilitate subclassing, simplifying code, and handling events (such as button clicks). Practical cases include: Event handling: Use anonymous inner classes to add click event listeners for buttons. Data transformation: Sort collections using Collections.sort method and anonymous inner class as comparator.

What is the life cycle of Java anonymous inner classes? What is the life cycle of Java anonymous inner classes? May 01, 2024 pm 04:06 PM

The lifetime of an anonymous inner class is determined by its scope: Method-local inner class: Valid only within the scope of the method that created it. Constructor inner class: bound to the outer class instance and released when the outer class instance is released. Static inner classes: loaded and unloaded at the same time as external classes.

What are the common mistakes with anonymous inner classes in Java? What are the common mistakes with anonymous inner classes in Java? May 02, 2024 am 09:03 AM

Anonymous inner class usage error: Accessing an out-of-scope variable using catching an undeclared exception in a non-thread-safe environment

How to optimize performance of Java anonymous inner classes? How to optimize performance of Java anonymous inner classes? May 02, 2024 am 08:48 AM

The performance problem of anonymous inner classes is that they are recreated every time they are used, which can be optimized through the following strategies: 1. Store anonymous inner classes in local variables; 2. Use non-static inner classes; 3. Use lambda expressions. Practical tests show that lambda expression optimization has the best effect.

What is the alternative to anonymous inner classes in Java? What is the alternative to anonymous inner classes in Java? Apr 30, 2024 pm 01:15 PM

Lambda expressions, as an alternative to anonymous inner classes, provide a more concise way to define the implementation of functional interfaces: use the short syntax (parameters)->expression to define anonymous functions. Suitable for situations where functional interfaces need to be implemented (only one abstract method). Can simplify tasks such as list sorting and thread definition.

In what scenarios are Java anonymous inner classes not suitable for use? In what scenarios are Java anonymous inner classes not suitable for use? May 03, 2024 pm 05:42 PM

Anonymous inner classes are not suitable for use when: need to access private members, need multiple instances, need inheritance, need to access generic types

See all articles