Research on internal classes in Java

Source: Internet
Author: User

 

Java has introduced internal classes since jdk1.1. For more information, see the code. The advantage is that you can be lazy when designing classes. It can be used to reference other internal elements of a class. It is similar to taking this internal class as an element of the original class. There are also some design details that can be hidden, but there are still many advantages.

Define two interfaces

Package interfacepackage;

Public interface destination {
String readlabel ();
}

Package interfacepackage;

Public interface contents {

Int value ();

}

A class with test code

Package debug;

Import interfacepackage. contents;
Import interfacepackage. destination;

Public class tester {
Private int valuerate = 2;

Private class Pcontent implements contents {
Private int I = 11 * valuerate;

Public int value (){
Return I;
}
}

Protected class pdestination implements destination {
Private string label;

Private pdestination (string whereto ){
Label = whereto;
}

Public String readlabel (){
Return label;
}
}

Public destination DEST (string s ){
Return new pdestination (s );
}

Public contents cont (){
Return new Pcontent ();
}
Public static void main (string ARGs [])
{
Tester P = new Tester ();
Contents c = P. cont ();
System. Out. println (C. Value ());
Destination d = P. DEST ("fire outside the sky ");
System. Out. println (D. readlabel ());
System. Out. println ("done ");
}
}
The above code is an internal dynamic class. Can the internal static class be used? The answer is yes, but the static internal class cannot reference other non-static elements of the class. For example, if the Pcontent internal class in the above example is changed to static class, the valuerate attribute cannot be referenced, in this case, a compilation error will be reported, but it can be run if valuerate is changed to static.

 

 

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.