java基础面试题
面试题1
public class Test {
public static void main(String[] args) {
Parent p = new Child();
System.out.println("Parent:" + p.getAge()); //40
System.out.println("Parent:" + p.age); //18
Child c = new Child();
System.out.println("Child:" + c.getAge()); //40
System.out.println("Child:" + c.age); //40
}
}
class Child extends Parent {
public Integer age = 40;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
class Parent {
public Integer age = 18;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
输出结果
Parent:40
Parent:18
Child:40
Child:40
原因:
- 属性属于实例自己的**,所以Parent的age属性值是18,这就解释通了
- 属性不存在覆盖(即使同名),而方法是实实在在的覆盖(复写)
当父类调用getAge()方法时会调用子类的方法
面试题2
public class Test {
public static void main(String[] args) {
Parent p= new Child();
System.out.println(p.age);
System.out.println("---------");
Child c= new Child();
System.out.println(c.age);
}
}
class Child extends Parent {
Integer age=5;
static {
System.out.println("Child的静态块");
}
{
System.out.println("Child的构造块age="+age);
}
Child() {
System.out.println("Child的构造方法age="+age);
}
public Integer getAge() {
return age;
}
}
class Parent {
public static Integer sex=20;
Integer age = 18;
static {
System.out.println("Parent的静态块sex="+sex);
}
{
System.out.println("Parent的构造块age="+age);
}
Parent() {
System.out.println("Parent的构造方法age="+age);
}
public Integer getAge() {
return age;
}
}
输出
Parent的静态块sex=20
Child的静态块
Parent的构造块age=18
Parent的构造方法age=18
Child的构造块age=5
Child的构造方法age=5
18
---------
Parent的构造块age=18
Parent的构造方法age=18
Child的构造块age=5
Child的构造方法age=5
5
类的生命周期是:加载->验证->准备->解析->初始化->使用->卸载。
类的准备阶段`:需要做是为类变量(static变量)分配内存并设置`默认值
需要注意的是,如果类变量是final的,编译时javac就会为它赋上值
1、静态变量设置默认值
static byte b=(byte)0;
static short s=(short)0;
static int i=0;
static long l=0;
static char c='\u0000' 0; //代表空格
static boolean bol=false;
static float f=0f;
static double d=0d;
2、静态变量赋值
3、静态代码块
4、成员变量设置默认值
5、成员变量赋值
6、父类构造代码块
7、父类构造函数
8、构造代码块
9、构造函数
面试题3
public class StaticTest {
public static void main(String[] args) {
staticFunction();
}
// 静态变量(有实例化的过程,这就是本题的重点)
static StaticTest st = new StaticTest();
static {
//System.out.println(b); // 编译报错:因为b在构造代码块后边,此处不能引用。因此Java代码是从上到下的顺序
System.out.println("1");
}
{
System.out.println("2");
}
StaticTest() {
System.out.println("3");
System.out.println("a=" + a + ",b=" + b);
}
public static void staticFunction() {
System.out.println("4");
}
// 这两个变量写在最后面
int a = 110;
static int b = 112;
}
结果
2
3
a=110,b=0
1
4