Documente Academic
Documente Profesional
Documente Cultură
Concept
Inheritance is based on the idea of reusability. This means that the features of an existing class are reused and new features are added to it. The existing class undergoes no modifications (i.e. it remains unchanged), it is just extended to form a new class. As a result, the new class has combined features of both the classes.
Existing Class
C
Functions Pointers
Super/Base/Parent Class
New Class
Inheritance
Extend
Basics
Inheritance is the technique of creating a new class by building upon an existing class definition. In this process, the new class acquires the properties and methods of the existing class. The existing class is referred to as parent or super or base class, and the new class is called a child or sub or derived class.
Types of Inheritance
1. Single Inheritance
B X
2. Hierarchical Inheritance
B X Y Z
3. Multilevel Inheritance
X Y Z
class Room extends Rectangle // sub class { int hgt ; //. other members of Room } Classes in Java can only inherit one class at a time (single inheritance). A subclass can declare new fields / methods that are not in the superclass.
// Single inheritance with factorial computation class Base { // super class int ctr ; void factorial( ) { int i, fact = 1 ; for(i = ctr ; i > 0 ; i ) fact = i ; System.out.println(Factorial = +fact) ; } } // end of Base class class Derv extends Base { // subclass void setCtr(int n) { ctr = n ; } }
class Test { public static void main(String args[ ]) throws Exception { Derv od = new Derv( ) ; // derived class object od.setCtr(5) ; od.factorial( ) ; // derv. class accesses members of base class } } Inheritance and Member Accessibility The accessibility of base class members inside a sub class depends on the fact that whether the subclass belongs to same base classs package.
subclass belongs to some other package. Base Class Derived Class Visibility Within base Outside base Visibility classs package classs package private protected public default (no modifier) Not inherited Yes Yes Yes Not inherited Yes Yes No
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 (default) members of the parent. A subclass does not inherit the private members of its parent class. However, inherited public or protected methods of the parent class can be used for accessing the private fields by the subclass. Also the subclass does not inherit the constructors from its base class.
// Single inheritance and Member Accessibility class Circle { // super class private double rad ; // private access double getRad( ) { // default access return rad ; } void setRad(double val) { // default access rad = val < 0 ? 0.0 : val ; } public double calcDiam( ) { // public access return (rad 2) ; } public double calcCirc( ) { // public access double c = calcDiam( ) 3.14 ;
return c ; } public double calcArea( ) { // public access double a = rad rad 3.14 ; return a ; } } class Sphere extends Circle { // subclass public void display( ) { System.out.println(\nSphere Properties) ; // System.out.println(rad) ; rad has private access System.out.println(Side: +getRad( )) ; System.out.println(Diameter: +calcDiam( )) ; System.out.println(Circumferance: +calcCirc( ));
{ Sphere ball = new Sphere( ) ; // subclass object ball.setRad(25.55) ; // accesses default member ball.display( ) ; // accesses public member } }
Sphere
default getRad( ) setRad( ) Inherited from Circle public calcDiam( ) calcCirc( ) calcArea( ) display( )
It provides the best encapsulation while still permitting inheritance. A protected member in Java is a hybrid between a default and a public member. Like default members, protected members are accessible inside its own class, and other non subclasses in the same package, but not available to statements outside the classs package. Like public members, protected members are inherited by derived classes and are accessible to member functions in the derived class of any package.
// Inheritance with protected visibility class Rectangle { // superclass private int width ; protected int depth ; protected int getWidth( ) { return width ; } protected void setWidth(int w) { // protected access width = w ; } } class Box extends Rectangle { // subclass private int height ; public void setHeight(int h) {
height = h ; } int boxArea( ) { int ar, w ; // ar = width depth ; Error: width has private access // accessing protected inherited members w = getWidth( ) ; // inherited method accesses private field ar = w depth ; return ar ; } int boxVol( ) { int v = boxArea( ) height ;
{ Box a = new Box( ) ; // subclass object // protected inherited method accesses private field a.setWidth(15) ; // invoking protected method a.depth = 10 ; // accessing inherited protected field a.setHeight(12) ;
Output:
Area =150 Volume= 1800
Box private height protected depth getWidth( ) setWidth( ) public setHeight( ) boxArea( ) boxVol( )
If the superclass definition contains a default zero argument constructor then, the subclass does not require a constructor or the subclass constructor (if present) does not need to invoke super( ) In either of the cases, the JVM will automatically invoke the default zero argument constructor in the superclass. If the superclass definition contains a parameterized constructor then, the subclass must have a parameterized constructor explicitly invoking a super() with an argument list matching the order and type of the desired super
class constructor. Explicit invocation of a superclass constructor must be the first line in the subclass constructor.
// Using super to call superclass constructor class B { // superclass private int a ; private double b ; B(int a, double b ) { System.out.println(Base class constructor called) ; this.a = a ; this.b = b ; } //.. } class D extends B { // subclass private int x ; private double y ;
D(int x, double y, int m, double n) { super(m, n) ; // invoking superclass constructor System.out.println(\nSub class constructor called); this.x = x ; this.y = y ; } // } class Test {
public static void main(String args[ ]) throws Exception
Output:
Base class constructor called Sub class constructor called
Order of Invocation:
When a subclass is instantiated, the object will begin with an invocation of the constructor in the base class and initialize downwards through constructors in each subclass till it reaches the final subclass constructor.
// Using super to refer an inherited hidden field class B { // superclass int i ; } class D extends B { // subclass int i ; // hides field i of base class private double y ; D(int a, int b) { super.i = a ; // refers to inherited hidden field i this.i = b ; } void show( ) { System.out.println(Hidden field: +super.i) ; System.out.println(Visible field: +i) ; }
} // end of class D class Test { public static void main(String args[ ]) throws Exception { D od = new D(10, 20) ; // subclass object od.show( ); } }
Output:
Method Overriding
It is a concept which occurs when an instance method in a subclass hides or overrides an inherited method of the superclass due to similar declarations. Overridden methods are methods that are redefined within an inherited class or subclass. They have the same signature, return types and access modifiers as the ones in the superclass. An overridden superclass method can be invoked in a subclass using the keyword super as: super . overriddenMethod( ) ;
// Using super to invoke an overridden method class B { // superclass private int x ; B(int x) { this.x = x ; } void display( ) { System.out.println(Super x = +x) ; } } class D extends B { // subclass int y ; D(int x, int y) { super(x) ; // invoking parent constructor this.y = y ;
} void display( ) // overriding method redefinition { super.display( ) ; // invoking hidden parent method System.out.println(Sub y = +y) ; } } class Test { public static void main(String args[ ]) throws Exception { D od = new D(10, 20) ; od.display( ) ; // invokes display( ) of D } }
Output:
Super x = 10 Sub y = 20
Abstract Classes
An abstract class defines a structure of given abstraction without any implementation. In Java, an abstract class is a special type of superclass that is specified by using the abstract keyword as: abstract class < classname > { . } Abstract classes cannot be instantiated, as they are defined solely for the purpose of extension (inheritance) by other classes. An abstract class may or may not have abstract methods.
Abstract Methods
It is an overridden method which is declared with the abstract modifier in an abstract superclass, but implemented specifically in a subclass. Declaration Syntax: abstract type <methodname> ([ parameterlist ]) ; An abstract method is used when a superclass is unable to create meaningful implementation for a method. Abstract methods are sometimes referred to as subclasser responsibility since they have no implementation defined in the superclass.
// Code segment for an abstract class and method abstract class Figure { // abstract superclass // abstract void draw( ) ; // abstract method declaration // } class Square extends Figure { // subclass // void draw { // abstract method definition ver.1 System.out.println(Drawing Square) ; } // } class Triangle extends Figure { // subclass //
void draw { // abstract method definition ver.2 System.out.println(Drawing Triangle) ; } // } // end of class An abstract class is used to create a superclass reference variable, that can be used to point to a subclass object. The type of subclass object referred to by the superclass reference variable at run time dynamically determines the execution of the correct version of the abstract method, thus implementing Javas approach to subclass polymorphism.
// Code fragment for subclass polymorphism class AbsTest { // Figure f ; // abstract superclass variable Square s = new Square( ) ; Triangle t = new Triangle( ) ; f=t; // f refers to Triangle object f.draw( ) ; // invokes draw( ) of Triangle f=s; // f refers to Square object f.draw( ) ; // invokes draw( ) of Square // }
Polymorphism
It is the capability of an action or method to do different things based on the object it is acting upon.
Compile Time Run Time Also called early or staticAlso called late or binding. dynamic binding. It is achieved using methodIt is achieved using overloading. method overriding. It is a mechanism by whichIt is a mechanism by the call to an overloadedwhich the call to an method is resolved by theoverridden method compiler at the compile( related to a subclass time. object) is resolved by the JVM at the run time.
// Dynamic binding using an overridden method abstract class Shape { // abstract super class double ar ; abstract void area( ) ; // abstract method declaration } class Circle extends Shape { // subclass double radius ; Circle(double r) { radius = r ; } public void area( ) {// abstract method def. version 1 ar = 3.14 radius radius ; System.out.println(Circle area = +ar) ; }}
class Triangle extends Shape { // subclass double base, height ; Triangle(double b, double h) { base = b ; height = h ; } public void area( ) {// abstract method def. version 2 ar = base height / 2 ; System.out.println(Triangle area = +ar) ; } } class PolyTest { public static void main(String args[ ]) throws Exception {
Shape s ;// abstract superclass reference variable s = new Circle(2.0) ; // s refers to Circle object s.area( ) ; // invokes area( ) of Circle s = new Triangle(2.0, 5.0) ; // s refers to Triangle obj. s.area( ) ; // invokes area( ) of Triangle } // end of main } // end of main class
Output:
Circle area = 12.56 Triangle area = 5.0
A class Student defines the personal data of a student while another class Marks defines the marks obtained by the student. Their details are: Class name : Student Data members: name : stores name of student age : integer variable Member functions: void inpdetails1( ) : to accept values for data members void show1( ) : to display personal data of student
Class name Data members: regnum, marks subject Member functions: void inpdetails2( ) void show2( )
: Marks : integer type variables : stores name of subject : to accept values for data members : to display exam details
Specify the class Student giving details of the functions. Using the concept of inheritance, specify the class Marks, giving details of the functions. The main function need not be written.
A class Account has the following details: Class name : Account Protected data members : acctNumber : a positive integer principle : a double precision real number Member functions: Account(int a, double p) : parameterized construc tor void display( ) : to display the data Extend class Account to derive two classes: Simple and Compound whose details are:
: parameterized construc tor to initialize various attributes void display( ) : to display the data double interest( ) : calculates and returns the interest using the for mula: SI = P X R X T/100 where, SI = simple interest, T = time, R = rate, P = principle
Class name Data members double rate int time Member functions: Simple(.)
: parameterized construc tor to initialize various attributes void display( ) : to display the data double interest( ) : calculates and returns the interest using the for mula: CI = P[1+R/100]T where, CI = compound interest, T = time, R = rate, P = principle
Class name Data members double rate int time Member functions: Compound(.)
Specify the classes Account, Simple and Compound giving details of their constructors and member functions. The output should be displayed as : Account Number = .. Principle = .. Rate = .. Time = .. Interest = .. You need not write the main function.