java接口编程题_java内部类面试题接口编程题

1、内部类的形式是怎样的?

⒈静态内部类

⒉成员内部类

⒊局部内部类

⒋匿名内部类

2、为什么要有“内部类”?

1、内部类提供了更好的封装。只能让外部类直接访问,不允许同一个包中的其他类直接访问。

2、内部类可以直接访问外部类的私有属性,内部类被当成其外部类成员。但外部类不能访问内部类的内部属性。

3、利用内部类可以方便实现哪些功能?

可以不受限制的访问外部类的域和方法。

4、内部类的实现机制?

5、内部类可以引用它的包含类(外部类)的成员吗?有没有什么限制?

可以,限制,如果是静态内部类,不能访问外部类的非静态成员。

编程题:

1.定义一个乐器(Instrument)接口,其中有抽象方法

void play();

在InstrumentTest类中,定义一个方法

void playInstrument(Instrument ins);

并在该类的main方法中调用该方法。

要求:分别使用下列内部类完成此题。

成员内部类

局部内部类

匿名类

//使用成员内部类实现

package xianweifu;

interface Instrument{

public abstract void play();

}

class InstrumentTest{

class Inner1 implements Instrument{

public void play(){

System.out.println("演奏钢琴");

}

}

public void playInstrument(Instrument ins){

ins.play();

}

}

public class demo8 {

public static void main(String[] args) {

InstrumentTest test = new InstrumentTest();//创建外部类对象

InstrumentTest.Inner1 inner= test.new Inner1();//创建内部类对象

test.playInstrument(inner);

}

}//使用局部内部类实现

package xianweifu;

interface Instrument{

public abstract void play();

}

class InstrumentTest{

public void tell(){

class Piano implements Instrument{

public void play() {

System.out.println("演奏钢琴");

}

}

Instrument piano = new Piano();

piano.play();

}

public void playInstrument(Instrument ins){

ins.play();

}

}

public class demo8 {

public static void main(String[] args) {

InstrumentTest test = new InstrumentTest();//创建类对象

test.tell();

}

}//使用匿名内部类实现

package xianweifu;

interface Instrument{

public abstract void play();

}

class InstrumentTest{

public void playInstrument(Instrument ins){

ins.play();

}

}

public class demo8 {

public static void main(String[] args) {

InstrumentTest test = new InstrumentTest();//创建类对象

test.playInstrument(new Instrument(){

public void play(){

System.out.println("弹奏钢琴");

}

});

}

}2、定义一个Father和Child类,并进行测试。

要求如下:

1)Father类为外部类,类中定义一个私有的String类型的属性name,name的值为“zhangjun”。 2)Child类为Father类的内部类,其中定义一个introFather()方法,方法中调用Father类的name属性。

3)定义一个测试类Test,在Test类的main()方法中,创建Child对象,并调用introFather ()方法。

package xianweifu;

class Father {

private String name = "zhangjun";

class Child {

public void introFather() {

System.out.println("father's name:" + name);

}

}

}

public class demo8 {

public static void main(String[] args) {

Father child = new Father();

Father.Child test = child.new Child();

test.introFather();

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值