最近java考试,复习像是开天辟地,发现之前了解的还是太浅薄了。
1.首先来个基本的
class Animal{
Animal(){
System.out.println("Animal");
}
}
public class Dog extends Animal{
Dog(){
System.out.println("Dog");
}
public static void main(String arg[]){
Dog s = new Dog();
}
}
请问程序中的输出结果是:
解析:此处Dog继承了Animal,所以创建Dog的时候,是先运行父类Aniam的构造方法,再运行Dog的构造方法的。
2.理解上面的基本思想,我们再来看下面的
class First{
public First(){
aMethod();
}
public void aMethod(){
System.out.println("in First class");
}
}
public class Second extends First{
public Second() {
aMethod();
}
public void aMethod(){
System.out.println("in Second class");
}
public static void main(String args[])
{
new Second();
}
}
请问程序的输出结果是什么?
in First class
in Second class
应该是很多人的答案
正确答案是:
解析
3.继承下的变量
public class Father{
int a=100;
public void miner(){
a--;
}
public static void main(String[] args){
Father x = new Father();
Son y = new Son();
System.out.println(y.a);
System.out.println(y.getA());
y.miner();
y.plus();
System.out.println(y.a);
System.out.println(y.getA());
}
}
class Son extends Father{
int a = 0;
public void plus(){
a++;
}
public int getA() {
return super.a;
}
}
运行结果
解析
前面 0 100 好理解就跳过了
首先子类y 中有两个变量 一个是 y中重新定义的 a
一个是继承来的a (Father.a)
然后程序运行到 y.miner();
该函数选择了 子类中的Father.a 进行减操作
y.plus()
子类中 有plus 所以就选择了子类的 a=0 的++
结果为1