Advanced Java object oriented

Object oriented advanced

1, Encapsulate private

In development, in order to avoid logic errors, we suggest encapsulating all properties and providing setter and getter methods for setting and obtaining operations.

significance:

Protect or prevent code (data) from being inadvertently damaged by us. Protect member properties from direct access and modification by programs outside the class.

principle:

Hide the properties and implementation details of the object, only expose the access methods, and control the access level.

For example:

Not encapsulated:

	Person1 p = new Person1();
	p.name = "Zhang San";
	//Logical error can not be defined as negative
	p.age = -10000;
	p.say();

After encapsulation:

public class Demo2 {

	public static void main(String[] args) {
		Person2 p = new Person2();
		p.name = "Zhang San";
		p.setAge(-10000);
		p.say();
		System.out.println(p.getAge());		
	}
}

class Person2 {
	String name;
	private int age;
	//Set method to set reasonable input interval
	void setAge(int age2) {
		if(age2 < 0 || age2 > 150) {
			System.out.println("Unreasonable age, automatically set to 1");
			age = 1;
		} else {
			age = age2;
		}
	}
	//If you need to take out the value in the attribute for operation, you can call the getAge() method
	int getAge() {
		return age;
	}
	
	void say() {
		System.out.println("self-introduction:" + name + ",Age" + age);
	}
	
}

2, this keyword

In the foundation of Java, the this keyword is one of the most important concepts. Use this keyword to complete the following operations:

  • Represents the current object (the object that is currently calling this method)
  • Calling properties in a class
  • Calling a method or constructor in a class

For example:

public class Demo3 {

	public static void main(String[] args) {
		Person3 p1 = new Person3("Zhang San",18);
		Person3 p2 = new Person3("Li Si",18);
		
		p1.say();
		p2.say();
		//Parameterless calls two parameter through the constructor's this, passing the default name and age
		Person3 p3 = new Person3();
		p3.say();

	}

}
/**
 * this Refers to the current object (the object that is currently calling this method)
 * You can call not only properties, but also methods
 * @author MayLee
 *
 */
class Person3 {
	private String name;
	private int age;
	
	Person3(){
		this("Default name",1);
	}
	
	Person3(String name, int age) {
		this.name = name;
		this.age = age;
	}
	
	void say() {
		System.out.println("full name:" + this.name + ",Age:" + this.age);
	}
}

[note]:

In a construction method, when calling another construction method, the code to be invoked must be written in the first line of the construction method. The function of the construction method is to build objects. Usually, the object is operated after the object is built. For example, if an object has no parameters and no parameters, then two parameters. In fact, in the process of adjusting two parameters, the object has not been initialized, so some logic can be executed only after its initialization. If the execution of logic is placed before object initialization, The program will report an error)

3, Static static

summary:

Static means "static" and can be used to modify member variables and member methods (we will learn about static code blocks and static inner classes later).

The main function of static is to create member variables or methods independent of specific objects

Simple understanding:

The method or variable modified by the static keyword does not need to rely on the object for access. As long as the class is loaded, it can be accessed through the class name. And it will not create multiple copies in memory because of multiple creation of objects.

For example:

package xinzhike;

public class Demo5 {

	public static void main(String[] args) {
        //Instead of creating an object, you can call it directly. 
		StaticDemo.say();
        //say2(); Object not created, cannot call
	}
}

class StaticDemo {
	/**
	 * When a statically decorated method is called, the object may not have been created
	 */
    //Statically decorated objects have nothing to do with objects. They are loaded when the class is used.
	static void say() {
		System.out.println("I love my family!");
		
	}
	/**
	 * Called through an object
	 */
	void say2() {
		System.out.println("I love my parents!");
		say();
	}
}

[key points]:

1. Static members are loaded and initialized when the class is loaded for the first time (loaded into the method area)

2. No matter how many objects exist in a class, there is always only one static attribute in the content (which can be understood as common to all objects)

3. When accessing: static cannot access static, non static can access static!

For example:

package xinzhike;
/**
 * static keyword
 * Statically decorated attributes will be stored in the method area
 * @author MayLee
 *
 */
public class Demo4 {

	public static void main(String[] args) {
		Employee.region = "Beijing";
		
		Employee e1 = new Employee("Zhang San");
		Employee e2 = new Employee("Li Si");
		Employee e3 = new Employee("WangTwo ");
		Employee e4 = new Employee("Pockmarks");
//		Assumption: company relocation, Tianjin
//		e1.setRegion("Tianjin");
//		e2.setRegion("Tianjin");
//		e3.setRegion("Tianjin");
//		e4.setRegion("Tianjin");
		
		e1.say();
		e2.say();
		e3.say();
		e4.say();
		
		//Assumption: company relocation, Tianjin
		Employee.region = "Tianjin";
		
		e1.say();
		e2.say();
		e3.say();
		e4.say();
		
		Employee e5 = new Employee();
		System.out.println(Employee.count);
	}

}

class Employee {
	
	private String name;
	static String region;
    //Indicates the number of times the object was created
	static int count;
	
	Employee(String name, String region) {
        //count+1 for each execution
		count++;
		this.name = name;
		this.region = region;
	}
	Employee(String name) {
		count++;
		this.name = name;
	}
	Employee() {
		count++;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getRegion() {
		return region;
	}
	public void setRegion(String region) {
		this.region = region;
	}

	void say() {
		System.out.println("Employee name:" + name + ",Employee's region:" + region);
	}
	
} 

4, Code block

Common code block

The code blocks that appear in the executed process are called ordinary code blocks. Construct code block

A member code block in a class, which we call a construction code block, is executed every time an object is created and before the construction method.

Static code block

The member code block decorated with static in the class is called static code block, which is executed when the class is loaded. A block of code that executes only once each time the program starts to close.

Synchronous code block

Learn in the subsequent multithreading technology.

[interview question]:

Construction method and execution sequence of construction code block and static code block:

Static code block -- > construction code block -- > Construction

For example:

package xinzhike;

public class Demo6 {

	public static void main(String[] args) {
		/**
		 * Write code blocks in a sequentially executed code flow
		 */
		{
//			int a = 10;
//			System.out.println(a);
		}
		
		Person6 p1 = new Person6();
		Person6 p2 = new Person6();
	}

}

class Person6 {
	private String name;
	private int age;
	/**
	 * Construct a code block, with each creation of an object, and execute before constructing a method.
	 * 
	 * Different from the construction method:
	 * No matter which construction method the user calls to create the object, the construction code block must be executed.
	 * 
	 */
	{
		System.out.println("Execute 1 on object creation");
	}
	/**
	 * The static code block is used to load the class (for the first time), and the static code block is executed.
	 * Because the class is loaded only once, the static code block is executed only once.
	 */
	static {
		System.out.println("Static code block execution");
	}
	public Person6() {
		System.out.println("Execute 2 on object creation");
	}
	public Person6(String name) {
		System.out.println("Execute 2 on object creation");
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

5, Package

1. Introduction:

  • Organize similar or related classes or interfaces in the same package to facilitate the search and use of classes.
  • Packages and folders are the same. The names of classes in different packages can be the same. When calling the same classes in two different packages at the same time, the package name should be added to distinguish them. Therefore, the package can avoid name conflicts.
  • Packages also limit access rights. Only classes with access rights can access classes in a package.

2. Usage rules:

At the head of the. java file, you must write which package the class belongs to

Format: package name;

Definition: it is usually composed of multiple words. The letters of all words are in lowercase. Words are separated by. It is generally named "com. Company name. Project name. Module name..."

3. Origin of specifications

Due to the object-oriented nature of Java, every java developer can write their own Java Package. In order to ensure the uniqueness of the naming of each Java Package, in the latest Java programming specification, developers are required to add a unique prefix to the package name they define. Because the domain name on the Internet will not be repeated, most developers use the domain name of their company on the Internet as the unique prefix of their packages.

For example: com.java.xxx

3.import keyword

import Package name.Class name;

4. Permission modifier

picture

6, main method

	public static void main(String args[]) 
    The meanings of the above parameters are as follows:: 
		public: Represents public content that can be called by all operations 
         static:The presentation method is static and can be called directly by the class name 
         void:Indicates that there is no return value operation 
         main:Method name specified by the system. If main If you write wrong or not, you will report an error: NoSuchMethodError: main 
         String[] args: String array, receiving the of parameters 
     public class StaticDemo10{ 
         public static void main(String args[]){ 
             //	The output is 0 and the length is 0 by default
             System.out.println(args.length);
         	for(int i=0; i<args .length;i++){ 
             	System. out . println(args[i]);              
        	 }       
    	 } 
 	}; 
When executing a class, you can pass in parameters to it and divide it with spaces. 
    java StaticDemo10 1 2 3 4 5 6 7  At this time args.length The length becomes 7
 However, if I want to enter the following parameters now“ hello world","hello vince","hello mjw". 
Because it is separated by spaces, all the above three groups of parameters will be used as six groups of parameter input. At this time, if you want to complete the content input with spaces, the parameters need to be used“""Wrap it up.
    Execution class:
java StaticDemo10 "hello world" "hello vince" "hello mjw"

Tags: Java JavaSE

Posted on Thu, 02 Sep 2021 17:07:29 -0400 by pwes24