How non-homogeneous in Java accesses variable values (Novice insights may be low)

Source: Internet
Author: User

Recently learning basic Java knowledge, this is one of the most common problems, I would like to list three different methods of outlier, of course, I chose the simplest three kinds:

1. You can call the properties and methods of the class that you want to access by using static statics variables. Because

characteristics of static in Java :

      • The static variable is initialized when the class is loaded.
      • Static variables for multiple instances share the same block of memory area.
1  Public classA1 {2  Public StaticString str = "Hello world!";3 }4 5  Public classB2 {6  Public Static voidMain (string[] args) {7 System.out.println (A1.STR);8 }9}

2. The class to be accessed can be instantiated in this class, and the instantiated properties and methods can be invoked after new.

Similar to the first method, but does not require the static property to be set for an instance variable, it requires that the object must be instantiated to be called.

1  Public classA1 {2  PublicString str = "Hello world!";3 }4 5  Public classB2 {6  Public Static voidMain (string[] args) {7A1 A =NewA1 ();8 System.out.println (A.STR);9 }Ten}

3. The third method takes one step further and writes out the value method in the class that is being valued.

 Public class A1 { public String str = ' Hello world! ' ;
String Getstr () {
return str;
}} publicclass B2 {publicstaticvoid New A1 (); System.out.println (A.getstr ());}}

How non-homogeneous in Java accesses variable values (Novice insights may be low)

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.