Tuesday 6 December 2016

Chapter 9.2 : The instanceof Keyword - HAS-A relationship


Let us use the instanceof operator to check determine whether Mammal is actually an Animal, and dog is actually an Animal
interface Animal{}
 
class Mammal implements Animal{}
 
public class Dog extends Mammal{
   public static void main(String args[]){
 
      Mammal m = new Mammal();
      Dog d = new Dog();
 
      System.out.println(m instanceof Animal);
      System.out.println(d instanceof Mammal);
      System.out.println(d instanceof Animal);
   }
} 
This would produce the following result:
true
true
true

HAS-A relationship:

These relationships are mainly based on the usage. This determines whether a certain class HAS-A certain thing. This relationship helps to reduce duplication of code as well as bugs.
Lets us look into an example:
public class Vehicle{}
public class Speed{}
public class Van extends Vehicle{
        private Speed sp;
} 
This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have to put the entire code that belongs to speed inside the Van class., which makes it possible to reuse the Speed class in multiple applications.
In Object-Oriented feature, the users do not need to bother about which object is doing the real work. To achieve this, the Van class hides the implementation details from the users of the Van class. So basically what happens is the users would ask the Van class to do a certain action and the Van class will either do the work by itself or ask another class to perform the action.
A very important fact to remember is that Java only supports only single inheritance. This means that a class cannot extend more than one class. Therefore following is illegal:
public class extends Animal, Mammal{} 
However, a class can implement one or more interfaces. This has made Java get rid of the impossibility of multiple inheritance.



No comments:

Post a Comment