关于static关键字的使用(多与类的继承一起考察)

起因当然是因为在面试中遇到不知道怎么搞定啦,然后看了几遍讲解视频也还是不懂。然后不得已自己写了个例子(见最后)。

一、基本知识点

1、static的应用

类中,static修饰成员变量:既可以用类名调用,此时无需生产对象,也可以用对象名调用;所有的对象使用的静态变量是同一份;

类中,static修饰成员函数:既可以用类名调用此时无需生产对象,也可以用对象名调用;静态函数里面不能够调用非静态变量

类中,静态代码块:静态代码块在装载类的时候执行(装载--构造--执行),只执行了一次


2、继承

A、只能继承一个类,就是只能有一个父类

B、继承是为了减少重复代码


父类:

public class Father {
	String name;
	public Father() {
		// TODO Auto-generated constructor stub
		System.out.println("I am father");
	}
	
	static {
		System.out.println("我是father的static");
	}

	public void say(){
		System.out.println("我是father的say"+name);
	}
}
子类:
public class Child extends Father {
	 String childname;
	
	
	public Child(String name){
		super();
		System.out.println("I am a child, name is"+name);
	}
	
	static {
		System.out.println("我是child的static");
	}
	
	public void say(){
		System.out.println("我是child的say"+childname);
	}
}
Test类用于运行结果
public class Test {
	public static void main(String[] args){
		Father father1=new Child("AAAAA");//向上转变
		father1.name="AAAAAA";
		father1.say();
		
		System.out.println("我是-------1");
		
		Child childer1=new Child("BBBBB");
		childer1.childname="BBBBBBBB";
		childer1.say();
		
		System.out.println("我是-------2");
		
		Father father2=new Father();
		father2.name="CCCCCC";
		father2.say();
		
	}

}
运行结果:
我是father的static
我是child的static
I am father
I am a child, name isAAAAA
我是child的saynull
我是-------1
I am father
I am a child, name isBBBBB
我是child的sayBBBBBBBB
我是-------2
I am father
我是father的sayCCCCCC



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值