Java multiple inheritance issue - java

I have a question like this :
Think a scenario like this
public class Animal {
protected String Name;
Boolean canWork;
}
public class Dog {
Enum TailType
}
And I need to have both of this classes attributes in a class of the third level which extends the both classes .. but using interfaces I don't think this can be achieved. Is it possible to do this using a design pattern or some else method ?
Summary : I want to have attributes from two classes to a concrete class

You can have Dog extend Animal, then extend Dog by the third class, but unless your 3rd class is Poodle then you may have a problem you don't realize yet. That being inheritance is only appropriate when the relationship is a modeling criteria, and extending objects only to get their functionality is the wrong approach. Inheritance should follow the IS-A principle. That being your subclass IS-A base class in modeling terms. If it doesn't pass that test you are using inheritance when you shouldn't. After all you can use delegation to obtain their functionality. That meaning:
public class SomeClass {
private Dog dog;
public void bark() {
dog.bark(); // this is reusing the functionality without extending
}
}
Now SomeClass can call or invoke methods on Dog without extending it. Now the downside to this is a reference to Dog can't point to SomeClass, but if SomeClass is-not-a Dog that's probably good. However, if you have to allow Dog and SomeClass to share some typing so you can have a reference that points at either Dog or SomeClass then you can create an interface that both share:
public class SomeClass implements Barkable {
private Dog dog;
#Override
public void bark() {
dog.bark();
}
}
public class Dog implements Barkable {
#Override
public void bark() {
System.out.println( "Bark! Bark!" );
}
}
With delegation/composition and interfaces you DON'T need multiple inheritance. It's a really simple technique to apply and master and you'll build systems that are much more flexible than relying on inheritance alone.

if you are trying to have just attributes, I think you can use interfaces like:
interface A{
int a = 0;
}
interface B{
int b = 1;
}
class implements A, B{
//can access A.a and B.b
}
But this is not a good approach, interfaces are meant for contracts not just to contain constants (variables in interface are static and final by default)

For good reasons modern OO languages like Java and C# do not support multiple inheritance.
The replacement to use in most cases is the interface:
public Interface NameAndWorkable {
setName(String name)
String getName();
boolean canWork();
setCanWork(boolean canWork);
}
public Interface TailAnimal {
TailtypeEnum getTailType();
setTailType(TailtypeEnum tailtype);
}
public class Animal implements NameAndWorkable {
private String name;
private boolean canWork;
public setName(String name)
public String getName();
public boolean canWork();
public setCanWork(boolean canWork);
}
public class Dog implements TailAnimal {
private TailTypeEnum tailType;
public TailtypeEnum getTailType();
public setTailType(TailtypeEnum tailtype);
}
and now the third object with fullfills both Interfaces
public class WorkingNamedDog implements NameAndWorkable, TailAnimal {
private String name;
private boolean canWork;
private TailTypeEnum tailType;
// from NameAndWorkable
public setName(String name)
public String getName();
public boolean canWork();
public setCanWork(boolean canWork);
// from TailAnimal
public TailtypeEnum getTailType();
public setTailType(TailtypeEnum tailtype);
}

To achieve multiple inheritance, it is necessary to use Interfaces. You can either use inheritance by extending these classes on one another like:
//Your first class
public abstract class Animal{
//It is upto you to use an abstract method inside it. However it is not necessary to do so!
//define an abstract method inside an abstract class.
}
//Your second class
public class Dog extends Animal{
}
//Your third class
public class ThirdClass extends Dog{
//here you can instantiate Dog
private Dog dogObject = new Dog();
public void anyMethod(){
dogObject.anyMethodsThatAreDefinedInClassDogAndAnimal();
}
}
Hope this helps!!

You can extend one class and have another class as composition like this:
public class MyClass extends Dog {
private Animal animal; // instance of Animal class
// rest of the code to expose Animal class's attributes as per your need
}

Dog should be a subclass of Animal. Then your third class would be a subclass of Dog. This third class would have the attributes of Dog and Animal.
If Dog is not a subclass of Animal then you would need multiple inheritance to achieve what you want. Since Java does not support multiple inheritance you have to make Dog a subclass of Animal.
Or in case, your two classes are not in same inheritance hierarchy, then you have two options: -
Either make them interfaces, and then you can implement both the interfaces.
Or, use Composition instead of Inheritance, in which case, you would need to have the references to both the classes - Animal and Dog, as attribute in your class.
E.g: -
public class YourClass {
Animal animal;
Dog dog;
}
However, it doesn't make sense to have Animal and Dog class, with Dog not being a subclass of Animal. So, you should change that first, and then you would be able to use inheritance.

Related

The purpose of this Java code - Object Creation

I would like to understand the following code. Is there a name for creating an object with two classes? I assumed I would create a Deer object that can call methods/variables from the Animal class but it does not seem to be working. Why would someone want to create an object like this in Java?
public class Animal {
int J = 20;
}
public class Deer extends Animal {
int Q = 40;
}
public void test() {
Animal D = new Deer();
}
This is called inheritance, which is extremely useful when you're doing anything OOP-related in Java.
You currently don't even have any methods in either class so you can't test how methods would work right now. However, if you added a method in the animal class (e.g. public void talk() {}), you could call that method in the Deer class using super.talk().
As a side note, if you're declaring a class as public, it needs to be in its own separate file or you'll get a compiler error. If you want everything to be in one file, just take out the word public.
You can visit https://www.w3schools.com/java/java_inheritance.asp for more information on inheritance and classes.
First of all I found the question description is too short. So try correcting it.
This type of class creation is part of something called as inheritance it helps when
we don't want to provide access of the function of a subclass.(So our base class act as a wrapper.)
To override the function of baseclass. So that when baseclass function is called, it behaves as if the subclass function has been called.
lets take example
public class MyClass {
public static void main(String args[]) {
Animal D = new Deer();
System.out.println(D.getType());
}
public static class Animal{
String Type="Animal";
public String getType(){
return Type;
}
}
public static class Deer extends Animal{
String SubType="Mammal";
public String getType(){
return SubType;
}
public String eatgrass(){
return "eatgrass";
}
}
public static class Bird extends Animal{
String SubType="bird";
public String getType(){
return SubType;
}
public String fly(){
return "flying";
}
}
}
In the above example.
We can see that not all animals eatgrass, so we would like to hide that detail and only use the function that are common to all animal objects, Here in this case its getType()
We want the D.getType() to return the closest type of class name of deer in animal chart which is "mammal". So when we call D.getType() instead of getting "Animal" as what you would be expecting looking at the code, we will be getting "Mammal"
This can be helpful when you need to re-use code and get information from both classes, For example, class ANIMAL and subclasses Dog, Cat, Monkey, and so on.
In the end, all of them are animals with similar methods like eating, run, sleep but in a deeper way each one of them has unique behaviors, the cat can eat but it also can meow, the Dog can run but it also can bark.
so they have unique and similar actions to perform.
inheritance is a good way to re-use an existing code from the parent class.
you can check inheritance docs.
Inheritance

Marker Interface vs Enums

I am trying model a zoo.
Suppose I have the following structure for areas in the Zoo(omitted some details)
public abstract class AnimalHabitat{
private ArrayList<Animal> animals = new ArrayList<>();
public void setAnimal(Animal animal) {
animals.add(animal)
}
}
public class Enclosure extends AnimalHabitat{}
public class Aquarium extends AnimalHabitat{}
public class Cage extends AnimalHabitat{}
Then I have the following structure for animals
public abstract class Animal{}
public class Lion extends Animal{}
public class Zebra extends Animal{}
public class Shark extends Animal{}
public class Starfish extends Animal{}
public class Parrot extends Animal{}
public class Eagle extends Animal{}
I want to add an animal to its corresponding appropriate habitat. To simplify code I was thinking to use either a marker interface, such as
public interface TerrestrialAnimal{}
public class Lion extends Animal implements TerrestrialAnimal{}
public class Zebra extends Animal implements TerrestrialAnimal{}
and then I will be able to do
public class Zoo{
public boolean addAnimal(AnimalHabitat habitat, Animal animal) {
if (animal instanceOf TerrestrialAnimal && habitat instanceOf Enclosure) {
habitat.set(animal);
return true;
}
if (animal instanceOf AquaticAnimal && habitat instance of Aquarium) {
habitat.set(animal);
return true;
}
// So for aerial
}
}
However an alternative is to use enums. For example suppose I have
public enum AnimalType{
Terrestrial, Aquatic, Aerial;
//getter
}
Then in the Animal abstract class I can define
public abstract class Animal{
private AnimalType type;
// Initialise in the constructor depending on the animal instance
}
And I will do the same in the addAnimal() method in Zoo.
What are the pros and cons of each approach? Thanks!
I would use enums. You don't need all of those if statements.
Just have the attribute type in both Animal and AnimalHabitat and then compare them.
if (animal.getType() == habital.getType()) { // can add to habitat
Switch to interfaces if you want to add some methods to the interface specific to the animal type.
Enum
pros:
Easy to scale: You can easily add value
More coincise: You have one single file to define all AnimalType
More readable: definitely readable
More Flexible: You can define method on Enum and you can print AnimalType using enum value
Comparable: You can do simple compare instead of using instanceof
with enums approach i doesn't find any cons.
Interface
pros
Methods: You can define common methods signatures
You can use 2 interfaces in same Animal (may an animal have more habitat? Or more types?)
you can use interface as supertype in collections/class variable
cons
Expensive: definitely expensive, one interface for each type
In your example i prefer Enums because you are using interfaces to define animal types and it can be done easily using Enums. Use interfaces if you need to define common method signatures or you want to use Interfaces as supertype as follow:
List<TerrestrialAnimal> terrestrialAnimal = new ArrayList<>(); it can contains all terrestiral animal.

Java Chain Inheritance with Lombok and Guice Injections

EDIT: This question really should be around Lombok and Guice instead of vanilla java inheritance.
I'm trying to implement a Java inheritance chain with Lombok and Guice injections, it works something like this:
Class 1
public abstract class Animal {
#NonNull protected String attr1;
protected abstract void method1();
void method0() {
// Some code that uses attr1
}
}
Class 2
public abstract class Mammal extends Animal {
#NonNull protected String attr2;
protected abstract void method2();
#Override
void method1() {
// some logic that uses attr2
method2();
}
}
Class 3
public class Wolf extends Mammal {
#Inject #NonNull private String attr1;
#Inject #NonNull private String attr2;
#Inject #NonNull private String attr3;
#Override
void method2() {
// some logic
}
}
Out there in the main program I have code that calls wolf.method1(). The problem here is that only wolf has all the attributes needed (due to Guice injections), whereas all the fields in Animal are undefined. I suspect I can probably do it in Vanilla Java, but things are going to get super messy (I have 6 attributes in Animal class and 5 more in Mammal). Is there a way to mix-and-match lombok's annotations (#NoArgsConstructor, #AllArgsConstructor, etc) to make this work?
Thanks.
Your abstract classes cannot be directly instantiated even if you add public constructors, because they are declared abstract. If you prefer, you can make the constructors protected to indicate they are only available to subclasses.
right that abstract classes can't really be instantiated, but why didn't the Java compiler catch this and stop complaining about not having a constructor?
Any class you write without an explicit constructor has an implicit no-args constructor. Any implicit no-args constructor implicitly calls its superclass's no-args constructor, even if that superclass is abstract. So if some class up the chain doesn't have a no-args constructor (because you explicitly gave it another constructor), then you code won't compile.
In the code you gave in your question, there are no explicit constructors, so every class does have an implicit no-args constructor. In your actual code, presumably you have written a constructor somewhere, which is why the implicit no-args constructor has not been added.
I propose:
use only interfaces for the entire hierarchy.
decouple behaviors and encapsulate them in separate classes.
use composition instead of inheritance, i.e. private SomeBehavior someBehavior; for every specific animal that needs it.
It will make your design better and solve the problem as well.
i.e.
public interface Mammals {
}
public interface Animal extends Mammals {
}
public interface Dog extends Animal {
}
and
public class TakeADump {
public void dump() {
}
}
public class TakeAPee {
public void pee() {
}
}
and then
public class Sheperd implements Dog {
private TakeADump dumpService;
private TakeApee peeService;
}
And now your dog can s... and p... :)
Also add
public class F... {
public void f...(<Animal> animal) {
// ... check it's an instance of the same or compatible animal or throw UnsupportedOperationException() if it's incompatible
}
}
:D
Of course it will make sense to create an abstract Animal.
i.e.
public class AbstractAnimal {
private TakeADump dumpService;
private TakeApee peeService;
private F... f...Service;
}
then
public abstract class AbstractDog extends AbstractAnimal implements Dog {
}
and
public class Sheperd extends AbstractDog {
public void lookAfterSheep() {
Sheep sheep = SheepLocator.findNearest();
// pee on a sheep
peeService.pee(sheep);
// dump on a sheep
dumpService.dump(sheep);
// f... a sheep
f...Service.mount(sheep);
}
}
So your mistake is using too much abstract when you can use interfaces.
When you are implementing concept of inheritance with some argument constructor it is good practice to have one default (no argument) constructor defined there. Because while creating object of child class compiler internally will call constructor of parent class.
e.g
class ABC {
}
class XYZ implements ABC{
}
public class Test{
XYZ obj= new XYZ() // this will internally call default constructor of XYZ and
//in that first statement will super()--> this will call default constructor of class ABC
}
if anyhow you have implemented argument constructor in parent class then compiler will not implement default constructor implicitly we need to define it explicit to make call to super constructor from child constructor. Or do a explicit call to argument constructor from child constructor.

Hide non mutual methods in superclass facade

Is there a way we can hide the non mutual methods for types which are not qualified for the specific methods?
Lets say we have an abstract superclass with methods we don't want to expose to the objects themselves. We create a facade with the methods we want to allow for the objects. (We dont want to be able to set a cats age to 32 out of the blue.)
I end up in a scenario where i expose methods for a specific subclass that was actually meant for another subclass. (Even if we in the method can controll that the type is correct)
Scenario:
public abstract class Animal {
//setters and code we want to protect
}
public class Cat extends Animal{
private boolean giveBirth;
public void giveBirth(){giveBirth = true;}
//setters etc
}
public class Bird extends Animal{
private boolean layEgg;
public void layEgg(){layEgg = true;}
//setters etc
}
public class FacadeAnimal {
Animal animal;
public FacadeAnimal(Animal a){
animal = a;
}
public void layEgg(){
if(animal instanceof Bird){
((Bird) animal).layEgg();
}
}
public void giveBirth(){
if(animal instanceof Cat){
((Cat) animal).giveBirth();
}
}
}
So in this case we can control inside the method that the type needs to be Bird if we want to layEgg. But it would also be okay for us to let a Cat layEgg. Even though the logic is taken care of, it's still not very intuitional to give Cat the option to lay eggs.
I was thinking it's possible to create an "facade inheritance structure", where we for every subclass also create a facade for that specific subclass. But in the terms of extensibility, that means we will force future developers to not only create a subclass, but also an implementation of it's facade.
Is this the way to go or can we change the way we wrap this around?
Cheers!
EDIT: Maybe the animalscenario was not very clear.
It could in the same manner be two different cars, where one has turbo and one has not, if the "activateTurbo" method exists in the facade, i would be able to call the activateTurbo method on a car that does not actually have a turbo.
Method names such as giveBirth() and layEgg() are too specific - consider something more common such as:
public abstract class Animal {
public void reproduce();
}
Then each subclass can implement as needed. For examle:
public class Cat extends Animal {
public void reproduce() {
liveBirth();
}
private void liveBirth() {
// ...
}
}
and
public class Bird extends Animal {
public void reproduce() {
layEgg();
}
private void layEgg() {
// ...
}
}
This approach will likely lead to at least some duplicate code in the private methods. As #Lini said, combine with the strategy pattern. A little refactoring, and it changes from inheritance to composition.
I would unify giveBirth() and layEgg() into one single method in Animal, the subclass decides itself what to do.
You can also encapsulate this behavior into a new class something like NextGenerationStrategy with subclasses LayEggStrategy or GiveBirthStrategy.
The subclass of Animal (Bird or Cat) selects itself the strategy. So when you work with Animal you dont care it lays egg or gives birth.

Abstract method implementation (if unused)

For instance, I have an abstract class implemented like this:
public abstract class Animal
{
public abstract void makeNoise();
}
and I have a child class which is representing an animal that does not make any noise. Which is better?
public class Turtle extends Animal
{
// properties and methods
public void makeNoise()
{
//leave it empty
}
}
or should i simply make it : public abstract void makeNoise(); inside Turtle?
It is better to move the makeNoise() method out of Animal as all the animals doesnot make noise. So create another interface NoiseMaker and add the the makeNoise method inside that.
public abstract class Animal {
// animals methods
}
public interface NoiseMaker {
void makeNoise();
}
public class Turtle extends Animal {
// properties and methods which are applicable for turtle
}
And when you want an animal which makes noise like Lion you can extend Animal class and implement NoiseMaker, so that it has the behaviour of Animal as well as it makes noise.
public class Lion extends Animal implements NoiseMaker {
public void makeNoise() {
// implementation
}
// other properties and methods which are applicable for turtle
}
What people often do: throw some sort of exception, like UnsupportedOperationException or something alike.
But: in the end your are fixing a symptom here.
The point is: extending a base class means that an object of the derived class IS-A object of the base class as well. And you are asking: how to violate the public contract of the base class.
And the answer is: you should not do that. Plain and simple.
Because if you start throwing exceptions here, all of a sudden, a caller that maybe has List<Animal> animals can't simply invoke makeNoise() on each object. The caller has instead to use instanceof (so that he can avoid calling makeNoise() on specific classes) - or try/catch is required.
So the real answer is: step back and improve your model. Make sure that all methods on the base class make sense for derived classes. If not - maybe introduce another layer, like abstract class NoisyAnimal extends Animal.
This is the best use case to use UnsupportedOperationException
You have to implement because of the abstract design. So just implement the method and throw UnsupportedOperationException exception.
Keep it Animal, cause most of the Animal's make sound :) If you move it to Turtle, all the subclasses again have to have their own voice method.
or should i simply make it : public abstract void makeNoise(); inside Turtle?
If you do, Turtle is abstract. So the question isn't which is better, the question is, do you want to be able to instantiate Turtle or not?
If you do, you have to implement the method.
If you are okay with it being abstract, then declare it abstract and don't list the method at all:
public abstract class Turtle extends Animal {
}
You might want to distinguish between Animals making noises or not. Something a long the lines of
public abstract class Animals {}
public abstract class AnimalsNoisy extends Animals { abstract void makeNoise(); }
You would then use Turtle extends Animals. The advantage of this structure is if you have a List of Animals you don't need to worry if they implemented the makeNoise method or not e.g.
for(AnimalsNoisy animal: ListAnimalsNoisy) { animal.makeNoise();}
It is a good example to learn how to make your code loosely coupled.
By loosely coupled I mean, if you decide to change or modify your code you will not touch your previous code. Sometimes it is referred as OPEN-CLOSE principle.
For this first you have to identify what part of your code is frequently changing.
Here the method makingNoise() will have different implementation based on your class.
This design can be achieved in following steps.
1) Make an interface which will have implementation for makeNoise()
method.
public interface NoiseInterface {
public void speak();
}
2) Create concrete implementation for NoiseInterface
eg: For Fox
public class FoxSound implements NoiseInterface {
#Override
public void speak()
{
//What does the fox say ?
Sysout("chin chin chin tin tin tin");
}
}
3: Provide the Noise Interface in Animal Class
public abstract class Animal
{
public NoiseInterface noiseMaker;
public abstract void makeNoise();
}
4: Just provide the Type of NoiseInterface of your choice in Fox Class
public class Fox extends Animal
{
public Fox()
{
noiseMaker = new FoxSound();
}
public void makeNoise()
{
noiseMaker.speak();
}
}
Now Amazing thing about this design is you will never have to worry about the implemetation. I will explain you how.
You will just call
Animal me = new Fox();
fox.makeNoise();
Now in future you want to mute the Fox.
You will create a new Interface Mute
public class Mute implements NoiseInterface {
#Override
public void speak()
{
Sysout("No sound");
}
}
Just change the NoiseBehavior in Fox class constructor
noiseMaker = new Mute();
You can find more on OPEN-CLOSE Principle Here
You may write like this,is this what you want?
public interface NoiseInterface {
void makingNoise();
void makingNoNoise();
}
public class Animal implements NoiseInterface{
#Override
public void makingNoise() {
System.out.println("noising");
}
#Override
public void makingNoNoise() {
System.out.println("slient");
}
}
public class Turtle extends Animal{
#Override
public void makingNoNoise() {
System.out.println("turtle");
super.makingNoNoise();
}
}

Categories