multiple inheritance of state of same methods of class

gudii9
gudii9 used Ask the Experts™
on
Remember that Java does not allow a class inherits two or more classes directly. To understand why multiple inheritance is not allowed, consider the following example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class A {
    public void methodA() {
 
    }
 
    public void foo() {
 
    }
}
 
 
public class B {
    public void methodB() {
 
    }
 
    public void foo() {
 
    }
}
Suppose that we want to write a class C that extends both A and B like this:
1
2
3
4
5
public class C extends A, B {
    public void methodC() {
        foo();
    }
}
As you can see, both A and B has a method called foo(), so which foo() method the class C invokes exactly? from A or B? This case is ambiguous hence Java does not allow.

Open in new window


https://www.codejava.net/java-core/the-java-language/12-rules-and-examples-about-inheritance-in-java

i tried as below

package MultipleInheritance;
public class A {
    public void methodA() {
 
    }
 
    public void foo() {
 
    }
}


package MultipleInheritance;
public class B {
    public void methodB() {
 
    }
 
    public void foo() {
 
    }
}


package MultipleInheritance;
public class C extends A, B {
    public void methodC() {
        foo();
    }
}

Open in new window


on C class i get below error

Multiple markers at this line
      - Syntax error on token "extends", delete this token
      - Syntax error, insert "ClassBody" to complete
       ClassDeclaration
      - Syntax error, insert "}" to complete Block

can you please advise what above error means

it did not say "multiple inheritance of state not allowed"

Please advise
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Distinguished Expert 2018
Commented:
You cannot extend two classes, only interfaces.

This is not allowed in Java

public class C extends A, B 

Open in new window


because A and B are classes, not interfaces.
Top Expert 2016
Commented:
it did not say "multiple inheritance of state not allowed"

as the java language doesn't support multiple inheritance at all, the compiler was not able to detect that you tried to declare multiple inheritance by using a c++ like syntax.

instead, it detected that the valid token (keyword) 'extends' was followed by an invalid comma ','.

because of the syntax error, the class definition was incomplete and the compiler complains that the class C wasn't properly defined because there was no body and no termination.

Sara

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial