Static keyword for Basic Java learning

This is the 9th day of my participation in the November Gwen Challenge. See details: The Last Gwen Challenge 2021.

About the author

  • The authors introduce

🍓 Blog home page: author’s home page 🍓 Introduction: 🥇, a high quality creator in JAVA field, 🎓, a junior in college, participated in various provincial and national competitions and won a series of honors. 🍓 pay attention to me: pay attention to my learning materials, document download all have, regularly update the article every day, inspirational to do a JAVA senior program ape 👨💻.

Use the static keyword to define attributes

Before we look at static defining property operations, let’s write the following program.

Now define an action class that represents Chinese people, all of whom live in China.

class Person{
	private String name;
	private int age;
	String country = "China";
	public Person(String name,int age){
		this.name = name;
		this.age = age;
	}
	public String getInfo(a){
		return "Name:"+this.name+""+"Age:"+this.age+""+"State:"+country; }}public class TestDemo1{
	public static void main(String args[]){
		Person per1 = new Person("Zhang".30);
		Person per2 = new Person("Bill".40);
		Person per3 = new Person("Fifty".50); System.out.println(per1.getInfo()); System.out.println(per2.getInfo()); System.out.println(per2.getInfo()); }}Copy the code

Obviously, no matter how many Person objects there are, the content of the country property is the same. If China is renamed, then all the Country properties of the Person class can be easily changed, which is too tedious.

Now you can find problems like this:

1. The country property should be public, but the code above assigns it to each object;

2. There are too many objects to consider when maintaining the country property, which is not easy to maintain.

So if you want to distinguish a country from a common attribute and represent a common concept, you should use the static keyword.

class Person{
	private String name;
	private int age;
	static String country = "China";
	public Person(String name,int age){
		this.name = name;
		this.age = age;
	}
	public String getInfo(a){
		return "Name:"+this.name+""+"Age:"+this.age+""+"State:"+country; }}public class TestDemo1{
	public static void main(String args[]){
		Person per1 = new Person("Zhang".30);
		Person per2 = new Person("Bill".40);
		Person per3 = new Person("Fifty".50);
		per1.country = "The United States." "; System.out.println(per1.getInfo()); System.out.println(per2.getInfo()); System.out.println(per2.getInfo()); }}Copy the code

Now to change the attribute of an object country will affect the other country attribute of an object, but there is a problem since using the static attributes of the definition of a public property, so if now it is an object modified is inappropriate, there should be a collection of all objects on behalf of the largest, is the class. The best way to call a static property is to call the class name.static property.

Person. Country = “USA “; // Class name. Static attribute

Through this procedure, it should be clear that:

Static attributes are not stored in the heap memory, but in the global data area.

Class attributes can be called directly from the type name.

3Static properties are defined in the class, but they can be called when no object is instantiated (normal properties are stored in the heap, static properties are stored in the global data area)

In future development, the first thing to come to mind is not static attributes, but generic ones.

Use static to define methods

class Person{
	private String name;
	private int age;
	//static String country = "China ";
	private static String country = "China";
	public Person(String name,int age){
		this.name = name;
		this.age = age;
	}
	// The non-static variable this cannot be referenced from a static context
	// There is no way to use this variable in static methods
	public static void setCountry(String c){
		country = c;
	}
	public static String getCountry(a){
		return country;
	}
	public String getInfo(a){
		return "Name:"+this.name+""+"Age:"+this.age+""+"City:"+country; }}public class TestDemo1{
	public static void main(String args[]){
		/*Person per1 = new Person(" Person ",30); Person per2 = new Person(" Person ",40); Person per3 = new Person(" Person ",50); Per1. Country = "Thailand "; System.out.println(per1.getInfo()); System.out.println(per2.getInfo()); System.out.println(per2.getInfo()); * /
		// The method called must be static
		// Name: Zhang SAN Age: 30 City: People's Republic of China
		Person.setCountry("The People's Republic of China");// No instantiated object is generated
		Person p1 = new Person("Zhang".30); System.out.println(p1.getInfo()); }}Copy the code

Static and non-static methods are defined as static and non-static. Methods that operate on static methods are defined as follows:

Static methods cannot call non-static methods or properties.

Methods that are not static can call static methods and static properties.

Discussion: Why are there such restrictions?

Properties and methods defined with static can be called without instantiating the object, whereas non-static methods must be called after the object has been instantiated.

Analytical master method

Before we look at main methods, consider a small difference: When we looked at Java method definition formats, we gave the following format: If a method is defined in a main class and is called directly by the main method, it must be preceded by public static.

public class TestDemo{
	public static void main(String args[]){
		print();   // Call the main method directly
	}
	public static void print(a){
		System.out.println("Hello World"); }}Copy the code

Print () : print () : print () : print () : print () : print () : print () : print () : print (); Almost all non-static methods have one feature: non-methods are called by instantiated objects.

public class TestDemo{
	public static void main(String args[]){
        //Hello,World!
		 new TestDemo().print();   // Instantiate the object to call non-static methods
	}
	public  void print(a){
		System.out.println("Hello,World!"); }}Copy the code

Main method composition:

  • Public: indicates an access permission

  • Static: This method is called directly by the class name, executing the class: Java class name

  • Void: The main method is where it all starts

  • Main: specifies a method name that is found by default when executing a class

  • String args[] : represents run-time parameters that are received as strings

public class TestDemo2{
	public static void main(String args[]){
		for(int x = 0;x<args.length;x++){
			System.out.println(args[x]);
		}
	}
}
Copy the code

Use of keywords

In real work, static is used for two reasons:

  1. You want to be able to easily perform certain operations of a class without instantiating an object
  2. Now I want to represent the concept of data sharing

Count the number of instantiated objects of a class

class Person{
	private String name;
	static int num = 0;
public Person(a){
	num++;
} 
public void setName(String name){
	this.name = name;
}
public String getName(a){
	returnname; }}public class TestDemo3{
	public static void main(String args[]){
		Person per1 =new Person();
		Person per2 =new Person();
		Person per3 =new Person();
		Person per4 =newPerson(); System.out.println(Person.num); }}Copy the code

The code block

Plain code block

public class PuTongDaiMaKuai{
	public static void main(String args[]){{// Plain code block
			int x = 10;                // Local variables
				System.out.println("x ="+x); 
		}
		int x = 100;               // Global variables
		System.out.println("x ="+x); }}//x =10
//x =100
Copy the code

Building blocks

class Person{
	public Person(a){
		System.out.println("Constructor Method 1")
	}
	{
		System.out.println("Building Block 2"); }}public class PuTongDaiMaKuai{
	public static void main(String args[]){
		new Person();
		new Person();
		newPerson(); }}/* struct block 2 struct block 1 struct block 2 struct block 1 */
Copy the code

You can see that the constructor executes before the constructor, and that the execution of the constructor occurs whenever a new instantiated object is created.

A static block

Static blocks are also defined in a class. If a constructor is defined with the static keyword, it is a static block, but static blocks are considered in two ways.

Case 1: a static block defined in a non-main class

class Person{
	public Person(a){
		System.out.println("Constructor Method 1");
	}	
	{/ / building blocks
	System.out.println("Building Block 2");
	}	
	static{/ / static block
	System.out.println("Static block 3"); }}public class JingTaiKuai{
	public static void main(String args[]){
		new Person();		
		new Person();		
		newPerson(); }}/* struct block 3 struct block 2 struct block 1 struct block 1 struct block 2 struct block 1*/
Copy the code

As you can see, static blocks take precedence over construction blocks and are called only once, no matter how many instantiated objects are produced.

Case two: a static block defined in the main class

public class TestDemo4{
	static{
		System.out.println("Static block");
	}
	public static void main(String args[]){
	System.out.println(Master method); }}/* Static block master method */
Copy the code

Static blocks in the main class take precedence over main method execution, so since static blocks have this feature, we can take advantage of it.

inheritance

Person java:

class Person{
	private String name;
	private int age;
	public void setName(String name){
		this.name=name;
	}
	public void setAge(int age){
		this.age=age;
	}
	public String getName(a){
		return this.name;
	}
	public int getAge(a){
		return this.age; }}Copy the code

Student java:

class Student{
	private String name;	
	private int age;	
	private String school;	
	public void setName(String name){		
		this.name=name;	
	}	
	public void setAge(String age){
		this.age=age;	
	}	
	public void setSchool(String school){
		this.school=school;
	}	
	public String getName(a){
		return name;	
	}	
	public int getAge(a){		
		return age;	
	}	
	public String getSchool(a){		
		returnschool; }}Copy the code

It can be found that a large part of the content has been repeated, but now regardless of the program, the relationship between students and people is: a student is a person, but the definition of students is more strict than that of human beings, at this time, according to the previous concept can not be solved.

Implementation of inheritance

In Java, if you want to explicitly implement an inherited relationship, you can do so using the extends keyword in the following format:

// It is important to note that subclasses are also called derived classes;
// A superclass is also called a super class.
classA subclassextendsThe parent class{}
Copy the code
class Person{
	private String name;
	private int age;
	public void setName(String name){
		this.name=name;
	}
	public void setAge(int age){
		this.age=age;
	}
	public String getName(a){
		return this.name;
	}
	public int getAge(a){
		return this.age; }}class Student extends Person
{}public class TestDemo5{
	public static void main(String args[]){
	Student stu = new Student();
	stu.setName("Zhang"); System.out.println(stu.getName()); }}Copy the code

By running the program, I can find that now in the subclass, there is no method defined, but can directly continue to use the operations defined in the parent class, so in the subclass can reuse the parent class, of course, the subclass can also define their own operations.

class Person{
	private String name;
	private int age;
	public void setName(String name){
		this.name=name;
	}
	public void setAge(int age){
		this.age=age;
	}
	public String getName(a){
		return this.name;
	}
	public int getAge(a){
		return this.age; }}class Student extends Person{
	private String school;
	public void setSchool(String school){
		this.school = school;
	}
	public String getSchool(a){
		return this.school; }}public class TestDemo5{
	public static void main(String args[]){
	Student stu = new Student();
	stu.setName("Zhang");
	stu.setSchool("University of Pennsylvania");
	// Name = Zhang SAN,school = University of Pennsylvania
	System.out.println("name = " + stu.getName()+ ",school = "+stu.getSchool()); }}Copy the code

Through the above procedures found that in the development language, the most basic function of the subclass is to maintain the original operation of the parent class, so there will be no so-called in real life “black sheep” concept in the program language. Therefore, it can be found through the program that the inherited function is an extension of the existing class function.

Limits on inheritance

  1. After using inheritance, a subclass object must instantiate its parent constructor before instantiating the object, and then call the subclass constructor before instantiating the object. – in real life, no Lao zi, and absolutely no offspring, affirmation is Lao tze out first, after the small turn out again, so the instantiation way very consistent with the real life, if the call subclasses structure before you go to call the superclass can prove is to instantiate the superclass object first, then, anti-fuzzy instance class object.
  2. Java allows only single inheritance, not multiple inheritance.
  3. When inheriting, a subclass inherits all the structures of its parent class. All non-private operations are inherited explicitly, and all private operations are inherited implicitly. The student class also inherits the name and age attributes of the Person class. These attributes are indirect inheritance (implicit inheritance) and can only be accessed by methods
class Person{
	public Person(a){
			System.out.println("Superclass construction"); }}class Student extends Person{
	public Student(a){        
	// The first line of the constructor must be written
	super(a);// If this statement has no more arguments, it is the same as if it were not written
	System.out.println("Subclass construction"); }}public class JiChengXing{
	public static void main(String args[]){
		newStudent(); }}Copy the code

If there is no explicit no-argument constructor in the parent class, then super() can be used to specify the parent constructor parameter to call.

class Person{
	public Person(String name,int age){
			System.out.println("Superclass construction"); }}class Student extends Person{
	public Student(String name,int age,String school){
		super(name,age);
		System.out.println("Subclass construction"); }}public class JiChengXing{
	public static void main(String args[]){
		new Student("Jokser".22."Peking University"); }}Copy the code

overwrite

Now that there is a class inheritance relationship, there is a relationship between the class subclass and the parent class, and in the subclass may define exactly the same method or attribute name as the parent class, this time becomes overwrite.

Method overrides

A subclass overrides a method when it defines a method with exactly the same name, return value type, parameter type, and number as the parent class.

class A{
	public void print(a){
		System.out.println("I am the output method of A."); }}class B extends A{
	public void print(a){
		System.out.println("I am the output method of B"); }}public class TestDemo6{
	public static void main(String args[]){
		B b=new B();
		// I am the output method of Bb.print(); }}Copy the code

When a method in one of our classes is overridden, if the subclass object is instantiated, the method being called is the overridden method.

However, there is a point to note when overriding a method: the method overridden by a subclass cannot have more stringent access control permissions than the parent class. For access control permissions, we have been exposed to three types: private

If the access permission of the parent class is default, the override permission of the subclass can only be default or public. If the method of the parent class is public, the override permission of the subclass can only be public.

Hint: Don’t look for trouble! From now on all methods will be of type public. I’ll just say private for the property

When a subclass overrides a superclass method, then in that case, if the subclass wants to call the overridden method of the superclass, it prefixes the method with “super”.

class A{
	public void print(a){
		System.out.println("I am the output method of A."); }}class B extends A{
	public void print(a){
	// If you want to call the parent method in a subclass, add the super. method name to the first line of the subclass
		super.print();
		System.out.println("I am the output method of B"); }}public class TestDemo6{
	public static void main(String args[]){
		B b=new B();
		// I am the output method of Bb.print(); }}Copy the code

:full_moon_with_face: Interview question: The difference between overloading and overwriting? Can the return value be different when reloading?

The difference between overloading overwrite
The English word OverLoding Overrider
concept The method name is the same, and the parameter type and number are different The method name, parameter type, and parameter number must all be the same
The scope of Occurs in a class Occurs in multiple classes
limit There is no requirement Overridden methods cannot have higher access control rights than their parent classes

Methods can be overloaded with different return types, but good design requires that the types be consistent.

Attribute to cover

When a subclass defines an attribute name that has the same name as the parent class, the attribute is overridden.

class A{
	String str = "Hello World";
}
class B extends A{
	int str = 100;
	public void print(a){
		System.out.println(this.str);
		System.out.println(super.str); }}public class FuXie{
	public static void main(String args[]){
		B b=new B();
		/ / 100
		//Hello Worldb.print(); }}Copy the code

This makes little sense because, from a development point of view, the property must be wrapped and then not overwritten.

The super keyword

:full_moon_with_face: Interview question: What is the difference between this and super?

The difference between this super
define Represents an object of this class Represents a superclass object
use This class operates on: this(), this. property, this. method Super (), super. property, super. method
Call constructor Calling the class constructor is placed on the first line The subclass calls the superclass construct on the first line
Find the range No parent can be found in this class Find the parent class directly by subclass
special Represents the current object There is no

Array operations (defining Array parent classes)

Requirements: * * * * now requires definition of an integer array class operation, the size of the array is determined by the external, the user can be increased to an array of data, and get all the data in an array, can also according to the size of an array of growth of external provide, on the array of original expand the specified capacity, in addition, derived in such two subclasses:

Sort class (sortArray) : get the array content is sorted out of the result;

Fanzhuan: Get the contents of the array as a result of the inversion;

The first thing to do is define the parent class; you don’t need to think about subclasses at all.

class Array{
	private int data[];// Define an array whose size is externally determined
	private int foot = 0;// Array horn
	// Create an array
	public Array(int len){
		if(len > 0) {this.data = new int [len];// Create space
		}else{
			this.data = new int [1]; }}// Add an array
	 public boolean add(int num){
		if(this.foot >= data.length){
			return false;
		}else{
			this.data[this.foot ++] = num;
			return true; }}// Output an array
	 public int[] getData(){
		return this.data;
	 }
	 // Dynamically expand the array
	 public void inc(int num){
		int [] newData = new int [this.data.length + num];
		/* public static void arrayCopy (Object SRC, SRC - source array) Int srcPos, srcPos - The start position in the source array. Object Dest, dest - Destination array. Int destPos, destPos - The start position in the destination data. Int length) length - Number of array elements to copy. * /
		System.arraycopy(this.data,0,newData,0.this.data.length);
		this.data = newData; }}// Sort the array
class sortArray extends Array{
	public sortArray(int num){
		super(num);
	}
	public int[] getData(){
		java.util.Arrays.sort(super.getData());
		return super.getData(); }}// Array contents are flipped
class Fanzhuan extends Array{
	public Fanzhuan(int num){
		super(num);
	}
	public int[] getData(){
		int head = 0;
		int tail = super.getData().length - 1;
		int center = super.getData().length / 2;
		for(int i = 0 ; i < center ; i++,head++,tail--){
			int temp = super.getData()[head];
			super.getData()[head] = super.getData()[tail];
			super.getData()[tail] = temp;
		}
		return super.getData(); }}public class Exam1{
	public static void main(String args[]){
		//Array arr = new Array(5);
		//sortArray arr = new sortArray(5);
		Fanzhuan arr = new Fanzhuan(5);
		System.out.println(arr.add(3));
		System.out.println(arr.add(1));
		System.out.println(arr.add(3));
		System.out.println(arr.add(8));
		System.out.println(arr.add(0));
		arr.inc(3);
		System.out.println(arr.add(7));
		System.out.println(arr.add(20));
		System.out.println(arr.add(10));
		int result[] = arr.getData();
		for(int i = 0; i < result.length ; i++){
			System.out.print(result[i]+"、"); }}}Copy the code

In the whole program development, you can obviously feel that all operations are around the expansion of the parent function, but the method has not changed, so in the development, the design of the parent class is the most important, the subclass is the best inheritance or overwrite overwrite operation, should be based on the method of the parent class.

The final keyword

In Java, the final keyword represents the concept of a finalizer. You can define classes, methods, and variables with final.

Classes defined with final cannot have subclasses

final class A{}class B extends A{}Copy the code

Methods defined using final cannot be overridden by subclasses

final class A{
	public final void print(a){}}class B extends A{
	public  void print(a){}}Copy the code

Variables defined with final represent constants, which must be defined with default values and cannot be changed

final class A{
	final String str = "hello world";/ / constant
	public final void print(a){
		str = "Hello";   // Cannot be modified}}public class Final{
	public static void main(String args[]){}}Copy the code

If we now use a constant defined by public static, that constant becomes a global constant.

public static final String STR = "hello,world";// Global constants
Copy the code

For the above three operations on the final keyword, only the concept of global constants is used in development, such as class or method definition, almost never occurs in our programming.

Each word is larger when defining final constants.