Java creates internal class objects in other classes, and other classes in java

Source: Internet
Author: User

Java creates internal class objects in other classes, and other classes in java

Objects of internal classes can be created using. this and. new. Specific Code

Package xunlong; class pri {class inner {int k = 0; public pri outer () {return pri. this ;}} public inner print () {return new inner () ;}} public class Root {public static void main (String [] args) {pri a = new pri (); pri. inner B =. new inner (); pri. inner k =. print (); System. out. println (B = k); k. k = 5; System. out. println (B. k); System. out. println (k. k); pri c; c = B. outer (); System. out. println (a = c );}}

In this Code, I used an instance of pri to create an inner class object B. Because the non-static internal class must be attached to the external class instance, it is confirmed at the end of the code that the object c of the external class returned by. this is the same object as the Instance Object a of the external class.

In this Code, I also created a method print in the external pri. This method returns the object of the internal class, and the object of this internal class is a brand new object, in the code, it is confirmed that the innner object k created through the print method is not the same object as the object B created through object.

If you set the inner class in this code to private, this code will fail because we cannot access the inner through the external class pri.

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.