Inheritance & Packaging

Inheritance
nheritance can be defined as the process where one object acquires the properties of another. With the use of inheritance the information is made manageable in a hierarchical order.
A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class).
Excepting Object, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object.
Classes can be derived from classes that are derived from classes that are derived from classes, and so on, and ultimately derived from the topmost class, Object. Such a class is said to be descended from all the classes in the inheritance chain stretching back to Object.
Advantages:-
1. Inheritance is used to minimize the amount of duplicate code in an application by sharing common code amongst several subclasses. Where equivalent code exists in two related classes, the hierarchy can usually be refactored to move the common code up to a mutual superclass. This also tends to result in a better organization of code and smaller, simpler compilation units.
2. Inheritance can also make application code more flexible to change because classes that inherit from a common superclass can be used interchangeably. If the return type of a method is superclass.
3. Reusability :- facility to use public methods of base class without rewriting the same
4. Extensibility :- extending the base class logic as per business logic of the derived class
5. Data hiding :- base class can decide to keep some data private so that it cannot be altered by the derived class
6. Overriding :- With inheritance, we will be able to override the methods of the base class so that meaningful implementation of the base class method can be designed in the derived class.
Disadvantages:-
1.One of the main disadvantages of inheritance in Java (the same in other object-oriented languages) is the increased time/effort it takes the program to jump through all the levels of overloaded classes. If a given class has ten levels of abstraction above it, then it will essentially take ten jumps to run through a function defined in each of those classes
2.Main disadvantage of using inheritance is that the two classes (base and inherited class) get tightly coupled. This means one cannot be used independent of each other.
3. Also with time, during maintenance adding new features both base as well as derived classes are required to be changed. If a method signature is changed then we will be affected in both cases (inheritance & composition)
4. If a method is deleted in the "super class" or aggregate, then we will have to re-factor in case of using that method.Here things can get a bit complicated in case of inheritance because our programs will still compile, but the methods of the subclass will no longer be overriding superclass methods. These methods will become independent methods in their own right.
Using ‘extends’ keyword:-
The extends is a Java keyword, which is used in inheritance process of Java. It specifies the superclass in a class declaration using extends keyword. It is a keyword that indicates the parent class that a subclass is inheriting from and may not be used as identifiers i.e. you cannot declare a variable or class with this name in your Java program. In Java, every class is a subclass of java.lang.Object.
Using ‘Interface’ keyword:-
An interface in the Java programming language is an abstract type that is used to specify an interface (in the generic sense of the term) that classes must implement. Interfaces are declared using the interface keyword, and may only contain method signature and constant declarations (variable declarations that are declared to be both static and final). An interface never contains method implementations (i.e. function "bodies").
Interfaces cannot be instantiated, but rather are implemented. A class that implements an interface must implement all of the methods described in the interface, or be an abstract class. Object references in Java may be specified to be of an interface type; in which case, they must either be null, or be bound to an object that implements the interface.
One benefit of using interfaces is that they simulate multiple inheritance. All classes in Java must have exactly one base class, the only exception being java.lang.Object (the root class of the Java type system); multiple inheritance of classes is not allowed.
A Java class may implement, and an interface may extend, any number of interfaces; however an interface may not implement an interface.
‘Interface’ v/s 'extends' keyword:-
1. Extends keyword is used to implement the concept of inheritance in Java programming language while Implements keyword in Java programming language is used for implementing an interface by a class.
2. Extents is used when creating a subclass while implements is used when implementing an interface.
3. You can only extend one class in java, but you can implement many interfaces.
Subcasses and Superclasses
Java allows you to derive new classes from existing classes. Let's consider the relationship between a student class and an MSc student class. The Student class would have variables and methods that describe the state and the behaviour of students; for example, we can have variables such as the name and the mark of the student; we can have methods such as getMark and setMark. An MScStudent class could be derived from the existing Student class, therefore inheriting the variables and methods contained in the Student class. New variables and methods can be added to the derived class; for example, we can add a variable and any necessary corresponding methods to represent the dissertation aspect for MSc students.
The original class that is used to derive a new class is called a superclass, a parent class or a base class. The derived class is a subclass or a child class. Java uses the key word extends to indicate that a new class is being derived from a superclass.
A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members: -
* The inherited fields can be used directly, just like any other fields.
* You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended). * You can declare new fields in the subclass that are not in the superclass.
* The inherited methods can be used directly as they are.
* You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it.
* You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it.
* You can declare new methods in the subclass that are not in the superclass.
* You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super.
'super' keyword usagerd usage
The super is a reference variable that is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e. referred by super reference variable.
Usage of super Keyword
* super is used to refer immediate parent class instance variable.
* super() is used to invoke immediate parent class constructor.
* super is used to invoke immediate parent class method.
The Object class
Object is the root of the hierarchy for any class, but it is not the direct1 super class for all classes. In fact, Object is only the direct super class for classes that are explicitly derived from Object or do not explicitly list another super class. Otherwise, it sits higher up the hierarchy chain. So, every class (except Object) has one and only one direct super class, and that super class is either Object or some other class but if you work your way up a class' inheritance chain eventually you'll hit Object (which is what we mean by Object is a super class for every class)..
Inheritance Type: -
1. Single inheritance
2. Multi – level inheritance
3. Hierarchical inheritance
4. Multiple inheritance
5. Hybrid inheritance
1. Single inheritance: - Single inheritance enables a derived class to inherit properties and behavior from a single parent class. It allows a derived class to inherit the properties and behavior of a base class, thus enabling code reusability as well as adding new features to the existing code. This makes the code much more elegant and less repetitive. Inheritance is one of the key features of object-oriented programming (OOP).
Example: -
class employee
{
private int eno;
private String ename;
public void setemp(int no,String name)
{
eno = no;
ename = name;
}
public void putemp()
{
System.out.println("Empno : " + eno);
System.out.println("Ename : " + ename);
}
}
class department extends employee
{
private int dno;
private String dname;
public void setdept(int no,String name)
{
dno = no;
dname = name;
}
public void putdept()
{
System.out.println("Deptno : " + dno);
System.out.println("Deptname : " + dname);
}
public static void main(String args[])
{
department d = new department();
d.setemp(7,"Anuj");
d.setdept(12,"Teacher");
d.putemp();
d.putdept();
}
}
Output: -
C:\java>javac department.java
C:\java>java department
Empno : 7
Ename : Anuj
Deptno : 12
Deptname : Teacher
2. Multi – level inheritance: -
Multilevel Inheritance A Scenario where one class is inheriting/extending the bahavior of another class which in turn is inheriting behavior from yet another class. This multilevel inheritance actually has no limitations on the number of levels it can go. So as far as java goes, it is limitless. But for maintenance and ease of use sakes it is better to keep the inheritance levels to a single digit number.
Multilevel inheritance is when there is a multiple father child hierarchy in your application. Ex: class A extends class B class B extends class C class C extends class D This means class A extends class D indirectly through classes B asnd C.
class Car{
public Car()
{
System.out.println("Class Car");
} public void vehicleType()
{
System.out.println("Vehicle Type: Car");
}
}
class Maruti extends Car{
public Maruti()
{
System.out.println("Class Maruti");
}
public void brand()
{ System.out.println("Brand: Maruti");
} public void speed()
{
System.out.println("Max: 90Kmph");
}
}
public class Maruti800 extends Maruti{
public Maruti800()
{
System.out.println("Maruti Model: 800");
}
public void speed()
{
System.out.println("Max: 80Kmph");
}
public static void main(String args[])
{
Maruti800 obj=new Maruti800();
obj.vehicleType();
obj.brand();
obj.speed();
}
}
Output: -
Class Car
Class Maruti
Maruti Model: 800
Vehicle Type: Car
Brand: Maruti
Max: 80Kmph
3. Hierarchical inheritance
Hierarchical inheritance in simple sentence "creating one or more child classes.from the parent class".The form of inheritance in which more than one classes are derived from single base class is known as hierarchical inheritance. We can implement the hierarchical inheritance by defining at least three classes in which one is base class and the remaining two classes is derived from the same one base class.
Example: -
//A.java
public class A
{
void DisplayA()
{
System.out.println("I am in A");
}
}
//B.java
public class B extends A
{
void DisplayB()
{
System.out.println("I am in B");
}
}
//c.java
public class C extends A
{
void DisplayC()
{
System.out.println("I am in C");
}
}
//MainClass.java
public class MainClass
{
public static void main(String args[])
{
System.out.println("Calling for subclass C");
C c = new C();
c.DisplayA();
c.DisplayC();
System.out.println("Calling for subclass B");
B b = new B();
b.DisplayA();
b.DisplayB();
}
}
Output =>
Calling for subclass C
I am in A
I am in C Calling for subclass B I am in A
I am in B
4. Multiple inheritance: - Multiple inheritance is the ability of a single class to inherit from multiple classes. Java does not have this capability.
The designers of Java considered multiple inheritance to be too complex, and not in line with the goal of keeping Java simple.
Multiple inheritance can cause the diamond problem
One specific problem that Java avoids by not having multiple inheritance is called the diamond problem.
The diamond problem is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If a method in D calls a method defined in A (and does not override the method), and B and C have overridden that method differently, then from which class does it inherit: B, or C?"

  
                    A
                   / \
                  B   C
                   \ /
                    D

Interface resolve Diamond problem in Java
Java allows the multiple inheritance of interfaces only. Interfaces are essentially abstract base classes with all abstract methods and no data essentially abstract base classes with all abstract methods and no data implementation of a specific method or property and no ambiguity arises.
An interface is a collection of methods that must be implemented by the implementing class. An interface defines a contract regarding what a class must do, without saying anything about how the class will do it. Interface can contain declaration of methods and variables. implementing class must define all the methods declared in the interface If a class implements an interface and does not implement all the methods then class itself must be declared as abstract Variables in interface automatically become static and final variableof the implementing class Members of interface are implicitly public, so need not be declared as public.An interface must be implemented in class.
Example:-
interface Animal {
public void eat();
public void travel();
}
public class MammalInt implements Animal{
public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
public int noOfLegs(){
return 0;
}
public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
C:\java>javac MammalInt.java
C:\java>java MammalInt
Mammal eats
Mammal travels
5. Hybrid inheritance: - Hierarchical inheritance is possible to have in java even using the classes alone itself as in this type of inheritance two or more classes have the same parent class or in other words a single parent class has two or more child classes, which is quite possible to have in java.
class Student
{
int rollNumber;
void getNumber(int n)
{
rollNumber=n;
}
void putNumber()
{
System.out.println("Roll No :: "+rollNumber);
}
}
class Test extends Student
{
float part1,part2;
void getMarks(float m1,float m2)
{
part1=m1;
part2=m2;
}
void putMarks()
{
System.out.println("Marks Obtained\n");
System.out.println("PART1: "+part1);
System.out.println("PART2: "+part2);
}
}
interface Sports
{
float sportWt=6.0F;
void putwt();
}
class Results extends Test implements Sports
{
float total;
public void putwt()
{
System.out.println("Sports Wt="+sportWt);
}
void display()
{
total=part1+part2+sportWt;
putNumber();
putMarks();
putwt();
System.out.println("Total Score= "+total);
}
}
class hybrid
{
public static void main(String args[])
{
Results student1=new Results();
student1.getNumber(1234);
student1.getMarks(17.4F, 33.0F);
student1.display();
}
}
C:\java>java hybrid
Roll No :: 1234
Marks Obtained
PART1: 17.4
PART2: 33.0
Sports Wt=6.0
Total Score= 56.4


Free Web Hosting