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)