[英]Call some methods from interface without override all the methods in JAVA
[英]Cannot call some methods in interface after instantiating the objects in Java
如您所见,我有此代码示例。 但是当我尝试编译时,它在id.input
给出了错误提示, id.input
对象引用变量id
。 有人可以帮帮我吗?
interface IDisplay{
void print();
void printDetails();
}
interface IInput{
void input();
}
class Book implements IDisplay,IInput{
int bookID;
String title,publisher;
public void print(){
}
public void printDetails(){
}
public void input(){
}
}
class Student implements IDisplay,IInput{
int studentID;
public void print(){
}
public void printDetails(){
}
public void input(){
}
}
class A{
public static void main(String[] args) {
IDisplay id=new Student();
id.print();
id.printDetails();
id.input();
}
}
接口IDisplay
只有两个方法print
和printDetails
,方法input
位于接口IInput
。
在您的代码中,对象id
的类型为 IDisplay
(即使它持有对Student
对象的引用 ),因此您只能在接口IDisplay
上调用方法。
您必须将id
对象转换为Student
或IInput
才能调用input
法
((Student)id).input();
((IInput)id).input();
要么
id
为Student
类型。
但是,可以争辩说,前者违反了一些OO原则,因为IDisplay
必须仅是IDisplay
而IInput
必须仅是IInput
在编译阶段,编译器仅知道id
的引用类型为IDisplay
,不知道id
的运行时类型为Student
。
由于IDisplay
没有方法input
,因此出现编译错误。 要使其编译,可以将其显式转换:
((Student)id).input();
一个Student
实例将能够调用IInput
和IDisplay
方法的所有方法,但这取决于您如何操作它
因为您将if存储在IDisplay
,所以IInput
的方法不可见
解决方案:
投放到IInput
IDisplay id = new Student(); id.print(); id.printDetails(); ((IInput) id).input(); // or ((Student) id).input();
以Student
类型存储
Student id = new Student(); id.print(); id.printDetails(); id.input();
那是因为id
是IDisplay
类型而不是Student
类型。
IDisplay
没有方法input()
如果要从Student
调用方法,可以将其Student
为Student
:
((Student)id).input();
或强制转换为IInput:
((IInput)id).input();
或实例化为学生:
Student s = new Student();
s.input();
实例化IDisplay的对象(id)类型时,导致JVM将其强制转换为IDisplay类型的对象。
因此,尽管您使用了实现IDisplay和IInput的Student类的构造函数,但仅使用接口IDisplay的已实现方法实例化了它。
如果要使用对象ID访问IDisplay和IInput这两个接口的已实现方法,则应将代码修改为:
class A{
public static void main(String[] args) {
Student id = new Student();
id.print();
id.printDetails();
id.input();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.