Java:static和内部类

1.static

(1)静态变量

在定义一个类时,只是描述他的特征和行为,并没有产生数据。当用new创建该类的实例对象,计算机才会分配给每一个对象空间去储存数据。但是有时候我们会希望某些特殊的数据在数据中独此一份。譬如学校名字,所有学生都共享同一个学校名字,不必在每一个对象所占的空间中都占据一个学校名字。

而static关键字来修饰成员,该变量变为静态变量被所有实例共享。例如

class Student{
	static String schoolName;
}

public class text5 {
	public static void main(String[] args) {
		Student str1 = new Student();
		Student str2 = new Student();
		Student.schoolName = "XXXX";
		System.out.println("1.我们的学校是"+str1.schoolName);
		System.out.println("2.我们的学校是"+str2.schoolName);
	}
}

运行结果:

但是static只能修饰成员变量不能修饰局部变量否则编译会报错。

(2)静态方法

有时我们会希望不创建对象直接调用方法,在类中定义方法前加static关键字,我们称这种方法为静态方法。

class Person{
	public static void say() {
		System.out.println("Hello word");
	}
}
public class text3 {

	public static void main(String[] args) {
		Person.say();

	}

}

(3)静态代码块

在Java类中,使用{}这包围起的代码被称为代码块,用static修饰的为静态代码块。每次运行类只加载一次,因此静态代码块只执行一次。在程序中,通常会使用静态代码块来对类的成员变量进行初始化。

class Person{
	static String country;
	static {
		country = "China";
		System.out.println("person类静态代码执行了");
	}
}
public class text3 {

	static {
		System.out.println("测试类的静态代码执行了");
	}
	public static void main(String[] args) {
		Person p1 = new Person();
		Person p2 = new Person();

	}

}

从结果看该方法创建两个实例化对象,静态代码只执行一次。这说明类在第一次使用才会被加载并且只会加载一次


(4)单例模式

单例模式是Java设计模式的一种,它指在设计一个类时,需要保证这个类在运行过程中只存在一个实例对象。

  • 类的构造方法使用private修饰,声明为私有,这样就不能在类的外部用new创建实例化对象
  • 在类的内部创建一个该类的实例化对象,再用静态INSTANCE引用该对象,由于成员变量禁止外界直接访问,因此用private修饰,声明对象私有化
  • 为了让外部访问对象创建getinstance静态方法。返回该类的实例INSTANCE。由于对象是实例的可以用“对象.方法名”的方法。
class Single{
	private static Single INSTANCE = new Single();
	private Single() {
		
	}
	public static Single getInstance() {
		return INSTANCE;
	}
}

public class text6 {

	public static void main(String[] args) {
		Single s1 = Single.getInstance();
		Single s2 = Single.getInstance();
		System.out.println(s1==s2);
	}
}

从结果看s1,s2引用的是同一个对象,而getinstance是唯一访问Single类实例对象的方法。

2.内部类

(1)成员内部类

class Outer{
	private int num = 4;
	public void test(){
		Inner inner = new Inner();
		inner.show();
	}
	class Inner{
		void show() {
			System.out.println("num="+num);
		}
	}
}

public class text7 {

	public static void main(String[] args) {
		Outer outer = new Outer();
		outer.test();

	}

}

又或者测试类这么写

public class text7 {

	public static void main(String[] args) {
		Outer.Inner inner = new Outer().new Inner();
		inner.show();

	}

}

(2)静态内部类

class Outer{
	private static int num = 4;
	
	static class Inner{
		void show() {
			System.out.println("num="+num);
		}
	}
}

public class text7 {

	public static void main(String[] args) {
		Outer.Inner inner = new Outer.Inner();
		inner.show();

	}

}

(3)方法内部类



class Outer{
	private int num = 4;
	public void test(){
		class Inner{
			void show() {
				System.out.println("num="+num);
			}
		}
		Inner inner = new Inner();
		inner.show();
	}
	
}

public class text7 {

	public static void main(String[] args) {
		Outer outer = new Outer();
		outer.test();

	}

}

猜你喜欢

转载自blog.csdn.net/qq_39248122/article/details/81066772