Getting Started with Java. Building Blocks and Static Code Blocks

package pro1;

class Person {
	private String name;
	private int age;

	{
		// Same as the constructor, as long as the object is instantiated, it will definitely run once
		// run before constructor
		System.out.println("Building Block");
	}

	static {
		// No matter how many objects are created, only run once
		System.out.println("Static code block");
	}

	public boolean compare(Person p1) {
		Person p2 = this;
		if (p2 == p1) {
			return true;
		}
		if ((p2.age == p1.age) && p2.name.equals(p1.name)) {
			return true;
		} else {
			return false;
		}
	}

	public static int count = 0;

	public Person() {
		count++;
		System.out.println("initialized" + count + "objects");
	}

	public Person(String name, int age) {
		this();
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}

public class T4 {
	public static void main(String[] args) {
		Person[] persons = new Person[2];
		persons[0] = new Person("Zhang San", 111);
		persons[1] = new Person("Zhang San", 111);
		System.out.println("Are the two objects the same: " + persons[0].compare(persons[1]));
	}
}


Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327050665&siteId=291194637