Transcript chapter 1

Programming With Java
ICS201
Chapter 7
Inheritance
University Of Ha’il
1
Programming With Java
ICS201
Introduction

Inheritance is the process by which a new class is created
from another class


The new class is called a derived class

The original class is called the base class
A derived class automatically has all the instance variables
and methods that the base class has, and it can have
additional methods and/or instance variables as well.

Inheritance is especially advantageous because it allows
code to be reused, without having to copy it into the
definitions of the derived classes.
University Of Ha’il
2
Programming With Java
ICS201
Introduction

The extends clause in a class declaration establishes an
inheritance relationship between two classes. It has the
following syntax:
class ClassName2 extends ClassName1
{
// body of the class
}
University Of Ha’il
3
Programming With Java
ICS201
Derived Class (subclass)

A derived class, also called a subclass (or child class), is
defined by starting with another already defined class,
called a base class or superclass or parent class, and
adding (and/or changing) methods, instance variables,
and static variables

The derived class inherits all the public methods, all
the public and private instance variables, and all the
public and private static variables from the base class.

The derived class can add more instance variables,
static variables, and/or methods.
University Of Ha’il
4
Programming With Java
ICS201
Example (Inheritance)
//This example shows how to declare a simple class inheritance hierarchy
class Grandparents{ }
class Parents extends Grandparents{ }
class Uncles extends Grandparents{ }
class Sisters extends Parents{ }
class Brothers extends Parents{ }
class Cousins extends Uncles{ }
class InheritanceHierarchy
{
public static void main(String[ ] a)
{
Grandparents Grandfather = new Grandparents(); System.out.println( "Instantiated Grandparents” );
Grandfather = new Parents();
System.out.println( "Instantiated Parents" );
Grandfather = new Sisters();
System.out.println( "Instantiated Sisters" );
Grandfather = new Brothers();
System.out.println( "Instantiated Brothers" );
Grandfather = new Uncles();
System.out.println( "Instantiated Uncles" );
Grandfather = new Cousins();
System.out.println( "Instantiated Cousins" );
}
}
University Of Ha’il
5
Programming With Java
ICS201
Example (Inheritance)
Output:
Instantiated Grandparents
Instantiated Parents
Instantiated Sisters
Instantiated Brothers
Instantiated Uncles
Instantiated Cousins
University Of Ha’il
6
Programming With Java
ICS201
Inherited Members

A
derived
class
automatically
has
all
the
instance
variables, all the static variables, and all the public
methods of the base class


Members from the base class are said to be inherited.
Definitions for the inherited variables and methods do not
appear in the derived class

The code is reused without having to explicitly copy it,
unless the creator of the derived class redefines one or
more of the base class methods.
University Of Ha’il
7
Programming With Java
ICS201
Inheritance and Variables
Inherit Variable and Methods

A class inherits the state (determined by variables) and
behavior (determined by methods) defined by all of its
super classes. Therefore an object has one copy of every
instance variable of its own class and its super classes.
Variable Hiding

If a variable of a class has a same name (type maybe
different) as a superclass variable, in that case class
variable hides the superclass variable.

You can access a hidden variable by using super keyword
super.variable
University Of Ha’il
8
Programming With Java
ICS201
Example (Inheritance and variables)
class C1 {
static int x;
}
class C2 extends C1 {
static String x;
}
class Cc {
public static void main(String[] args)
{
C1 p = new C1();
p.x = 55;
System.out.println( “p.x=" + p.x);
C2 q = new C2();
q.x = "This is a String";
System.out.println( "q.x=" + q.x);
}
}
University Of Ha’il
Output:
p.x=55
q.x=This is a String
9
Programming With Java
ICS201
Example (Inheritance and variables)
class M100 {
int x = 100;
}
class M200 extends M100 {
int x = 200;
void display()
{
System.out.println( "x=" + x);
System.out.println( "super.x="
+super.x);
}
}
class SuperKeyword {
public static void main(String[] args)
{
M200 m200 = new M200();
m200.display();
}
}
University Of Ha’il
Output:
x=200
super.x=100
10
Programming With Java
ICS201
Homework
Write an application that illustrates how to access a hidden
variable. Class G declares a static variable x. Class H
extends G and declares an instance variable x. A display()
method in H displays both of these variables.
University Of Ha’il
11
Programming With Java
ICS201
Method Overriding



Method overriding occurs when a class declares a
method that has the same type signature as a method
declared by one of its super classes.
When a method in a subclass overrides a method in a
superclass, the method in the super class is hidden
relative to the subclass object.
Method overriding is
a very important capability
because it forms the basis for run-time polymorphism
(means one interface, multiple implementation).
University Of Ha’il
12
Programming With Java
ICS201
Method Overriding

The access permission of an overridden method can be
changed from private in the base class to public (or
some other more permissive access) in the derived
class.

However, the access permission of an overridden
method can not be changed from public in the base
class to a more restricted access permission in the
derived class.
University Of Ha’il
13
Programming With Java
ICS201
Method Overriding





Given the following method header in a base case:
private void doSomething()
The following method header is valid in a derived class:
public void doSomething()
However, the opposite is not valid
Given the following method header in a base case:
public void doSomething()
The following method header is not valid in a derived
class:
private void doSomething()
University Of Ha’il
14
Programming With Java
ICS201
Note

Do not confuse overriding a method in a derived class
with overloading a method name



When a method is overridden, the new method
definition given in the derived class has the exact
same number and types of parameters as in the
base class.
When a method in a derived class has a different
signature from the method in the base class, that is
overloading.
Note that when the derived class overloads the
original method, it still inherits the original method
from the base class as well.
University Of Ha’il
15
Example (Method Overriding)
Programming With Java
ICS201
class A1
{
void hello()
{
System.out.println( "Hello from A1" );
}
}
class B1 extends A1
{
void hello()
{
System.out.println( "Hello from B1" );
}
}
class MethodOverriding
{
public static void main(String[] arg)
{
C1 obj = new C1();
obj.hello();
A1 a = new C1() ;
a.hello();
}
}
class C1 extends B1
{
void hello()
{
System.out.println( "Hello from C1");
}
}
University Of Ha’il
Output:
Hello from C1
Hello from C1
16
Programming With Java
ICS201
The final Modifier

If the modifier final is placed before the definition of a
method, then that method may not be redefined in a
derived class.

If the modifier final is placed before the definition of a
class, then that class may not be used as a base class
to derive other classes.
University Of Ha’il
17
Programming With Java
ICS201
Example (Inheritance and Methods)
class I1
{
void hello( String s )
{
System.out.println( "I1:"+ s );
}
}
class J1 extends I1
{
void hello( String s )
{
super.hello(s);
System.out.println( "J1:"+ s );
}
}
class K1 extends J1
{
void hello( String s )
{
super.hello(s);
System.out.println( "K1:"+ s );
}
}
class SuperForMethod
{
public static void main( String[] ar )
{
I1 obj;
System.out.println( "Initiating I1" );
obj = new I1();
obj.hello( "morning" );
System.out.println( "Initiating J1" );
obj = new J1();
obj.hello( "noon" );
System.out.println( "Initiating K1" );
obj = new K1();
obj.hello( "evening" );
}
}
University Of Ha’il
18
Programming With Java
ICS201
Example (Inheritance and Methods)
Output:
Initiating I1
I1:morning
Initiating J1
I1:noon
J1:noon
Initiating K1
I1:evening
J1:evening
K1:evening
University Of Ha’il
19
Programming With Java
ICS201
Exercise (Inheritance and Methods)

Write an application that illustrates how a method
can
invoke
a
superclass
method.
Class
I2
is
extended by J2. Class J2 is extended by K2. Each of
these classes defines a getDescription() method
that
returns
a
string.
That
string
includes
a
description of the class plus descriptions of each
superclass. Instantiate each of these classes and
invoke the getDescription() mehod.
University Of Ha’il
20
Programming With Java
ICS201
Inheritance and Methods

When we define a method with the same signature as a
base class methods, we effectively override that base
method. That means when we send the same message
to base or subclass, the methods defined for that class
will be executed. This is called overriding. This is what
we do in C++ when we define a method as virtual.

To access the parent method we can use modifier super
followed by the dot and the parent method name.

Super.parentMethod()
University Of Ha’il
21
Programming With Java
ICS201
The super Constructor

A derived class uses a constructor from the base class
to initialize all the data inherited from the base class


In order to invoke a constructor from the base class,
it uses a special syntax:
public derivedClass(int p1, int p2, double p3)
{
super(p1, p2);
instanceVariable = p3;
}
In the above example, super(p1, p2); is a call to
the base class constructor
University Of Ha’il
22
Programming With Java
ICS201
The super Constructor

A call to the base class constructor can never use the
name of the base class, but uses the keyword super
instead.

A call to super must always be the first action taken in
a constructor definition.

An instance variable cannot be used as an argument to
super.
University Of Ha’il
23
Programming With Java
ICS201
Example (Inheritance & Constructor)
class S1 {
int s1;
S1( ) {
System.out.println( "print S1" ) ;
s1=1;
}
}
class T1 extends S1 {
int t1;
T1() {
System.out.println( "print T1" );
t1=2;
}
}
class U1 extends T1 {
int u1;
U1( ) {
System.out.println( "print U1" );
u1=3;
}
}
class InhAndConstructor
{
public static void main(String[ ] ar)
{
U1 u1 = new U1();
System.out.println( "u1.s1=" + u1.s1);
System.out.println( "u1.t1=" + u1.t1);
System.out.println( "u1.u1=" + u1.u1);
}
}
Output:
print S1
print T1
print U1
u1.s1=1
u1.t1=2
u1.u1=3
University Of Ha’il
24
Programming With Java
ICS201
Example (Inheritance & Constructor)
class S2 {
int s2;
S2( int s2) {
this.s2 = s2;
}
}
class T2 extends S2 {
int t2;
T2( int s2, int t2)
{
super(s2);
this.t2 = t2;
}
}
class U2 extends T2 {
int u2;
U2(int s2, int t2, int u2) {
super(s2,t2);
this.u2 = u2;
}
}
class SuperAndConstructor
{
public static void main(String[] arg)
{
U2 u2 = new U2(1,2,3);
System.out.println( "u2.s2 =" + u2.s2);
System.out.println( "u2.t2 =" + u2.t2);
System.out.println( "u2.u2 =" + u2.u2);
}
}
Output:
u2.s2 =1
u2.t2 =2
u2.t2 =3
University Of Ha’il
25
Programming With Java
ICS201
Inheritance & Final classes


final classes – A class can be defined as ‘final’
when we do not allow any further sub
classing.
This can be done for security reasons, or to
allow Java to perform some optimization in
accessing methods.
final class Polygon extends Shape
{
}
University Of Ha’il
26
Programming With Java
ICS201
Abstract Class

There are 3 possible modifiers that may precede the class
keyword:
abstract
Cannot be instantiated
final
Cannot be extended
public
Can be accessed by any other class. If this
keyword is missing, access to the class is
limited to the current package.
University Of Ha’il
27
Programming With Java
ICS201
Example (Abstract Class)
abstract class Shape {
void display()
{
}
}
class Circle extends Shape {
void display()
{
System.out.println( "Circle" );
}
}
class Rectangle extends Shape
{
void display() {
System.out.println( "Rectangle" );
}
}
class Triangle extends Shape {
void display()
{
System.out.println( "Triangle" );
}
}
class AbstractClass {
public static void main(String[] arg)
{
Shape s = new Circle();
s.display();
s = new Rectangle();
s.display();
s = new Triangle();
s.display();
}
OUTPUT:
}
University Of Ha’il
Circle
Rectangle
Triangle
28
Programming With Java
ICS201
Variable Modifiers

The possible modifiers that may precede the declaration of
a variable are:
final
private
Is a constant
Can be accessed only by code in the same class
protected Can be accessed only by code in a subclass or
the same package
public
Can be accessed by any other class
static
Is not an instance variable
University Of Ha’il
29
Programming With Java
ICS201
Access Modifiers
Programming With Java
ICS201
Polymorphism



Polymorphism (from the Greek, meaning "many
forms", or something similar) is the quality that allows
one name to be used for more than one (hopefully
related) but technically different purpose.
Method overriding occurs when a class declares a
method having same types of signature as a method by
one of its super class.
Note: Super class reference can refer to objects of its
own or its subclass.
University Of Ha’il
31
Programming With Java
ICS201
Polymorphism

Methods can be overloaded. A method has the same
name as another member methods, but the type and/or
the count of parameters differs.
class Integer
{
float val;
void add( int amount )
{
val = val + amount;
}
void add( int num, int den)
{
val = float(num) / den;
}
}
University Of Ha’il
32