我对多重继承中的概念感到困惑。 我有三个班级A,B和C.
Class A {
// ...
}
Class B extends A {
// ...
}
Class C extends B {
// ...
}
我知道这是多重继承的坏习惯,我也读过java允许通过接口进行多重继承。但我在上面的代码中没有收到任何错误。请不要使用界面,任何人都可以用一个明确的例子来解释我 谢谢!
答案 0 :(得分:2)
这不是多重继承。每个班级都有一个直接的超级班级。如果您的示例被视为多重继承,则根本无法使用extends
关键字,因为每个类默认都会扩展Object
类。
多重继承将是
class C extends A,B {}
这在Java中是非法的。
答案 1 :(得分:2)
您的代码不包含多重继承,实际上是合法的Java语法。多重继承是指类直接扩展两个超类的情况。例如:
public class MyClass extends MyFather, MyMother {
}
请注意,这当然是非法的Java语法。
答案 2 :(得分:2)
"多重继承"在Java中,基本上意味着继承多个接口,而不是继承多个实现。
现在,Java 8的一个新功能允许您通过接口和称为默认方法的方式执行实际实现的多重继承。我强烈建议您在尝试之前先掌握Java的基础知识。准备好后,here is a good tutorial on default methods。
答案 3 :(得分:1)
您上面编写的代码是多级继承的示例不是多重继承。
多重继承就像:
class A extends B,C {
//this code is not valid in JAVA
}
并且,如果您想使用接口来实现多继承等结构,那么您可以使用:
interface test_interface1{
/*all the methods declared here in this interface should be the part
** of the class which is implementing this current interface
*/
}
同样:
interface test_interface2{
}
因此,创建一个类TestClass,如:
class TestClass implements test_interface1,test_interface2 {
//now you have to use each and every method(s) declared in both the interfaces
// i.e. test_interface1 & test_interface2
}
您还可以使用以下语法:
class TestClass extends AnyClass implements test_interface1,test_interface2 {
/* but do keep in mind - use extends keyword before implements
** and now you know you cannot use more than 1 class names with extends keyword
** in java.
*/