内部类向上转型为接口

内部类向上转型为接口


public interface Destination {
    String readLable();
}
public interface Contents {
    int value();
}
public class Parcel {
    //普通的(非内部类),不能声明为private或protected,只能被赋予public或包访问权限
    private class PContents implements Contents{//私有,除了Parcel没有人能访问
        private int i = 11;
        @Override
        public int value() {
            return i;
        }

    }

   //protected 只有parcel及其子类,同一包中的类才能访问
   protected class PDestination implements Destination{
    private String lable;

    private  PDestination(String whereto) {
        lable = whereto;
    }

    @Override
    public String readLable() { return lable; }

   }    

   public Destination dest(String s){
    return new PDestination(s);
   }

   public Contents cont(){
    return new PContents();
   }


}
/**
 * 1.内部类向上转型为接口可以完全隐藏内部类的具体实现过程
 *
 * 2.可以定义多个内部类 以不同的方式实现接口中的同一个方法
 * 
 * 3.这种技巧经常被应用在swing编程中,可以在一个类中做出不同的响应事件。
 * @author jack
 *
 */

public class ParcelTest {

    public static void main(String[] args) {
        Parcel p = new Parcel();

        Contents c = p.cont();//upcasting 内部类向上转型为接口
        System.out.println(c.value());

        Destination d = p.dest("Shanghai");
        System.out.println(d.readLable());

        //PDestination pd = 
        //Parcel.PCcontents pc = p.new PContents();PContents是私有的,不能被创建
    }

}
很高兴回答你的问题!这是一个非常好的Java编程问题。 首先,创建私有内部类的语法如下: ``` class OuterClass { private class InnerClass implements PublicInterface { // Inner class implementation } public PublicInterface createObject() { return new InnerClass(); } } ``` 然后,我们可以在外部中使用 `createObject()` 方法来获取对私有内部类的引用。由于 `InnerClass` 是私有的,它不能在外部之外直接访问,因此需要通过公共接口向上转型。 下面是示例代码: ``` public interface PublicInterface { // Interface methods } class OuterClass { private class InnerClass implements PublicInterface { public void innerMethod() { System.out.println("Inner class method called"); } } public PublicInterface createObject() { return new InnerClass(); } } public class Main { public static void main(String[] args) { OuterClass outer = new OuterClass(); PublicInterface obj = outer.createObject(); // Upcasting done here // Try to downcast to InnerClass // This will fail at runtime as InnerClass is completely hidden InnerClass inner = (InnerClass) obj; // This line will cause the program to throw a ClassCastException } } ``` 我们在 `Main` 中尝试向下转型 `PublicInterface` 对象为 `InnerClass`,但是由于 `InnerClass` 完全被隐藏了,所以会在运行时抛出 `ClassCastException` 异常。 另外,当你问我前面对你说了什么时,我想给你讲一个笑话: 有两个人在大街上说话,其中一个明显在向另一个炫耀自己的声音有多响。忽然,一个路过的母牛猛然大叫,你猜谁响声更大?答案是母牛,因为它没有说话,只是自然地发出了声音。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值