java_instanceof_static关键字讲解

instanceof

  • (类型转换)引用类型,判断一个对象是什么类型
//父类
public class Person {

}


//子类
public class Student extends Person{
	
}

//子类
public class Teacher extends Person{

}

//测试类
public class test {
	public static void main(String[] args) {
		Object o=new Student();
		System.out.println(o instanceof Student);//true
		System.out.println(o instanceof Person);//true
		System.out.println(o instanceof Object);//true
		System.out.println(o instanceof Teacher);//false
		System.out.println(o instanceof String);//false
		System.out.println("-------------------------");
		Person p=new Student();
		System.out.println(p instanceof Student);//true
		System.out.println(p instanceof Person);//true
		System.out.println(p instanceof Object);//true
		System.out.println(p instanceof Teacher);//false
	//	System.out.println(p instanceof String);//编译就报错!!
		System.out.println("-------------------------");
		Student s=new Student();
		System.out.println(s instanceof Student);//true
		System.out.println(s instanceof Person);//true
		System.out.println(s instanceof Object);//true
	//	System.out.println(s instanceof Teacher);//编译就报错!!
	//	System.out.println(p instanceof String);//编译就报错!!
	}
}

static

public class Student {
	private static int age;// 静态的变量
	private double score;// 非静态的常量
	public void run() {
		go();//可以调用静态方法
	}
	//静态方法
	public static void go() {
		
	}

	public static void main(String[] args) {
		Student s = new Student();

		System.out.println(s.age);
		System.out.println(s.score);
		System.out.println(Student.age);
		// System.out.println(Student.score); 报错 no static
		//run();不能调用
		s.run();//只能实例化Student 调用
		go();//直接调用
	}
}


//-------------------------------------------
public class Test {

/*	{		
		//代码块(匿名代码块)
	}
	static {
		//静态代码块
	}
	*/
	{
		System.out.println("匿名代码块");
	}
	static {
		System.out.println("静态代码块");
		//只执行一次
	}
	public Test() {
		System.out.println("构造方法");
	}
	public static void main(String[] args) {
		Test p=new Test();
		/*输出结构顺序
		 * 静态代码块
		匿名代码块
		构造方法*/
		System.out.println("---------------");
		Test p1=new Test();
		//匿名代码块
		//构造方法
	}
}


//-------------------------------------------


//加static不报错
//称为静态导入包
import static java.lang.Math.random;

//报错
//import  java.lang.Math.random
public class Test1 {
public static void main(String[] args) {
	//System.out.println(Math.random());
	System.out.println(random());//可以直接使用
}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值