Inheritance and HAS-A relationship - java

Can I say that class House HAS-A class Animal even if that is not declared explicitly and can be seen only through inheritance?
public class Animal {}
public class Dog extends Animal {}
public class House {
private Dog inhabitant = new Dog();
}

Your class "House" Has-A Dog.
Every Dog Is-AN Animal.
So, Yes, your House has an Animal.

The is a relationship is expressed with inheritance and has a relationship is expressed with aggregation. Both inheritance and aggregation allow you to place sub-objects inside your new class.
Simple example:
Aggregation: is used when House has a Dog/Animal and Dog/Animal can exist without House.

It's more a question about semantics, there's nothing wrong in saying House has an Animal since Dog is an Animal
But reference 'inhabitant' in house can only point to a Dog instance. So, it's better to say House has a Dog. It will be more align with Law of Demeter.

You can't say that class House HAS-A class Animal. You could say an instance of class House has an instance of class Animal (or Dog).

One of the advantages of Object-Oriented programming language is code reuse. There are two ways we can do code reuse either by implementation of inheritance (IS-A relationship), or aggregation (HAS-A relationship). Although the compiler and Java virtual machine (JVM) will do a lot of work for you when you use inheritance, you can also get at the functionality of inheritance when you use composition.
Read Difference between IS-A and HAS-A relationships

I would say yes, because Animal is polymorphic for Dog

Yes, because the House class HAS-A Dog and Dog IS-A (extends)
Animal.....

Is-A means it refers to inheritance or implementation using extends or implements keywords.
Has-A means instance of one class “has a” reference to an instance of another class or another instance of same class without using any keywords.

Related

How to make a type part of another type? (Java)

This question isn't worded the best, but essentially I created some classes that can be used as types called Dog, Cat, Whale, etc. I also made another class that could take in a pet. How would I make classes like dog, cat, etc. belong to the pet type?
What you're looking for is called inheritance. In Java, you use the extends keyword in the class definition to make one class extend another.
For example:
public class Dog extends Pet { ...

Java inheritance hierarchy animal classes

I'm supposed to have a hierarchy of animals in my java project, but I'm confused on what should extend what.
Here are the instructions:
Write classes or interfaces to represent the following:
Adoptable
Animal
Bat
Bird
BlueWhale
Dog
Emu
Fish
Goldfish
Mammal
Otter
Parakeet
Reptile
Turtle
WaterDweller
Whale
Winged
You need to decide on the structure of the classes/interfaces. Consider:
Which should be an abstract class? a concrete class? Which should be
an interface? How should the classes be related through inheritance?
In what classes should methods be placed? What methods should be
overridden? What information should be taken in as a parameter and
what information can be hard-coded into a class? Some additional
details/requirements:
All animals have a method "isWarmBlooded" that returns a boolean. The
method can be in the class directly or inherited. All animals have a
name. All classes have a toString method that returns the animal's
name, whether the animal is warm blooded, and a list of all animal
names that apply to the animal. The toString method can be in the
class directly or inherited. Animals that can be adopted as pets have
a method "getHomeCareInstructions" that returns a description of how
to care for the animal. Animals that live in water (are water
dwellers) have a method "livesOnLand" that returns a boolean of
whether the animal also can live on land. Animals that have wings have
a method "flies" that returns a boolean of whether the animal can fly.
This part of the assignment isn't necessarily difficult from a
programming perspective. What you should spend time on is carefully
considering the design of you classes and how they should be related
through inheritance or interfaces
I'm not sure how to design this because I know a bird is winged, but so is a bat. Therefor bat would extend winged, but bats are also mammals. I can't have winged extend mammal because birds are not mammals. Also, whales and otters are watter dwellers, but are also waterdwellers. I can't have waterdwellers extend mammals (because whales/otters are mammals), but fish are not mammals and are waterdwellers. How would I make it so a bat is both winged and a mammal? The programming is the easy part, just struggling with the structure of the project. How can I structure this so it could work?
So in your modelling you have to think:
Which are actual animals?
e.g. whales, otters -> classes
which are a type of animal?
e.g. a bird. -> abstract class
Since every emu is a bird.
This is called the Liskov Substitution Principle https://en.wikipedia.org/wiki/Liskov_substitution_principle
Which are characteristics of an animal?
e.g. WaterDweller, Winged -> those are interfaces.
Every class can have one superclass, it can have many characteristics, like being winged, or being a waterdweller, or adoptable
one addition for your bat example:
It is a mammal -> therefore it's superclass is mammal. It is winged - which is a characteristic - so it implements the winged interface.
class Bat extends Mammal implements Winged{
}

Trouble with understanding extends and instantiate. Is extends the same as instantiating a class?

My question is. Are these the same?
public class Pet {
}
public class Fish extends Pet {
}
If I extend the class Pet to my Fish class, is that the same as if I instantiate the Pet class in my Fish class? The extends is above and the instantiate is below. Are they the same?
public class Pet {
}
public class Fish {
Pet myPet = new Pet ();
}
First example describes inheritance, the second one - composition. Those are two OOP concepts. They allow programmer to reuse common logic. Your should prefer to use composiiton over inheritance.
Copy from other SO answer:
They are absolutely different. Inheritance is an "is-a" relationship.
Composition is a "has-a".
You do composition by having an instance of another class C as a field
of your class, instead of extending C. A good example where
composition would've been a lot better than inheritance is
java.util.Stack, which currently extends java.util.Vector. This is now
considered a blunder. A stack "is-NOT-a" vector; you should not be
allowed to insert and remove elements arbitrarily. It should've been
composition instead.
Unfortunately it's too late to rectify this design mistake, since
changing the inheritance hierarchy now would break compatibility with
existing code. Had Stack used composition instead of inheritance, it
can always be modified to use another data structure without violating
the API.
I highly recommend Josh Bloch's book Effective Java 2nd Edition
Item 16: Favor composition over inheritance
Item 17: Design and document for inheritance or else prohibit it
Good object-oriented
design is not about liberally extending existing classes. Your first
instinct should be to compose instead.
They are not the same.
In the first example, with inheritance, an instance of a Fish can access all of it's own properties and methods, including those inherited from Pet, via this or self, depending on language.
In the second example, myPet is just a variable that happens to be an instance of the Pet class, but Pet and Fish have no relationship to each other.
They are completely different. extends is 'is-a' relationship , while later (composition) is 'has-a'. Take a look here for more details.
No, They are completely different.
In this one public class Fish extends Pet { } you are using inheritance to extend the Pet class to the Fish class, meaning that Fish is a subclass of Pet it will inherit the Pet class.
However in this one
public class Fish {
Pet myPet = new Pet (); }
You are creating a whole new object called Fish which does not extend from anything, just that it has a class level object that is a Pet, so you can use the Pet objects methods variables etc through the myPet object however it is not inherited by Fish so Fish would be its own object and not a subclass of Pet.
These are the differences.
As for when you should use which, here is the general rule: if you are enhancing a class then you should use Inheritance, however if you are just going to be using a class for its particular function then you should instantiate it as a variable in the class.

Can a subclass also be a superclass?

Can a subclass also be a superclass of another subclass in Java? Perhaps this is not the best example, but consider the following classes:
public class Animal { }
public class Dog extends Animal { }
public class Cat extends Animal { }
public class Siamese extends Cat { }
public class JackRussel extends Dog { }
Does inheritance allow for this sort of behaviour?
Given that JackRussels would require the methods and properties of both an Animal and a Dog, and Siamese's would require the methods and properties of both Animal and Cat.
If not, is there a generalised approach I could take to achieve this sort of behaviour?
Cheers
Yes, that behavior is exactly what is expected when using inheritance in Java.
Here's some quick reading that you may find usefull: http://www.homeandlearn.co.uk/java/java_inheritance.html
Your JackRussel object will inherit all fields and methods from it's Animal and Dog super-classes that are:
not declared private;
are not overridden (in which case will get only have access to the overridden one);
are not shadowed (in which case will get only have access to the shadowed one);
Here's another quick link on shadowing and overriding in Java:
http://docstore.mik.ua/orelly/java-ent/jnut/ch03_04.htm
Having those point in mind, you can easily design inheritance tree that can propagate parent’s behavior and state to all of its children.
Thanks.
Of course this is possible. But saying that the Siamese would require methods and fields from both superclasses is a bit wrong. When cat extends animal it gets all of the fields and methods of animal (if you do not override them). Then, when Siamese extends that cat class, it will automatically get the whole Cat class, including the things that are from the Animal class, regardless of whether they are overriden or not.
In short terms, this is possible.

Casting between Java classes extended from common Abstract class

I have an interesting situation that EMF forced me into:
abstract class AbstractDog{
...
}
public class Dog extends AbstractDog{
< implemented code >
}
public class DogTemplate extends AbstractDog{
< implemented code identical to Dog >
}
The code found in both Dog and DogTemplate are literally identical (don't ask - our system is very reliant on Eclipse stuff and this is the only way). I need to cast from a DogTemplate into a Dog, but getting java.lang.ClassCastException when I do Dog d = (Dog) dogTemplateInstance. I completely understand why this exception is occurring, so please don't bother telling me why.
What I need to know is if there is any way to leverage the common ancestor relationship between the 2 classes to make this cast happen?
There is no way a DogTemplate can be cast to a Dog, since Dog doesn't even extend DogTemplate. Only a Dog instance can be cast to a Dog.
You could create a new Dog instance using a constructor which would copy all the fields of DogTemplate to Dog, if it's possible. Or you could use a common interface to both classes.
Make the dog and dogTemplate implements the same interface. in this interface, declare the public contract/behavior of Dog.
Then you will be able to cast DogTemplate -> IDog.

Categories

Resources