java经典题目

java经典题目

1.输出下列结果:
package test1;

public class test5 {
public static void main(String[] args) {
	new Deviced();
}
}
class Base{
	private String name="base";
	public Base(){
		tell();
		print();
	}
	public void tell() {
		System.out.println("Base tell     "+name);
	}
	public void print() {
		System.out.println("Base print   "+name);
	}
}
class Deviced extends Base{
	private String name="devied";
	public Deviced() {
		// TODO Auto-generated constructor stub
	tell();
	print();
	}
	public void tell() {
		System.out.println("Deviced tell   "+name);
		
	}
	public void print() {
		System.out.println("Deviced print    "+name);
	}
}

答案:

Deviced tell null
Deviced print null
Deviced tell devied
Deviced print devied

分析:

1.创建子类对象的时候没有显示调用父类的构造函数,默认调用父类的 无参构造。

2.父类的无参构造中有tell和print方法,调用tell和print方法,此时的tell和print调用的是子类的tell和print方法,而由于name还未初始化,所以为null

3.调用子类构造方法:正常调用;

2.ArrayList在并发情况下会发生数组越界问题

数组下表越界:

假设有2个线程操作一个Arraylist,当thread1执行add后,假设此时容量只剩下一个,thread2还没开始,thread1认为ArrayList还有容量就睡去了,而thread2执行add()操作后size已满,thread1醒来后直接执行就会报错了。

3.父类的私有private成员可以被继承

父类的私有成员是可以被继承的,但是不能使用,就是只可以看不可以改动。

4.输出下列结果值
package test1;

public class test5 {
    private static String getA(){return "a";}
    public static void main(String[] args) {
        String a="a";
        String b="a"+"b";
        String c=getA()+"b";
        String e=a+"b";
        String compare="ab";
        System.out.println(b==compare);
        System.out.println(c==compare);
        System.out.println(e==compare);
        System.out.println(c==e);
        
    StringBuffer aBuffer=new StringBuffer();
    }
}
答案:true,false,false,false;

分析:b就是组合的ab,string 创建时会先去常量区查找是否有已经创建好的一样的对象,一样则把b指向它,故compaer和b地址相等

c 是一个get()和"b"相加,大家要切记,这个时候c是一个stringbuffer的变量,相当于new 了一个stringbuffer的对象放在了堆区,所以地址和compare不相等,可以取编译反编译看一下具体。

e和c一样都是变成了stringbuffer对象所以和compare不相等

注意:e和c是不想等的,stringbuffer就算一样也会重新开辟新的空间存储对象。

5.输出下列结果值:
class Person{
    public static void read(){
        System.out.println("The Person is reading books now.");
    }
}

class Student extends Person{
    public static void read() {
        System.out.println("The Student is reading books now.");
    }
}

public class Test2 {
    public static void main(String[] args) {
        Person p=(Student)null;
        p.read();
    }
}
答案:The Person is reading books now

分析:由于read是静态方法所以相当于直接可以通过类名区调用,此时person p就可以直接调用,当去掉方法上的static关键字时就会报错了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值