接口和类对象之间的区别

时间:2014-04-09 12:40:40

标签: java class oop interface

我正在阅读Oracle文档,但我没有得到什么。

假设我有

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

这有什么区别:

a asd=new b();

和此:

b asf=new b();

4 个答案:

答案 0 :(得分:3)

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

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(); 

答案 1 :(得分:1)

假设我们有类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中定义的两种方法

答案 2 :(得分:0)

  1. 您无法实例化界面

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

  3. 假设您有这些类:

    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();
    

答案 3 :(得分:0)

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

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

相关问题