Object-oriented - static &Math class&custom tool class&code block

Table of contents

static keyword

Precautions for static

Advantages and disadvantages of static

Application scenarios

 Custom tool class

code block

static keyword

  • static is a modifier used to modify members (member variables, member methods)
  • Characteristics of static

        –Loaded as the class is loaded

        –Prioritizes the object’s existence

        –Shared by all objects of the class

        – can be called by the class name

Case:

package com.demo01;
/*
 * static:是一个关键字,用于修饰成员变量和成员方法
 * static的特点:
 * 			被所有的对象所共享
 * 			可以使用类名调用
 * 			静态的加载优先于对象
 * 			随着类的加载而加载
 * 
 */
public class StaticDemo {
	public static void main(String[] args) {
		Person.graduateFrom = "湖南大学";
		
		Person p = new Person();
		p.name = "段誉";
		p.age = 18;
		//p.graduateFrom = "湖南大学";
		p.speak();
		
		Person p2 = new Person();
		p2.name = "萧峰";
		p2.age = 20;
		//p2.graduateFrom = "湖南大学";
		p2.speak();
		Person.think();
	}
}

class Person {
	String name;
	int age;
	static String graduateFrom;//毕业院校
	
	public void speak() {
		System.out.println(name + "---" + graduateFrom);
	}
	
	public static void think() {
		System.out.println("思考");
	}
}

Analysis: Create a class object first with Person.graduateFrom = "Hunan University". Static member variables should be accessed using a static method, using Person instead of p.

Precautions for static

Static method:

* 1. Static member variables can be called

* 2. Static member methods can be called

* 3. Non-static member variables cannot be called

* 4. Non-static member methods cannot be called

* Static methods can only call static members

Non-static methods:

* 1. Static member variables can be called

* 2. Static member methods can be called

* 3. Non-static member variables can be called

* 4. Non-static member methods can be called

* Is this object included in the static method? No

Analysis:Static methods belong to the class, not static members. Whether it is a member variable or a member method, it belongs to the object, and the static method is calling the class. It has been initialized. If you can call a static member of a non-static member, you will find that it does not belong to the class, but to the object. There is no object yet, so what should we do? So they are contradictory, so static cannot call non-static, and conversely, non-static can call static member variables. When we use static, we have declared the object before calling it.

package com.demo01;
/*
 * static的注意事项:
 * 			静态方法:
 * 				1、可以调用静态的成员变量
 * 				2、可以调用静态的成员方法
 * 				3、不可以调用非静态成员变量
 * 				4、不可以调用非静态成员方法
 * 				静态方法只能调用静态的成员
 * 			非静态方法:
 * 				1、可以调用静态的成员变量
 * 				2、可以调用静态的成员方法
 * 				3、可以调用非静态的成员变量
 * 				4、可以调用非静态的成员方法
 * 		
 * 	静态的方法中是否this这个对象?没有的
 * 				
 * 
 */
public class StaticDemo2 {
	public static void main(String[] args) {
		Student.graduateFrom = "湖南大学";//1、可以调用静态的成员变量
		//Student.study();
		Student s = new Student();
		s.eat();
	}
}


class Student {
	String name;
	int age;
	
	//
	static String graduateFrom;//毕业院校
	
	public static void study() {
		//System.out.println(graduateFrom);
		sleep();//可以调用静态的成员方法
		
		//System.out.println(name);//不可以调用非静态成员变量
		
		//eat();//不可以调用非静态成员变量,这样是错误得
		
	}
	
	public static void sleep() {
		System.out.println("sleep");
		
	}
	
	public void eat() {
		System.out.println("eat");
		
		System.out.println(graduateFrom);
		sleep();
		
		
	}
	
}

Advantages and disadvantages of static

  • statictargetgood point

        – Provides separate storage space for shared data of objects, saving space. There is no need to store one for each object shares

        – can be called directly by the class name without creating an object in the heap memory

  • Disadvantages of static

        –Access is limited. (Static is good, but you can only access static)

Application scenarios

  • The Math class contains methods for performing basic mathematical operations. Classes commonly used for mathematical operations.
  • Mathclassuse

        –There is no constructor, how do we use it?

  • MathKind of controlSupernatural ability

        –Character:PI

        –方法:absmaxmin powceilfloorround,random

package com.demo02;

public class MathDemo {
	public static void main(String[] args) {
		//Math:包含了一些基本的数学运算方法
		//static double PI  
		System.out.println(Math.PI);
		//
		//static double abs(double a)  :返回绝对值
		System.out.println(Math.abs(15.67));
		System.out.println(Math.abs(-0.10));
		
		//static double ceil(double a) 天花板   向上取整
		System.out.println(Math.ceil(-2.1));
		System.out.println(Math.ceil(1.6));
		//static double floor(double a)  地板  向下取整
		System.out.println(Math.floor(1.2));
		System.out.println(Math.floor(-1.6));
		
		//static long round(double a)  :四舍五入
		System.out.println(Math.round(-1.2));
		System.out.println(Math.round(1.6));
		
		//static double max(double a, double b) 
		System.out.println(Math.max(3, 4));
		
		//static double pow(double a, double b) :返回第一个参数的第二个参数次幂
		System.out.println(Math.pow(3, 4));
		
		//static double random() :返回一个随机数,大于零且小于一
		System.out.println(Math.random());
		
		
		 
	}
}

 Custom tool class

Case:

package com.demo03;

/**
 * 数组工具类
 * @author (无限嚣张(菜菜))
 *
 */
public class MyArrays {
	private MyArrays() {} 
	
	/*
	 * 返回数组中最大的元素
	 * 
	 */
	public static int getMax(int[] arr) {
		if(arr==null||arr.length==0) {
			return 0;
		}
		int max = arr[0];//参照物
		//遍历数组
		for(int x = 1;x < arr.length;x++) {
			if(arr[x] > max) {
				max = arr[x];//替换参照物
			}
		}
		
		return max;
	}
	
	
	/*
	 * 返回数组中指定参数的索引
	 * 
	 */
	
	public static int getIndex(int[] arr,int a) {
		//遍历数组
		for(int x = 0;x < arr.length;x++) {
			if(arr[x] == a) {
				return x;
			}
		}
		
		return -1;//如果查不到指定的参数,则返回-1
	}
}
package com.demo03;

public class MyArraysDemo {
	public static void main(String[] args) {
		//MyArrays m = new MyArrays();
		int[] arr = {3,5,8,10,1};
		int max = MyArrays.getMax(arr);
		System.out.println(max);
		
		int index = MyArrays.getIndex(arr, 8);
		System.out.println(index);
		
		
	}
}

code block

  • In Java, code enclosed with {} is called codeblock
  • Code block classification

        –Local code block——Exists in the method, controls the life cycle (scope) of the variable, and destroys it after use

        –Construction code block——Extract common features in the construction method, which will be executed every time the object is created, and executed before the construction method is executed

        –Static code block—— is loaded as the class is loaded. It is only loaded once. Some initialization needs to be done when loading the class. For example, loading the driver

        –same steps(multiline steps)< /span>

package com.demo04;

public class BlockDemo {
	public static void main(String[] args) {
		
		//局部代码块:存在于方法中,控制变量的生命周期(作用域),用完销毁
		{
			for(int x = 0;x < 10;x++) {
				System.out.println("我爱Java");
			}
			int num = 10;
		}
		//System.out.println(num);
		
		Teacher t = new Teacher();
		Teacher t2 = new Teacher("王老师",18);
	}
}

class Teacher {
	String name;
	int age;
	
	//构造代码块:提取构造方法中的共性,每次创建对象都会执行,并且在构造方法执行之前执行
	{
		for(int x = 0;x < 10;x++) {
			System.out.println("我爱Java");
		}
		System.out.println("我爱Java");
	}
	
	//静态代码块:随着类的加载而加载,只加载一次,加载类时需要做的一些初始化,比如加载驱动
	static {
		System.out.println("我爱Java");
	}
	
	public Teacher() {
		System.out.println("我是无参空构造");
	}
	
	public Teacher(String name,int age) {
		System.out.println("我是有参构造");
		
		this.name = name;
		this.age = age;
	}
	
	
}

Analysis: We first create a new object without parameters, execute the local code block after entering it, and output 10 words I love Java, num=10. After running, num is deleted. We create a new teacher object, and the static code block is executed first. , after execution, the construction code block is executed, and the construction method is executed only after the construction code block is executed.

Guess you like

Origin blog.csdn.net/zywcxz/article/details/128845647