0% found this document useful (0 votes)
72 views

Inheritance, Package, Interface and Exception Handling 3.1 Inheritance

The document discusses inheritance in Java. It explains that inheritance allows one class to acquire properties of another class in a hierarchical manner. It provides examples of single inheritance, where a subclass extends a single superclass, and multi-level inheritance with multiple levels in the hierarchy. It also discusses accessing members of superclasses, overriding methods, calling constructors from superclasses to subclasses, and using the super keyword. Constructors are called from the superclass down to the most specific subclass. Method overriding occurs when a subclass defines a method with the same name and parameters as a method in the superclass.

Uploaded by

Surya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views

Inheritance, Package, Interface and Exception Handling 3.1 Inheritance

The document discusses inheritance in Java. It explains that inheritance allows one class to acquire properties of another class in a hierarchical manner. It provides examples of single inheritance, where a subclass extends a single superclass, and multi-level inheritance with multiple levels in the hierarchy. It also discusses accessing members of superclasses, overriding methods, calling constructors from superclasses to subclasses, and using the super keyword. Constructors are called from the superclass down to the most specific subclass. Method overriding occurs when a subclass defines a method with the same name and parameters as a method in the superclass.

Uploaded by

Surya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

SEM-III

KNS INSTITUTE OF TECHNLOGY

JAVA CH-3

DEPARTMENT OF MCA

Programming with JAVA


Chapter-3

INHERITANCE, PACKAGE, INTERFACE AND EXCEPTION HANDLING


3.1 INHERITANCE
Inheritance is the process by which one object acquires the properties of another object.
This is important because it supports the concept of hierarchical classification.
Birds
Attrib
utes
Non Flying
Birds
Attributes

Flying
Birds
Attributes
Eagle

Pigeon

Attrib
utes

Attrib
utes

Pengui
n
Attrib
utes

Kiwi
Attrib
utes

o Inheritance interacts with encapsulation as well.


o If a given class encapsulates some attributes, then any subclass will have the same attributes
plus any that it adds as part of its specialization.
o Inheritance Can be achieved by using extends key word.
The following program creates a superclass called A and a subclass called B. Notice how the
keyword extends is used to create a subclass of A
// Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
} } // end of B class
Lecturer: Syed Khutubuddin Ahmed

class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
superOb.i = 10; superOb.j = 20;
superOb.showij();
/* The subclass has access to all public members of its
superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
subOb.showij();
subOb.showk();
subOb.sum();
}
}

E-Mail: [email protected]

SEM-III

KNS INSTITUTE OF TECHNLOGY

JAVA CH-3

DEPARTMENT OF MCA

The general form of a class declaration that inherits a superclass is shown here:
class subclass-name extends superclass-name
{
// body of class
}
o You can only specify one superclass for any subclass that you create.
o Java does not Support the inheritance of multiple super-classes into a single subclass.
o You can, as stated, create a hierarchy of inheritance in which a subclass becomes a superclass
of another subclass. However, no class can be a superclass of itself

3.1.2 MEMBER ACCESS AND INHERITANCE


o 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.
o 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.
class A {
int i; // public by default
private int j; // private to A
void setij(int x, int y) {
i = x;
j = y;
}}
// A's j is not accessible here.
class B extends A {
int total;
void 2.1.3
sum() Declaring
{
Objects:
total = i + j; // ERROR, j is not accessible here
} Box mybox = new Box();
}
OR

Lecturer: Syed Khutubuddin Ahmed

class Access {
public static void main(String args[]) {
B subOb = new B();
subOb.setij(10, 12);
subOb.sum();
System.out.println("Total is " + subOb.total);
}
}
o This program will not compile because the
reference to j inside the sum( ) method of B
causes an access violation.
o Since j is declared as private, it is only
accessible by other members of its own
class. Subclasses have no access to it.

E-Mail: [email protected]

SEM-III

KNS INSTITUTE OF TECHNLOGY

JAVA CH-3

DEPARTMENT OF MCA

3.1.3 A SUPERCLASS VARIABLE CAN REFERENCE A SUBCLASS OBJECT


o A reference variable of a superclass can be assigned a reference to any subclass derived from
that superclass.
o For example, consider the following:
class super1
{
int a,b;
public void superClassFunction()
{
System.out.println("super class function");
}
}
class sub extends super1
{
int c;
public void subFunction()
{
System.out.println("sub class function ");
}
}

public class test {


public static void main(String args[])
{
super1 super_obj = new super1();
sub sub_obj = new sub();
super1 r;
r=sub_obj;
r.superClassFunction();
/*
this
calls
superClassFunction */
/*
r.subFunction(); // not possible as
subFunction is not part of Super Class */
}
}

3.1.4 USING SUPER


o Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the
keyword super
super has two general forms:
o The first calls the superclass constructor.
o The second is used to access a member of the superclass that has been hidden by a
member of a subclass.
i) Using super to Call Superclass Constructors
o A subclass can call a constructor defined by its superclass by use of the following form of
super:
super(arg-list);
o Here, arg-list specifies any arguments needed by the constructor in the superclass.
o super( ) must always be the first statement executed inside a subclass constructor.

Lecturer: Syed Khutubuddin Ahmed

E-Mail: [email protected]

SEM-III

KNS INSTITUTE OF TECHNLOGY

JAVA CH-3

DEPARTMENT OF MCA

sub(int x, int y, int z)


{
super(x,y); // this calls the base class constructor
c=z;
System.out.println("a=" + a + "b=" + b +"c=" + c);
}
}
class test
{
public static void main(String args[])
{
sub sub_obj = new sub(10,20,30);
}
}

class base
{
int a,b;
base(int x,int y)
{
a=x;
b=y;
}
}
class sub extends base
{
int c;

ii) A Second Use for super:


The second form of super acts somewhat like this, except that it always refers to
the superclass of the subclass in which it is used.
This usage has the following general form:
super.member
Here, member can be either a method or an instance variable.

Use: This second form of super is most applicable to situations in which member names
of a subclass hide members by the same name in the superclass.

// Using super to overcome name hiding.


class A {
int i;
}
// Create a subclass by extending class A.
class B extends A {
int i; // this i hides the i in A
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}

System.out.println("i in superclass: " + super.i);


System.out.println("i in subclass: " + i);
}
class UseSuper {
public static void main(String args[])
{
B subOb = new B(1, 2);
}
}

Note:

Super can also be used to call methods that are hidden by a subclass.

This program displays the following OUTPUT:


i in superclass: 1
i in subclass: 2

Lecturer: Syed Khutubuddin Ahmed

E-Mail: [email protected]

SEM-III

KNS INSTITUTE OF TECHNLOGY

JAVA CH-3

DEPARTMENT OF MCA

Although the instance variable i in B hides the I in A, super allows access to the i defined in
the superclass.
Note: Super can also be used to call methods that are hidden by a subclass.

3.1.5 CREATING A MULTILEVEL HIERARCHY

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
super classes. In this case, C inherits all aspects of B and A

class a
{
int i;
}
class b extends a
{
int j;
}
class c extends b
{
int k;
}

class inh_hy
{
public static void main(String args[])
{
c obj= new c();
obj.i=10;
obj.j=20;
obj.k=30;
System.out.println("i="+obj.i + "j="+obj.j+ "k="+obj.k);
}
}
Output: i= 10 j=20 k=30

3.1.6 WHEN CONSTRUCTORS ARE CALLED

When a class hierarchy is created, in what order are the constructors for the classes that
make up the hierarchy called?
For example, given a subclass called B and a superclass called A, is As constructor called
before Bs, or vice versa?
The answer is that in a class hierarchy, constructors are called in order of derivation, from
superclass to subclass.
Further, since super( ) must be the first statement executed in a subclass constructor, this
order is the same whether or not super( ) is used.
If super( ) is not used, then the default or parameterless constructor of each superclass will be
executed

Lecturer: Syed Khutubuddin Ahmed

E-Mail: [email protected]

SEM-III

KNS INSTITUTE OF TECHNLOGY

JAVA CH-3

class A {
A() {
System.out.println("Inside A's constructor.");
}
}
class B extends A {
B() {
System.out.println("Inside B's constructor.");
}
}
class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}

DEPARTMENT OF MCA

class CallingCons
{
public static void main(String args[])
{
C c = new C();
}
}

OUTPUT:
Inside As constructor
Inside Bs constructor
Inside Cs constructor

If you think about it, it makes sense that constructors are executed in order of derivation.
Because a superclass has no knowledge of any subclass, any initialization it needs to perform
is separate from and possibly prerequisite to any initialization performed by the subclass.
Therefore, it must be executed first.

3.1.7 METHOD OVERRIDING

In a class hierarchy, when a method in a subclass has the same name and type signature as a
method in its superclass, then the method in the subclass is said to override the method in the
superclass.
When an overridden method is called from within a subclass, it will always refer to the
method defined by the subclass.
The version of the method defined by the superclass will be hidden.

class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
void show() {
System.out.println("i and j: " + i + " " + j);
}
} // end of class A
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
Lecturer: Syed Khutubuddin Ahmed

// display k this overrides show() in A


void show() {
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
OUTPUT:
k: 3

E-Mail: [email protected]

SEM-III

KNS INSTITUTE OF TECHNLOGY

JAVA CH-3

DEPARTMENT OF MCA

Explanation of the Program:

When show( ) is invoked on an object of type B, the version of show( ) defined within B is
used.

That is, the version of show( ) inside B overrides the version declared in A.

If you wish to access the superclass version of an overridden method, you can do so by using
super.

For example, in this version of B, the superclass version of show( ) is invoked within the
subclass version. This allows all instance variables to be displayed.
An Example program showing the solution to the above problem:

class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
void show() {
System.out.println("i and j: " + i + " " + j);
}
} // end of class A
class B extends A {
int k;
B(int a, int b, int c)
{
super(a, b);
k = c;
}
void show() {
super.show(); // this calls A's show()
System.out.println("k: " + k);
}
}

class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}

OUTPUT:
i and j : 1 2
k: 3

NOTE:
o Method overriding occurs only when the names and the type signatures of the two
methods are identical. If they are not, then the two methods are simply overloaded.
o The concept of overriding happen with a condition inheritance is the mandatory.

Lecturer: Syed Khutubuddin Ahmed

E-Mail: [email protected]

You might also like