起因当然是因为在面试中遇到不知道怎么搞定啦,然后看了几遍讲解视频也还是不懂。然后不得已自己写了个例子(见最后)。
一、基本知识点
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