Inner classes in Java

Source: Internet
Author: User
Tags static class

Inner class
A class defined inside a class, inside a method, or inside a local code block
(1) Non-static inner class
Class A {
Class Inner {
}
}
A = new A ();
A.inner Inner = A.new Inner ();

(2) Static inner class
Class A {
Static Class Inner {
}
}
A.inner Inner = new A.inner ();

(3) Local inner class
*) locally defined type, can only be used locally
*) An object of a local inner class that can be transferred outward to the parent type
Class A {
Weapon A () {
Class Inner implements Weapon {
}

Inner i = new Inner ();
return i;
}
}

(4) Anonymous inner class: A class that is often used in writing code, which generally means not declaring object names, creating objects directly and overriding methods.

An example of an anonymous inner class can be seen first.

Define an interface first:

 Public Interface Animal {    void  eat ();}

Then look at defining a test class, using the class local inner class and the anonymous inner class, respectively. The use of anonymous internal classes can be seen through this small example.

 Public classTest1 { Public Static voidMain (string[] args) {Animal A1=test1 ();                A1.eat (); Animal A2= Test2 ("Tiger");    A2.eat (); }    Private StaticAnimal test1 () {classTiger Implements animal{//implementing Interfaces@Override Public voideat () {System. out. println ("It's a carnivorous animal! "); }} Tiger Tiger=NewTiger (); returnTiger; }        Private StaticAnimal test2 (String name) {//Animal Tiger = new Animal () {//Anonymous inner class implementation interface//@Override//Public void Eat () {//System.out.println (name+ "is a carnivorous animal"); //}        //}; //return Tiger;        return NewAnimal () {//Anonymous inner classes are more straightforward@Override Public voideat () {System. out. println (name+"It's a carnivorous animal .");        }        }; }}

Inner classes in Java

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.