Results for Inheritance

Inheritance Concept Simplified In Java

November 16, 2018

Inheritance In Java
Inheritance In Java

Inheritance Concept Simplified In Java:


Inheritance provides us the ability to make new,more versatile objects from already compiled objects without changing the original object.It also allow us to write new classes based on existing classes without changing the existing class in any way.Inheritance allows descendants of  a class (known as child class or subclass) to inherit all of its member elements and methods from its ancestor(Known as Parent class or super class).
The advantage of Inheritance is that it supports incremental development by allowing us to write new code without affecting the previously deployed code. By inheriting from an existing functional class,we add new methods and data members. This mechanism leaves the actual code as it is and all changes happens to be in defined  in derived class . This also helps in tracking the bugs easily.
Another aspect of Inheritance is that we don't need the source code of the base class. Rather we need to import that class and write an extend keyword to our class.No copy paste is required.
Inheritance works as a building block providing incremental support which is very much sustainable.

The inheritance allows subclasses to inherit all the variables and methods of their parent class.
The inheritance cam be of many different forms:

  1. Single inheritance(only one super class)
  2. Multiple inheritance(several super classes)
  3. Hierarchical inheritance(One super class and many subclasses)
  4. Mutilevel inheritance(Derived from a derived class).

Single inheritance(only one super class):


Here B will contain all the public methods and variables of A.
The inheritance path is A->B

Multiple inheritance(several super classes):


Not directly supported by java but C will have all public variables and methods of A and B.
The inheritance path is A->C and B->C

Hierarchical inheritance(One super class and many subclasses):

This is the most real and common scenario when designing the real time application or issue.
The inheritance path is bird->duck
bird->cuckoo
bird->ostrich

Mutilevel inheritance(Derived from a derived class).

Class B will have all the public variables and methods of A apart from its own methods and variables and C will have all the the public methods and variables of B. Technically C will have all methods and variables of A and B.
The inheritance path is A->B->C

An Example:


class MyClass{
    public int x,y;
    MyClass(int x,int y)
    {
        this.x=x;
        this.y=y;
    }
}
class MyAnotherClass extends MyClass{
    int z;
    //inherits x,y from 
    MyAnotherClass(int x,int y,int z)
    {
    //code duplication
    //this.x=x;
    //this.y=y;
    //instead use super
    super(x,y);         
    this.z=z;
    }
    void displayValues()
    {
        System.out.println(x+y+z);
    }
}
public class TestInheritance{
    public static void main(String args[])
    {
        MyAnotherClass mac=new MyAnotherClass(3,2,2);
        mac.displayValues();
    }
}
 
relax!! the code won't compile if we do not activate super() and activate the two commented lines. This is just to show how we can do repetition of data if we do not take help from Inheritance.To avoid the repetition of code ,java uses a special keyword called Super,this can be used to refer directly to super class constructor.
this is another keyword user to tell java compiler that this will refer to current object. Let us see one more example

class Toy{
    void createNoice()
    {
        System.out.println("DUM DUM");
    }
}
class RailToy extends Toy{
    void createNoice()
    {
        System.out.println("JHIK JHIK");
    } 
}
class BusToy extends Toy{
    static boolean noHorn;
    void createNoice()
    { 
        if(noHorn)
        super.createNoice();
        else
        System.out.println("GOOO");
    }
}
public class MyToy{
    public static void main(String args[])
    {
        RailToy rt=new RailToy();
        BusToy bt=new BusToy();
        bt.noHorn=true;
        bt.createNoice();
        rt.createNoice();
        bt.noHorn=false;
        bt.createNoice();
    }
    
}
 
Output of the code:
$javac MyToy.java
$java -Xmx128M -Xms16M MyToy
DUM DUM
JHIK JHIK
GOOO
Here createNoice() method is overridden in the respective classes,with a condition that if noHorn is set to true it will invoke the Toy class's createNoice() method.
Inheritance Concept Simplified In Java Inheritance Concept Simplified In Java Reviewed by Animesh Chatterjee on November 16, 2018 Rating: 5

How Inheritance Concept Works For Java Enum??

May 30, 2013
How Inheritance Concept Works For Java Enum??
How Inheritance Concept Works For Java Enum??

How Inheritance Concept Works For Java Enum??

In my previous post (http://www.mydigitalvoice.in/2013/05/enum-concept-simplified-in-java.html) I have told how compiler will treat enum.
It will treat enum as a class.
enum Month  
{  
JAN,FEB,MAR;  
//note semicolon(;) is optional here  
}  
will be transferred by the compiler as..
Class Month  
{  
//for JAN  
public static final Month JAN=new Month();  
//similarly for FEB and MAR  
public static final Month FEB=new Month();  
public static final Month MAR=new Month();  
}  

Since the underlying concept is class, the very next question arises as can Inheritance concept works for enum? Let us see few concepts..

  • Every enum is direct child of java.lang.Enum class in java, So enum can't extend any other enum
  • Every enum is always final implicitly hence we can't create child enum
With the above statements we can conclude that inheritance concept is not applicable for explicitly.Hence we can't use extends keyword for enums.
enum x
{}
enum y extends x{}
output: Compile time error
enum x extends java.lan.Enum
{}
output: Compile time error
Class x
{}
enum y extends x{}
output: Compile time error
enum x
{}
Class y extends x{}
output: Compile time error
Can not inherit from final (enum) or enum types are not extensible

However an enum can implement any no of interfaces simultaneously.
interface x
{}
enum y implements x{}
Valid deceleration.
How Inheritance Concept Works For Java Enum?? How Inheritance Concept Works For Java Enum?? Reviewed by Animesh Chatterjee on May 30, 2013 Rating: 5

What Is IS-A Relationship And What Are The Rules Of IS-A Relationship In Java

May 13, 2013
In java Inheritance concept came to reduce the number of code line i.e code redundancy.

Say in an college we have some student,lecturer,principal.

Now for student we can have n column, so the corresponding class design will be..
class student{
int id
String name;
int age;
int No_of_Subject;
----
----
student(int id,string name,int age,......)
{
//constructor to initialize the value
this.id=id;
this.name=name;
this.age=age;
----
----

}
}
Similarly for lecturer class we will have...
class lecturer{
int id
String name;
int age;

----
----
lecturer(int id,string name,int age,......)
{
//constructor to initialize the value
this.id=id;
this.name=name;
this.age=age;
----
----

}
}
for principal we will have--
class principal{
int id
String name;
int age;

----
----
principal(int id,string name,int age,......)
{
//constructor to initialize the value
this.id=id;
this.name=name;
this.age=age;
----
----

}

}

now if you observe closely most of the code is redundant in nature. To get reduce redundancy we can create a common class and can derive more special classes from it.


How to design the common class?
It is interesting..we can create a parent class with all the common attribute..the common class is more abstract in nature.And the child classes are more specific class.Child classes can override the methods it got from parent class. It can also add more instance variable and child specific method. Instance variables are not overridden because they do not define behavior.So a sub class can give an inherited instance variable any value
like-
class College_person{
int id
String name;
int age;

----
----
College_person(int id,string name,int age,......)
{
//constructor to initialize the value
this.id=id;
this.name=name;
this.age=age;
----
----

}

}

Now the corresponding classes will become:
Student:
class student extends College_person {
int id
String name;
int age;

----
----
student(int id,string name,int age,......)
{
//constructor to initialize the value
super(id,name,age,......)
this.xyx=xyz;
----
----

}

}
Similarly for lecturer class we will have...
class lecturer extends College_person{
int id
String name;
int age;

----
----
lecturer(int id,string name,int age,......)
{
//constructor to initialize the value
super(id,name,age,......)
this.abc=abc;
----
----

}
}
for principal we will have--
class principal extends College_person{
int id
String name;
int age;

----
----
principal(int id,string name,int age,......)
{
//constructor to initialize the value
super(id,name,age,......)
this.tgb=tgb;

----
----

}

}
If you observe closely the super method is taking care of default value's initialization and specific values specific to the class are mentioned in the corresponding class.This is inheritance in nature.
the College_person becomes parent for all class student,lecturer and principal.

Cool isn't it???
But to perform a valid parent child relationship , the relationship has to go through a IS-A test. If it passes then only we can confirm the relationship is perfect.

here is student IS-A College_person? the answer is yes...hence College_person and student are in valid parent child relationship.Similarly it is yes for lecturer and principal

So the conclusions are--
  • IS-A relationship is valid inheritance
  • By using extends keyword we can implement IS-A relationship
  • It reduces the code redundancy but increases code re usability.
Let us see some one more example with respect to inheritance:
Class Parent:
Class Parent{
metho1()
{
}
}

Class Child:

Class Child extends Parent{
method2()
{
}

Class test:

Class test{
public static void main(String... Args)
{
//case-1
Parent p=new Parent();
p.method1();
p.method2();

//case-2
Child c=new Child();
c.method1();
c.method2();

//case-3
Parent p=new Child()
p.method1();
p.method2();

//case-4
Child c=new Parent();
c.method1();
c.method2();
}
Let us discuss case by case..
Case-1
Parent p=new Parent();
p.method1();
p.method2();

here Parent class is a independent class hence
p.method1() is a valid method call
but
p.method2() is invalid as in Parent class, method2 is unavailable
so we will get a Compilation error
Error Details:
Can not find symbol
symbol:method method2()
location:Class Parent
Conclusion:
The methods very specific to child is not available to Parent .So all child specific methods can not be called with parent reference.

Case-2
Child c=new Child();
c.method1();
c.method2();

As Child class is extending to Parent class hence by default method1 is available to Child class.
hence both the method calls are valid


Conclusion:
For the valid parent child relationship, whatever the parent is having by default will be available to child


Case-3
Parent p=new Child()
p.method1();
p.method2();

This is really interesting..We are creating object of Child of type Parent.
so p.method1() call is perfectly valid
but
p.method2() we will get compilation error
Error Details:
can not find symbol
symbol:method method2()
location:Class Parent

Conclusion:
Parent reference can hold child class object but using that variable (reference) we can not call child specific methods. We can only call parent's methods


Case-4
We will get compilation error
Error Details:
incompatible types
found Parent
Required Child



Conclusion:
Child reference can not be used to hold parent class object.
The last point is keep the IS-A direction one way, Child to parent. Java supports Child to parent direction. Not the other way round.
Square IS-A shape,but not necessarily Shape IS-A Square.
That's it for today!!.
What Is IS-A Relationship And What Are The Rules Of IS-A Relationship In Java What Is IS-A Relationship And What Are The Rules Of IS-A Relationship In Java Reviewed by Animesh Chatterjee on May 13, 2013 Rating: 5
Powered by Blogger.