设为首页 加入收藏

TOP

java笔记(5)(this,super,override,instanceof,static)(二)
2023-07-25 21:33:48 】 浏览:48
Tags:java 笔记 this super override instanceof static
Student); //true // System.out.println(person instanceof Teacher); //不能编译 // System.out.println(person instanceof String); //不能编译 System.out.println("==================================="); Student student = new Student(); System.out.println(student instanceof Object); //true System.out.println(student instanceof Student); //true System.out.println(student instanceof Person); //true // System.out.println(student instanceof Teacher); //不能编译 // System.out.println(student instanceof String); //不能编译

static

static修饰的属性和方法属于类本身,称为静态成员/方法,在类加载时一同加载,因此即使该类没有进行实例化,静态成员/方法也已经被分配了内存空间。而非静态成员和方法则只有在实例化时才被分配内存空间,这个生命周期的差异,使得在类仅加载还没有实例化的时候,非静态成员/方法对静态成员/方法是不可见的,为了避免出现非法访问内存的问题,静态成员/方法禁止访问非静态成员/方法。相反的,当非静态成员/方法加载时,静态成员/方法一定已经存在了,因此可以在非静态成员/方法中访问静态成员/方法,静态成员/方法也可以互相访问。

public class P4{
	{
		System.out.println("Anonymous code block!");
	}
	static {
		System.out.println("Static anonymous code block!");
	}
	public P4(){
		System.out.println("No parameter constructor!");
	}
	public static void main(String[] args){
        P4 per1 = new P4();
        System.out.println("==============");
        P4 per2 = new P4();
	}
}

执行结果如下:
image
可见静态代码块在类加载时首先执行,且在类生命周期中只被执行一次,而匿名代码块则在构造方法之前执行,且每次实例化都会执行。

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Java学习一 下一篇Java 函数式编程「二」

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目