【问题标题】:Difference between interface and class objects [duplicate]接口和类对象之间的区别[重复]
【发布时间】:2014-04-09 12:40:40
【问题描述】:

我正在阅读 Oracle 文档,但没有得到任何信息。

假设我有

public interface a {
    //some methods
}
public class b implements a {
    //some methods
}

这有什么区别:

a asd=new b();

还有这个:

b asf=new b();

【问题讨论】:

标签: java class oop interface


【解决方案1】:

没有这样的事情。至少不会编译。

a asd=new a(); // you can't instantiate an interface

b asf=new a(); // you can't instantiate an interface

您可以执行以下操作。

b asd=new b();  

a asd=new b(); 

【讨论】:

  • 我的意思是b,对不起。
【解决方案2】:

假设我们有类 b 和接口 a:

public interface a{
  void foo();
}
public class b implements a{
  @Override
  void foo(){}
  void bar(){}
}

然后我们创建两个实例:

a asd=new b();
b asf=new b();

现在asd是“a”的实例,因此它只能访问接口a中声明的方法(在本例中为方法foo

另一方面,asfb 的实例,因此它可以访问类b 中定义的两种方法

【讨论】:

    【解决方案3】:

    a asd = new b() -- 可以在运行时解析

    b bsd = new b() -- 可以在编译时解析。

    【讨论】:

      【解决方案4】:
      1. 你不能实例化接口

      2. 如果我们假设你的意思是父类,在第一种情况下你不能访问类 b 的方法

      假设你有这些类:

      public class a {
      //some methods
      }
      public class b extends a {
      //some methods
          type method1(args) {...}
      }
      

      两者有什么区别?

      a asd=new b(); // you cannot call method1 using asd
      

      b asf=new b();
      

      【讨论】:

        猜你喜欢
        • 2011-04-07
        • 2013-03-29
        • 1970-01-01
        • 2011-12-28
        • 1970-01-01
        • 2014-05-16
        • 1970-01-01
        • 2011-12-26
        • 2015-12-16
        相关资源
        最近更新 更多