Can Class extend more than one Class how we do this

Can Class extend more than one Class

Answer: In Java multiple inheritance is not permitted. It was excluded from the language as a design decision, primarily to avoid circular dependencies.

Scenario 1: Following is not possible in Java:

package com.javahonk.multipleinheritence;

public class Whale extends Mammal, Animal{	

}

 

Scenario 2: However below is possible:

package com.javahonk.multipleinheritence;

public class Animal {
	void nurse() {
		System.out.println("Form Animal Class");
	}
}

 

package com.javahonk.multipleinheritence;

public class Mammal extends Animal{

	void nurse() {
	   System.out.println("Form Mammal Class");
	}
}

 

package com.javahonk.multipleinheritence;

public class Whale extends Mammal {

	public static void main(String[] args) {
		Whale whale = new Whale();
		whale.nurse();
	}

}

 

Basically the difference between above two approaches is that in the scenario 2 there is a clearly defined parent or super class, while in the scenario 1 the super class is ambiguous.

Think if as you see above both Animal and Mammal have a method nurse(). Under the first scenario which parent method would be called if we called Whale.nurse()? Under the second scenario, we know calling Whale.drink() would call the Mammal classes nurse method as long as Whale class had not overridden it.

Leave a Reply

Your email address will not be published. Required fields are marked *