Java learning notes 8 --- class static variables and static methods access and call methods, java learning notes

Source: Internet
Author: User

Java learning notes 8 --- class static variables and static methods access and call methods, java learning notes

Static variables are also called class variables, static methods are also called class methods. They are collectively referred to as static members or class members. Static members are modified by static and belong to the entire class. All objects share these static members. No object needs to be created. The static member is initialized during class loading, and its memory position remains unchanged throughout the runtime until the class is detached. In view of these characteristics of static members, accessing static variables and defining or calling static methods are also different from non-static members. The descriptions are as follows.

1. Static variables

  • Both non-static and static methods of the class can directly access static variables.
  • Other classes can access static variables of a class either by instance name or directly by class name. We recommend that you use the class name for access, in this way, the accessed variable is a static variable.

2. Static Method

  • You cannot directly access non-static variables or directly call non-static methods. You need to instantiate an object and then use this object to access non-static variables or non-static methods to be called. That is to say, the static method cannot directly use non-static members. In my opinion, non-static members exist based on objects. When no instance has an object, non-static members do not allocate memory space, to use non-static members for static methods, you do not know where to find them. Of course, you cannot directly use non-static members.
  • Other classes need to call static methods of a class. They can be called either by instance name or directly by class name. We recommend that you call the method by class name, in this way, we can intuitively describe that the called method is a static method.

 

3. The conclusion above is verified with simple code below

Defines a Person class. The class code can be found at the end.

 

(1). The static method of the class can directly access static variables

  • The static method staticMethod accesses the static variable citizenship.
  • Defines and uses the local variable testY.

The staticMethod () method is as follows:

public static void staticMethod() {
		int testY = 20;
		
		System.out.println("She has applied for " + citizenship + " citizenship"); //static variable access
		System.out.println("She's now " + testY + " years old");  //local variable access
	}

The main () method is as follows:

public static void main(String[] args) {
		Person xiaoxi = new Person("xiaoxi",29,"female","piano");
		
		xiaoxi.informationPrint();
		
		staticMethod();
	}

The output result is as follows:

My name is xiaoxi
I am 29 years old
I am a girl
My hobby is piano
I am a chinese
She has applied for Chinese citizenship
She's now 20 years old

Result Analysis:

  • Static methods can directly access static variables
  • You can use static methods to customize local variables.

 

(2) The static method cannot directly access non-static variables.

[1]. staticMethod directly accesses the static variable citizenship, and an error occurs.

  • The static method staticMethod accesses the static variable citizenship.
  • Defines and uses the local variable testY.
  • Accessed the non-static variable holobby.

The staticMethod () method is as follows:

public static void staticMethod() {
		int testY = 20;
		
		System.out.println("She has applied for " + citizenship + " citizenship"); //static variable access
		System.out.println("She's now " + testY + " years old");  //local variable access
		System.out.println("She doesn't like " + hobby); //nonstatic variable access
	}

The main method is the same as above.

The output result is as follows:

My name is xiaoxi
I am 29 years old
I am a girl
My hobby is piano
I am a chinese
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Cannot make a static reference to the non-static field hobby

	at human.Person.staticMethod(Person.java:99)
	at human.Person.main(Person.java:107)

Result Analysis:

  • Static methods Cannot directly access non-static variables. Otherwise, the error "Cannot make a static reference to the non-static field Hoby" may occur.

 

[2]. staticMethod () creates an object testP, which accesses the non-static variable holobby by testP and is successfully executed.

 

  • Static Method staticMethod uses the static variable citizenship
  • Defines and uses the local variable testY.
  • Create a Person instance testP and use the variable holobby of testP.

 

The staticMethod () method is as follows:

public static void staticMethod() {
		int testY = 20;
		Person testP = new Person();
		
		System.out.println("She has applied for " + citizenship + " citizenship"); //static variable access
		System.out.println("She's now " + testY + " years old");  //local variable access
		System.out.println("She doesn't like " + testP.hobby); // nonstatic variable access via object instance testP
	}

The main method is the same as above.

The output result is as follows:

My name is xiaoxi
I am 29 years old
I am a girl
My hobby is piano
I am a chinese
She has applied for Chinese citizenship
She's now 20 years old
She doesn't like null

Result Analysis:

  • To access non-static variables in a static method, You Can instantiate an object before accessing it through the object.

 

(3) static methods cannot be called directly.

[1]. staticMethod () directly accesses the non-static method ionionprint (), and an error occurs.

  • Static Method staticMethod uses the static variable citizenship
  • Defines and uses the local variable testY.
  • Create a Person instance testP and use the hoppy variable of testP.
  • Call the non-static method informationPrint () directly ()

The staticMethod () method is as follows:

public static void staticMethod() {
		int testY = 20;
		Person testP = new Person();
		
		System.out.println("She has applied for " + citizenship + " citizenship"); //static variable access
		System.out.println("She's now " + testY + " years old");  //local variable access
		//System.out.println("She doesn't like " + testP.hobby); //nonstatic variable access
		System.out.println("She doesn't like " + testP.hobby); // nonstatic variable access via object instance testP
		System.out.println("Her personal information is as follows:");
		informationPrint();
	}

The main () method is the same as above.

The output result is as follows:

My name is xiaoxi
I am 29 years old
I am a girl
My hobby is piano
I am a chinese
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Cannot make a static reference to the non-static method informationPrint() from the type Person

	at human.Person.staticMethod(Person.java:103)
	at human.Person.main(Person.java:111)

Result Analysis:

  • Static methods Cannot directly call non-static methods; otherwise, errors similar to direct access to non-static variables may occur. Cannot make a static reference to the non-static method informationPrint () from the type Person.

 

[2]. Call the informationPrint () method through the existing object testP, And the execution is successful.

  • Static Method staticMethod uses the static variable citizenship
  • Defines and uses the local variable testY.
  • Create a Person instance testP and use the hoppy variable of testP.
  • Call non-static method informationPrint () through testP ()

The staticMethod () method is as follows:

public static void staticMethod() {
		int testY = 20;
		Person testP = new Person();
		
		System.out.println("She has applied for " + citizenship + " citizenship"); //static variable access
		System.out.println("She's now " + testY + " years old");  //local variable access
		System.out.println("She doesn't like " + testP.hobby); // nonstatic variable access via object instance testP
		System.out.println("Her personal information is as follows:");
		//informationPrint();
		testP.informationPrint();
	}

The main () method is the same as above.

The output result is as follows:

My name is xiaoxi
I am 29 years old
I am a girl
My hobby is piano
I am a chinese
She has applied for Chinese citizenship
She's now 20 years old
She doesn't like null
Her personal information is as follows:
My name is null
I am 0 years old
Something is wrong!
My hobby is null
I am a chinese

Result Analysis:

  • To call a non-static method for a static method, You Can instantiate an object and then call it through the object.

 

Attached Person class:

package human;

public class Person {
	String name;
	int age;
	String gender;
	
	private String hobby;
	protected String residence;
	
	static String citizenship = "Chinese";
	
	public Person() {
		
	}
	
	public Person(String n, String g) {
		this.name = n;
		this.gender = g;
	}
	
	public Person(String n, int a, String g, String h) {
		this.name = n;
		this.age = a;
		this.gender = g;
		this.hobby = h;
		
		//test:静态变量初始化的时机是否在构造方法之前
		System.out.println("constructor:");
		System.out.println("change value of the static variable citizenship " + "\"" + citizenship + "\"");
		citizenship = "US";
		System.out.println(" to " + "\"" + citizenship + "\"");
	}	

	public Person(String n, int a, String g, String h, String r) {
		this.name = n;
		this.age = a;
		this.gender = g;
		this.hobby = h;
		this.residence = r;
	}	
	
	public void setName(String n) {
		this.name = n;
	}
	
	public void setAge(int a) {
		this.age = a;
	}
	
	public void setGender(String g) {
		this.gender = g;
	}
	
	public void setHobby(String h) {
		this.hobby = h;
	}
	
	public void setResidence(String r) {
		this.residence = r;
	}
	
	public String getName() {
		return this.name;
	}
	
	public int getAge() {
		return this.age;
	}
	
	public String getGender() {
		return this.gender;
	}
	
	public String getHobby() {
		return this.hobby;
	}
	
	public String getResidence() {
		return this.residence;
	}
	
	public void informationPrint() {
		System.out.println("My name is " + getName());
		System.out.println("I am " + getAge() + " years old");
		
		if(getGender() == "female")
			System.out.println("I am a girl");
		else
			if(getGender() == "male")
				System.out.println("I am a boy");
			else
				System.out.println("Something is wrong!");
		System.out.println("My hobby is " + hobby);
		
		if(citizenship == "Chinese")
			System.out.println("I am a chinese");
		//test:静态变量是否在构造方法之前初始化
		else
			if(citizenship == "US")
				System.out.println("I am an American");
			else
				System.out.println("Oh,something is wrong");
	}

	public static void staticMethod() {
		int testY = 20;
		Person testP = new Person();
		
		System.out.println("She has applied for " + citizenship + " citizenship"); //static variable access
		System.out.println("She's now " + testY + " years old");  //local variable access
		System.out.println("She doesn't like " + testP.hobby); // nonstatic variable access via object instance testP
		System.out.println("Her personal information is as follows:");
		//informationPrint();
		testP.informationPrint();
	}
	
	public static void main(String[] args) {
		Person xiaoxi = new Person("xiaoxi",29,"female","piano");
		
		xiaoxi.informationPrint();
		
		staticMethod();
	}
}



Related Article

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.