[英]When I create an object from a class that extends a specific interface, can I use this object in the place where I use this interface?
I know that I can pass an interface
as an argument.我知道我可以将
interface
作为参数传递。 Since we cannot create an object from an interface
!因为我们不能从
interface
创建 object ! Can I create an object from a class
that extends
this interface
then I use this object in the place where I use this interface
as an argument?我可以从
extends
这个interface
的class
创建一个 object 然后我在我使用这个interface
作为参数的地方使用这个 object 吗?
My question, since obj
is an object from Final
class, can I use it as a parameter here ( m1(obj)
)?我的问题是,由于
obj
是来自Final
class 的 object,我可以在此处将其用作参数( m1(obj)
)吗? And explain to me why, please?请向我解释为什么?
package aaa;
public class AAA {
public static void m1(One one) {
System.out.print("AAA");
}
public static void main(String[] args) {
Final obj = new Final();
m1(obj);
}
}
interface One {
}
class Final implements One {
}
Yes, you can do that.是的,你可以这样做。 Interfaces are a way in Java to avoid multiple inheritance, ie declaring a class
Foo
to extend a class Bar
and implement an interface Bar
means that we have a "is a" relationship between Foo
and Bar
/ Baz
.接口是 Java 中避免多个 inheritance 的一种方式,即声明 class
Foo
以扩展 class Bar
并实现接口Bar
意味着我们在Foo
和Bar
/ Baz
之间具有“是”关系。 So, " Foo
is a Bar
" and " Foo
is a Baz
" are true or in your case Final
is a One
.因此,“
Foo
is a Bar
”和“ Foo
is a Baz
”是真实的,或者在您的情况下Final
是One
。 So, if a type is a subtype (or in Java implements an interface) the subtype can be used in place of the type or the interface (see the Liskov substitution principle).因此,如果类型是子类型(或在 Java 中实现接口),则可以使用子类型代替类型或接口(参见 Liskov 替换原则)。
When you declare a method m1(One one)
, you require the first parameter to be of type One
and as Final
is a One
this is obviously true.当你声明一个方法
m1(One one)
时,你需要第一个参数是One
类型,因为Final
是One
,这显然是正确的。
Please note, that even though you pass in an object of type Final
the method only "sees" the interface part of the object without casting it.请注意,即使您传入
Final
类型的 object,该方法也只能“看到”object 的接口部分,而不会强制转换它。
I know that I can pass an interface
as an argument.我知道我可以将
interface
作为参数传递。 Since we cannot create an object from an interface
!由于我们无法从
interface
创建 object ! Can I create an object from a class
that extends
this interface
then I use this object in the place where I use this interface
as an argument?我可以从
extends
此interface
的class
创建 object,然后在我使用此interface
作为参数的地方使用此 object 吗?
My question, since obj
is an object from Final
class, can I use it as a parameter here ( m1(obj)
)?我的问题,由于
obj
是来自Final
class 的 object,我可以在这里将它用作参数( m1(obj)
)吗? And explain to me why, please?请给我解释一下为什么?
package aaa;
public class AAA {
public static void m1(One one) {
System.out.print("AAA");
}
public static void main(String[] args) {
Final obj = new Final();
m1(obj);
}
}
interface One {
}
class Final implements One {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.