[英]can we define abstract class inside the interface in java?
I am new to this concept, i know the property of interface and abstract.我是这个概念的新手,我知道接口和抽象的属性。 when i explain the concept to my friends, they asked me to create abstract class inside the interface.
当我向我的朋友解释这个概念时,他们要求我在接口内部创建抽象类。
please tell me, is it possible to create abstract class inside the interface.请告诉我,是否可以在接口内创建抽象类。 i googled, but i am not able find the exact answer for my question.
我用谷歌搜索,但找不到我的问题的确切答案。
i tried the below code,but i dont know how to cal the AbstractMethod.我尝试了下面的代码,但我不知道如何调用 AbstractMethod。
interface Student {
public abstract class Subject {
public void AbstractMethod(){
System.out.println("hi");
}
}
}
class Data implements Student {
public void ClassMethod() {
System.out.println("method 2");
}
}
public class NewClass {
public static void main(String[] args) {
Data s=new Data();
Student.Subject obj=new Student.Subject();// compiler error
s.ClassMethod();
}
}
Wouldn't something like this be better?这样的事情不是更好吗?
interface Student {
public abstract void sayHi();
}
class Data implements Student {
@Override
public void sayHi() {
System.out.println("method 2");
}
}
Yes, you can.是的你可以。 Here in the below example, I used Anonymous Class but you can use Lambda Expression also
在下面的示例中,我使用了匿名类,但您也可以使用 Lambda 表达式
interface Student {
public abstract class Subject {
public abstract void AbstractMethod();
public void show(){
System.out.println("Show Method");
}
}
}
class Data implements Student {
public void ClassMethod() {
System.out.println("method 2");
}
}
public class NewClass {
public static void main(String[] args) {
Data s=new Data();
Student.Subject obj=new Student.Subject(){
public void AbstractMethod(){
System.out.println("hi");
}
};
obj.show();
obj.AbstractMethod();
s.ClassMethod();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.