Java anonymous inner class usage with example

Source: Internet
Author: User

First of all, why are anonymous classes

Two reasons (the resulting mission)

1. Simplify code writing

In some cases, the class only needs to extend a method, there is no need to write a subclass for a method, and then call the subclass, the anonymous class is required at this time

2. Calling the protected method of a class within a class within a different package (in fact, it can be understood and the first reason is the same)

The anonymous class inherits the parent class and calls the protected method of the parent class

Conditions:

Anonymous class to accomplish the above mission, you need to inherit a class or implement an interface

Form: New < class or interface > < class body >

Example 1:

/** * General class * @author Masan * */class normal{public void func () {System.out.println ("Do with Name");}} public class Unnamedclass {public static void main (string[] args) {normal m = new Normal () {public void Func () {SYSTEM.OUT.P Rintln ("Do without Name");}; M.func ();}}

The output is: "Do without name",

The anonymous class inherits the normal class and overrides the Func method of the parent class

So what is the object of this M class, the parent class or the child class??

Example 2:

/** * General class * @author Masan * */class normal{public void func () {System.out.println ("Do with Name");}} public class Unnamedclass {public static void main (string[] args) {normal m = new Normal () {
A method that overrides the parent class, func () public void Func () {System.out.println ("Do without Name");};/ /define a method that does not have a parent class func1public void Func1 () { System.out.println ("func1 do without Name");}}; M.func (); Output "Do without Name" m.func1 (); Error, no this method// call FUNC1 (), this notation is correct, you can call any method of anonymous class new Normal () {public void Func () {System.out.println ("Do without name ");}; public void Func1 () {System.out.println (' func1 do without name ');}}. Func1 ();//The example above illustrates that this relationship is a parent class reference to a subclass instance of new, and M is a reference to the parent class but an instance of the subclass}}

The above example shows that this relationship is a parent class reference to the subclass instance of new, so what happens to the interface?

Example 3: Anonymous class implementation interface

First define an interface public interface Human {public void eat ();p ublic void Drink ();}
public class Unnamedclass {public static void main (string[] args) {
As you can see, there is a new interface here, Java interface is not a constructor, then what is the situation here Human Masan = new Human () { ///anonymous class implements all methods of Human interface @overridepublic void Eat () {System.out.println ("Masan eat");} @Overridepublic void Drink () {System.out.println ("Masan Drink");}; Masan.eat (); Compile through, output "Masan eat" masan.drink (); Compile through, output "Masan drink"
It can be seen that Masan this object can invoke all implemented methods, that is, actually Masan is an instance of an anonymous class,
So instead of instantiating the interface and instantiating the anonymous class}}

  

Example 4: Protected method for calling classes of different packages

Access permissions If you are unfamiliar with it, attach a permission map

Modifier words

This class

Class of the same package

Inheriting classes

Other classes

Private

X

X

X

None (Default)

X

X

Protected

X

Public

Parent class: (Different packages)

Package Another;public class Parent {public void run () {System.out.println (' Run with legs! ');}    public void drink () {System.out.println ("Parent Drink with mouth!");        Protected  method protected void Eat () {System.out.println ("Parent eat with mouth! (protected) ");}}

Another package calls the protected method

Package Base;import another. Parent;public class Unnamedclass {public static void main (string[] args) {Parent p = new Parent ();p. Eat ();  Error, because it is not a class within the same package, is not a subclass, so you cannot call the protected method;//  assume that only this place needs to call this protected permission eat () method//  You can use anonymous class to inherit the parent, Call the parent class of the eatnew parent () {///anonymous class to define a new method, the method body calls the parent class's Eat ();p ublic void peat () {super.eat ();};}. Peat ();//Output  "Parent eat with mouth! (protected) "succeeded in invoking the parent class's Eat ()}}

Summing up, the above 4 examples can be seen:

The difference between an anonymous class and an ordinary class is that there is no name and time to use

The inherited parent class and implementation interface of an anonymous class conform to Java's general rules

Anonymous classes are a bit special when instantiated

To construct the new parent class, instantiate the anonymous class itself (because there is no name)

Similarly, a reference can only be used by a parent class, so it is generally a parent reference to a subclass (anonymous class) instance

Java anonymous inner class usage with example

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.