Inheritance
Reusability is a concept where we use the existing class to create new class so that we save the
resources and money. This concept of reusability in CLASSES in OOPS is called INHERITANCE. Thus,
inheritance is process of creating new class from the existing class. Where existing class is known as superclass (base class/ parent class) and newly created class is known as subclass (derived class / child class).
When object of subclass is created, superclass copies all its members in the subclass objects. i.e. subclass object will have its own members plus members of superclass.
Important points
In the inheritance the class which is give data members and methods is known as base or super or parent class. The class which is taking the data members and methods is known as sub or derived or child class. The data members and methods of a class are known as features. The concept of inheritance is also known as re-usability or extendable classes or sub classing or derivation.
Why use Inheritance?
For Method Overriding (used for Runtime Polymorphism). It's main uses are to enable polymorphism and to be able to reuse code for different classes by putting it in a common super class for code Re-usability.
Advantage of inheritance
If we develop any application using concept of Inheritance than that application have following advantages,
1. Application development time is less.
2. Application take less memory.
3. Application execution time is less.
4. Application performance is enhanced (improved).
5. Redundancy (repetition) of the code is reduced or minimized so that we get consistence results and less storage cost.
Note: In Inheritance the scope of access modifier increasing is allowed but decreasing is not allowed. Suppose in parent class method access modifier is default then it's present in child class with default or public or protected access modifier but not private (it decreased scope).
Types of Inheritance
Based on number of ways inheriting the feature of base class into derived class we have five types of inheritance; they are:
1. Single inheritance
2. Multiple inheritance
3. Hierarchical inheritance
4. Multilevel inheritance
5. Hybrid inheritance
1. Single inheritance
In single inheritance there exists single base class and single derived class.
Example of Single Inheritance
Code
class Faculty { float salary=30000; } class Science extends Faculty { float bonous=2000; public static void main(String args[]) { Science obj=new Science(); System.out.println("Salary is:"+obj.salary); System.out.println("Bonous is:"+obj.bonous); } }
Output:
Salary is: 30000.0
Bonus is: 2000.0
2. Multilevel inheritances in Java
In Multilevel inheritances there exists single base class, single derived class and multiple intermediate base classes. It is process of creating a single subclass derived class
Single base class + single derived class + multiple intermediate base classes.
Intermediate base classes - An intermediate base class is one in one context with access derived class and in another context same class access base class.
Hence all the above three inheritance types are supported by both classes and interfaces.
Example of Multilevel Inheritance
Code
class Faculty { float total_sal=0, salary=30000; } class HRA extends Faculty { float hra=3000; } class DA extends HRA { float da=2000; } class Science extends DA { float bonous=2000; public static void main(String args[]) { Science obj=new Science(); obj.total_sal=obj.salary+obj.hra+obj.da+obj.bonous; System.out.println("Total Salary is:"+obj.total_sal); } }
Output: Total Salary is: 37000.0
3. Multiple inheritance
In multiple inheritance there exist multiple classes and single derived class.
The concept of multiple inheritance is not supported in java through concept of classes but it can be supported through the concept
of interface.
Hybrid inheritance.
Combination of any inheritance type
In the combination if one of the combinations is multiple inheritance then the inherited combination is not supported by java through the classes concept but it can be supported through the concept of interface.
Inheriting the feature from base class to derived class. In order to inherit the feature of base class into derived class we use the following syntax
class ClassName-2 extends ClasssName-1
{
variable declaration;
Method declaration;
}
Explanation
-
ClassName-1 and ClassName-2 represents name of the base and derived classes respectively. extends is one of the keywords used for inheriting the features of base class into derived class it improves the functionality of derived class.
Important Points for Inheritance:
In java programming one derived class can extends only one base class because java programming does not support multiple inheritance through the concept of classes, but it can be supported through the concept of Interface.
Whenever we develop any inheritance application first create an object of bottom most derived class but not for top most base class. When we create an object of bottom most derived class, first we get the memory space for the data members of top most base class, and then we get the memory space for data member of other bottom most derived class.
Bottom most derived class contains logical appearance for the data members of all top most base classes. If we do not want to give the features of base class to the derived class, then the definition of the base class must be preceded by final hence final base classes are not reusable or not inheritable.
If we are do not want to give some of the features of base class to derived class than such features of base class must be as private hence private features of base class are not inheritable or accessible in derived class.
Data members and methods of a base class can be inherited into the derived class but constructors of base class cannot be inherited because every constructor of a class is made for initializing its own data members but not made for initializing the data members of other classes.
An object of base class can contain details about features of same class but
an object of base class never contains the details about special features of its derived class (this concept is known as scope of base class object). For each and every class in java there exists an implicit predefined super class called java.lang.Object. because it provides garbage collection facilities to its sub classes for collecting un-used memory space and improved the performance of java application.
Why multiple
inheritance
is
not
supported in java?
Due to ambiguity problem java does not support multiple inheritance at class level.
Example
Code
class A { void disp() { System.out.println("Hello"); } } class B { void disp() { System.out.println("How are you?"); } } class C extends A, B //suppose if it were { public Static void main (String args[]) { C obj=new C(); obj.disp();//Now which disp() method would be invoked? } }
In above code we call both class A and class B disp() method then it confusion which class method is call. So due to this ambiguity problem in java do not use multiple inheritance at class level, but it supports at interface level.
To inherit a class, you simply incorporate the definition of one class into another by using the extends keyword. To see how, let's begin with a short example. The following program creates a superclass called A and a subclass called B.
// A simple example of inheritance. Create a superclass.
Code
class A{ int i, j; void showij { System.out.println("i and j:"+ i + " "+ j); } } class B extends A { int k; void showk() { System.out.println("k: "+k); } void sum() { System.ou.println("i+j+k:" + (i+j+k)); } } class SimpleInheritance { public static void main(String args[]) { A superOb = new A(); B subOb = new B(); // The superclass may be used by itself. superOb.i = 10; superOb.j = 20; System.out.println("Contents of superOb: "); superOb.showij(); System.out.println(); subOb.i= 7; /* The subclass has access to all public members of its superclass. */ subObj = 8; subOb.k = 9; System.out.println("Contents of subOb: "); subOb.showij(); subOb.showk(); System.out.println("Sum of i, j and k in subOb:"); subOb.sum(); } }
The output from this
program is
shown here:
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24
As you can see, the subclass B includes all of the members of its superclass, A. This is why subOb can access i and j and call showij(). Also, inside sum(), i and j can be referred to directly, as if they were part of B.
Even though A is a superclass for B, it is also a completely independent, stand-alone class. Being a superclass for a subclass does not mean that the superclass cannot be used by itself. Further, a subclass can be a superclass for another subclass.
The general form of a class declaration that inherits a superclass is shown here:
class subclass-name extends superclass-name
{
// body of class
}
Member Access and Inheritance
Although a subclass includes all of the members of its superclass, it cannot access those members of the superclass that have been declared as private. For example, consider the following simple class hierarchy:
/* In a class hierarchy, private members remain private to their class. This program contains an error and will not-compile. */
// Create a superclass.
Code
class A { int i; // public by default private int j; // private to A void setij(int x, int y){ i=x; j=y; } } class B extends A { int total; void sum(){ total = i+j; } // ERROR j is not accessible here } class Access { public static void main (String args[]) { B subOb = new B(); subOb.setij(10, 12); subOb.sum(); System.out.printIn("Total is " + subOb.total); } }
This program will not compile because the reference to j inside the sum ( )
method of B causes an access violation. Since j is declared as private, it
is only accessible by other members of its own class. Subclasses have no
access to it.
Final keyword in java
It is used to make a variable as a constant, Restrict method overriding,
Restrict inheritance. It is used at variable level, method level and class
level. In java language final keyword can be used in following way.
1. Final at variable level
2. Final at method level
3. Final at class level
1. Final at variable level
Final keyword is used to make a variable as a constant. This is similar to
const in other language. A variable declared with the final keyword cannot
be modified by the program after initialization. This is useful to universal
constants, such as “PI”.
Final Keyword in java Example
Code
public class Circle { public static final double PI=3.14159; public static void main(String x []) { System.out.println(PI); } }
2. Final at method level
It makes a method final, meaning that sub classes cannot override this
method. The compiler checks and gives an error if you try to override the
method. When we want to restrict overriding, then make a method as a
final.
public class A
{
public void fun1()
{
………………..
}
public final void fun2()
{
………………...
}
}
class B extends A
{
public void fun1()
{
……………..
}
public void fun2()
{
// it gives an error because we cannot override final method
}
}
Example
of
final keyword at method level
Code
class Employee { final void disp() { System.out.println(“Hello Good Morning”); } } class Developer extends Employee { void disp() { System.out.println(“How are you?”); } } class FinalDemo { public static void main(String args[]) { Developer obj = new Developer(); Obj.disp(); } }
Output: It gives an error
3. Final at class level
It makes a class final, meaning that the class cannot be inheriting by other classes. When we want to restrict inheritance then make class as a final.
Example
public final class A
{
.........................
.........................
}
public class B extends A
{
// it gives an error, because we can not inherit final class
}
Example of
final
keyword at class level
Code
final class Employee { int salary = 10000; } class Developer extends Employee { void show() { System.out.println(“Hello Good morning”) } } class FinalDemo { public static void main(String args[]) { Developer obj = new Developer(); obj.show(); } }
Output:
It gives an error
A Superclass Variable Can Reference a Subclass Object
A reference variable of a superclass can be assigned a reference to any subclass derived from that superclass. You will find this aspect of inheritance quite useful in a variety of situations. For example, consider the following:
Code
class 2dshape { int length, breadth; 2dshape(int len, int bre) { length = len breadth = bre; } void area() { float a = length * breadth; System.out.println("The area is "+a) } } class 3dshape extends 2dshape { int depth; 3dshape(int len, int bre, int dep) { length =len; breadth = bre; depth = dep; } void volume() { float v = length * breadth * depth; System.out.println("volume = "+v) } } class Demo { public static void main(String args[]) { 2dshape s1 = new 2dshape(10,20); 3dshape s2 = new 3dshape(1,2,3); 2dshape ref; ref = s1; ref.area(); // well defined as it exists in 2dshape ref = s2; ref.volume(); /* invalid step as it is not defined in 2dshape */ } }
This program gives a compiler error as it recognizes that the reference variable is the parent (superclass) variable hence it cannot recognize the volume function in the subclass.
Multilevel Inheritance
Up to this point, we have been using simple class hierarchies that consist of only a superclass and a subclass. However, you can build hierarchies that contain as many layers of inheritance as you like. As mentioned, it is perfectly acceptable to use a subclass as a superclass of another. For example, given three classes called A, B, and C, C can be a subclass of B, which is a subclass of A. When this type of situation occurs, each subclass inherits all of the traits found in all of its superclasses. In this case, C inherits all aspects of B and A.
Example:
Code
class A { int a; } class B extends A { int b; } class C extends B { int c; C(int i,int j,int k) { a=i; b=j; c=k; } void display() { System.out.println(“a=”+a+”b=”+b+”c=”+c); } } class Main { public static void main(Strings[] args) { C obj1=new C(10,20,30); obj1.display(); } }
//The Output for this program is a=10 b=20 c=30
In this the class A variable 'a'
is inherited by class B While class B variables 'a' and 'b'
both are inherited by class C.
Calling the Constructors
In the inheritance hierarchy, what is the order of execution for the constructor? For example, given a subclass called B and a superclass called A, is A's constructor called before B's, or vice versa? The answer is that in a inheritance hierarchy, constructors are called in order of derivation, from superclass to subclass. Consider the following example:
Code
class A // Create a super class { A() { System.out.println("Inside A’s constructor."); } } class B extends A // Create a subclass by extending class A { B() { System.out.println(“Inside B’s constructor”) } } class C extends B // Create another subclass by extending B { C() { System.out.println(“Inside C’s constructor.”) } } class ConstructorDemo { public static void main(String args[]) { Cc = new C(); } }
The output from this
program
is shown
here:
Inside A's constructor
Inside B's constructor
Inside C's constructor
As you can see, the constructors are called in order of derivation. Constructors are executed in order of derivation because a superclass has no knowledge of any subclass. The initialization of non-static variables takes place from superclass to subclass.so first super class's A's constructor is executed followed by subclass B's and C's constructors respectively.
1. Two or more methods in the-Same class (including methods inherited from a superclass) with the same name but different argument lists are called method overloaded.
2. Return type, accessibility and. exception lists may be different.
3. Overloaded method may call one another simply providing a normal method call with an appropriately formed argument list.
4. Overloaded methods supplement each other.
5. Overloaded methods can exist in any numbers in the same class.
6. Overloading can be done in the same class & or subclass.
7. Overloading allows multiple implementation of the same essential functionality to use the same name.
Program: WAP with help of Method Overloading to calculate the volume of cube, rectangular box and rectangular box.
Code
class Volume { double v; Volume () { System.out.println("Method Overloading"); } void calVolume(int r, int h) { v=3.14f*r*r*h; System.out.println("Cylinder="+v); } void calVolume(int 1, int b,int h1) { v=l*b*hl; System.out.println("rbox="+v); } void calVolume(double s) { v=s*s*s System.out.println("Cube=" +v); } } class MethodOverloadDemo { public static void main(String[] args) { Volume v1=new Volume(); v1.calVolume(10); v1.calVolume(5,6,7); v1.calVolume(3,5); } }
Output:
Method Overloading
Cube=1000.0
rbox=210.0
Cube=15.0
Method Overriding
When in a method in the sub class has the same signature as that of the super
class, the sub class method is set to override the super class method. i.e. subclass method hides (replaces) the super class method.so subclass method is called as overriding method and superclass method is
called as overridden method.
The six parts in the signature of a method are:
1) Visibility Specifier
2) Keyword
3) Return Type
4) Method Name
5) Parameters list and their type.
6) Throws Conditions
The main rule of overriding that the signature of the method should be the same.
The two exceptions are:
1) Overriding method cannot be less accessible than the overridden method
2) Overriding method cannot throw super classes of the exception that is thrown by the overridden method.
Program:
Code
class Shape { double length, breadth; void Area() { // this statement is very imp. for the next concepts System.out.println("The shape is not yet defined"); } } class Triangle extends Shape { Triangle(int base, int height) { length=base; breadth=height; } void Area() { //Method overriding System.out.println("The area of the triangle is "+ 0.5*length*breadth); } } class Main { public static void main(Strings[] args) { Triangle t=new Triangle(10,20); t.area(); //this calls show in Triangle } }
The Output:
The area of the triangle is 100.
When Area() is invoked on an object of type B, the version of Area() defined within TRIANGLE is used. That is, the version of Area () inside TRIANGLE overrides the version declared in Shape.
Difference between Overloading and Overriding
Late Binding /
Dynamic
Method Dispatch /
Runtime Polymorphism
/ Dynamic Binding
While the examples in the preceding section demonstrate the mechanics of method overriding, they do not show its power. Indeed, if there were nothing more to method overriding than a name space convention, method overriding forms the basis for one of Java's most powerful concepts:
Dynamic method dispatch is the mechanism by which a call to an overridden function is resolved at run time, rather than compile time. Dynamic method dispatch is important because this is how Java implements run-time polymorphism.
A superclass reference variable can refer to a subclass object. Java uses this fact to resolve calls to overridden methods at run time. When an overridden method is called through a superclass reference, Java determines which version of that method to execute based upon the type of the object being referred to at the time the call occurs. Thus, this determination is made at run time. When different types of objects are referred to, different versions of an overridden method will be called. In other words, it is the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed. Therefore, if a superclass contains a method that is overridden by a subclass, then when different types of objects are referred to through a superclass reference variable, different version of the method are executed. Here is an example that illustrates dynamic method dispatch:
Code
class Shape { void Area() { System.out.println(“Inside Shape’s area method”) } } class Triangle extends Shape { void Area() // override Area() { System.out.println(“Inside Triangle’s Area method”) } } class Rectangle extends Shape { void Area() // override Area() { System.out.println(“Inside Reactangle’s Area method”) } } class Dispatch{ public static void main(String args[]){ Shape ref; // obtain a reference of type Shape ref = new Shape(); // object of Shape class is referred by super class reference ref ref.Area(); // calls Shape’s Area method ref = new Triangle (); // object of Triangle class is referred by superclass reference ref ref.Area(); // calls Triangle’s Area method ref = new Rectangle(); // object of Rectangle class is referred by superclass reference ref ref.Area(); // calls Rectangle’s Area method } }
The output from the program is shown here:
Inside Shape's Area method
Inside Triangle's Area method
Inside Rectangle's Area method
This program creates one superclass called Shape and two subclasses of it, called Triangle and Rectangle. Subclasses Triangle and Rectangle override Area() declared in Shape. Inside the main() method, objects of type Shape, Triangle, and Rectangle are declared. Also, a reference of type Shape, called ref, is declared. The program then assigns a reference to each type of object to ref and uses that reference to invoke Area ().
As the output shows, the version of Area ( ) executed is determined by the type of object being referred to at the time of the call. Had it been determined by the type of the reference variable, ref, you would see three calls to Shape's Area () method.
Abstract Class:
1. Abstract class is the opposite to the final class.
2. The advantages of abstract methods are
a) To enable dynamic binding
b) To force the subclass to override and keep the same method name.
3. An abstract class declares a method that does not contain an implementation (method definition).
i.e. An abstract method does not have a body.
4. The declaration of an abstract method ends with a semi colon and specify the method with the Keyword abstract.
5. super class will only provide a method signature.
6. Any class with one or more abstract methods is declared abstract.
7. Abstract classes may have abstract, non-abstract methods and constructors.
8. An abstract method cannot be private because private method cannot be inherited.
9. An abstract class may not be instantiated (i.e. we cannot create an object and call constructor).
10. Variable can be declared of an abstract class type.
11. GOOD practice to make constructors in abstract class protected rather than public.
12. If a subclass does not provide an implementation to the abstract method of superclass, it will be declared abstract.
Program:
Code
abstract class Shapel { abstract void area(); void met1() { System.out.println("metl in shape1"); } } class Square extends Shapel { void area() { System.out.println("area in Square"); } } class Rectangle extends Shapel { void area() { System.out.println("area in Rectangle"); } } class Abstract1 { public static void main(String args[]) { Shapel x = new Shape1(); Shapel ref; ref= new Square(); ref.area(); ref.metl(); ref= new Rectangle(); ref.area() ref.metl(); } }
Output: Compile Error - Shape1() is abstract; can not be instantiated. Comment it.
Output:
metl in Shapel
area in Square
area in Rectangle
metl in Shapel
super
Keyword: The first use of super is to refer to a super class variable or method which is hidden (variable) or Overridden (method) in the super class. When super class and subclass members are having the same name then to access the superclass members from subclass members, we write the super as first statement as follows.
Example
Code
class A { int x = 10; void met1() { System.out.println(x); } } class Superl extends A { int x=100; void met1() { System.out.println("Super1"); System.out.println(super.x); super.met1(); } public static void main(String args[]) { Super1 p = new Super1(); p.met1(); System.out.println(p.x); } }
Super:
The second use of super is to call a specific super class constructor from the subclass's Constructor by passing
appropriate arguments. The call to super should be in the first line of the sub class's constructor.
Code
class Area { int l, b; Area(int x, int y) { l=x; b=y; } void calArea() { int c = 1 * b; System.out.println("Area : "+c); } } class Volume extends Area { int h; Volume(int a, int b, int c) { super(a,b); h=c; } void calVolume() { int v=l*b*h; System.out.println("Volume: "+v); } public static void main(String args[]) { Volume x = new Volume(10,20,30); x.calArea(); x.calVolume(); } }
Output:
Area: 200
Volume: 6000
Q. Explain the difference Overloading and Overriding.
Ans:
Overloading occurs when two or more methods have same name (but different parameter list), such that both methods are available side by side in the same class.
Overriding occurs when a subclass method and a superclass method use the same name (and the matching parameters list), such that subclass method blocks out the superclass method.
Post a Comment