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

Java PPT Ib

Uploaded by

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

Java PPT Ib

Uploaded by

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

Need for OOP Paradigm

 OOP is an approach to program organization and development,


which attempts to eliminate some of the drawbacks of conventional
programming methods by incorporating the best of structured
programming features with several new concepts.

 OOP allows us to decompose a problem into number of entities


called objects and then build data and methods (functions) around
these entities.

 The data of an object can be accessed only by the methods


associated with the object.
Introduction
⚫ Object-oriented programming (OOP) is a programming
paradigm that uses “Objects “and their interactions to design
applications.

⚫ It simplifies the software development and maintenance by


providing some concepts:

⚫ Object
⚫ Class
⚫ Data Abstraction & Encapsulation
⚫ Inheritance
⚫ Polymorphism
⚫ Dynamic Binding
⚫ Message Passing
Object
⚫Objects are the basic run time entities in an object-
oriented system. They may represent a person, a place,
a bank account, a table of data or any item that the
program has to handle.
Class
⚫ The entire set of data and code of an object can be made of a
user defined data type with the help of a class.

⚫ In fact, Objects are variables of the type class. Once a class has
been defined, we can create any number of objects belonging to
that class.

⚫ Classes are data types based on which objects are created.


Objects with similar properties and methods are grouped
together to form a Class. Thus a Class represents a set of
individual objects.
⚫ Characteristics of an object are represented in a class as
Properties. The actions that can be performed by objects
become functions of the class and is referred to as
Methods.

⚫ A class is thus a collection of objects of similar type . for


example: mango, apple, and orange are members of the
class fruit . ex: fruit mango; will create an object mango
belonging to the class fruit.
Example for class
⚫ class Human

⚫{

private:

⚫ EyeColor IColor;

⚫ NAME personname;

⚫ public:

⚫ void SetName(NAME anyName);

⚫ void SetIColor(EyeColor eyecolor);

⚫ };
Data abstraction
⚫ Abstraction refers to the act of representing essential features
without including the background details or explanations. since the
classes use the concept of data abstraction ,they are known as
abstraction data type(ADT).

For example, a class Car would be made up of an Engine, Gearbox,


Steering objects, and many more components. To build the Car
class, one does not need to know how the different components
work internally, but only how to interface with them, i.e., send
messages to them, receive messages from them, and perhaps make
the different objects composing the class interact with each other.
An example for abstraction
⚫ Humans manage complexity through abstraction. When you drive
your car you do not have to be concerned with the exact internal
working of your car(unless you are a mechanic). What you are
concerned with is interacting with your car via its interfaces like
steering wheel, brake pedal, accelerator pedal etc. Various
manufacturers of car has different implementation of car working but
its basic interface has not changed (i.e. you still use steering wheel,
brake pedal, accelerator pedal etc to interact with your car). Hence the
knowledgeyou have of your car is abstract.
Methods
⚫ A method is a group of instructions that is given a name and can be
called up at any point in a program simply by quoting that name.
⚫ Drawing a Triangle require draw of three straight lines. This
instruction three times to draw a simple triangle.
⚫ We can define a method to call this instruction three times and draw
the triangle(i.e. create a method drawLine() to draw lines and this
method is called repeatedly to achieve the needed task)
⚫ The idea of methods appears in all programming languages, although
sometimes it goes under the name functions and sometimes under
the name procedures.
⚫ The name methods is a throw-back to the language C++, from which
Java was developed.
⚫ In C++, there is an object called a class which can contain methods.
However, everything in Java is enclosed within a class .so the
functions within it are called methods
CLASSES
• Class is blue print or an idea of an Object
• From One class any number of Instances can be created
• It is an encapsulation of attributes and methods

class
FIGURE
Ob1 Ob3

CIRCLE Ob2 SQUARE


RECTANGLE
syntax of CLASS

class <ClassName>
{
attributes/variables;
Constructors();
methods();
}
INSTANCE
• Instance is an Object of a class which is an entity with its own
attribute values and methods.

• Creating an Instance

ClassName refVariable;
refVariable = new Constructor();
or
ClassName refVariable = new Constructor();
Java Class Hierarchy
• In Java, class “Object” is the base class to all other classes
– If we do not explicitly say extends in a new class definition,
it implicitly extends Object

– The tree of classes that extend from Object and all of its
subclasses are is called the class hierarchy

– All classes eventually lead back up to Object

– This will enable consistent access of objects of different


classes.
Inheritance
⚫ Methods allows to reuse a sequence of statements

⚫ Inheritance allows to reuse classes by deriving a new class


from an existing one

⚫ The existing class is called the parent class, or superclass, or


base class

⚫ The derived class is called the child class or subclass.

⚫ The child class inherits characteristics of the parent class(i.e


the child class inherits the methods and data defined for the
parent class
Inheritance
⚫ Inheritance relationships are often shown graphically
in a class diagram, with the arrow pointing to the
parent class

Animal
weight : int

+ getWeight() : int

Bird

+ fly() : void
Method Overriding.
 There may be some occasions when we want an object to
respond to the same method but have different behavior
when that method is called.
 That means, we should override the method defined in the
super class. This is possible by defining a method in a sub class
that has the same name, same arguments and same return
type as a method in the super class.
 Then when that method is called, the method defined in the
sub class is invoked and executed instead of the one in the
super class. This is known as overriding.
Exceptions in Java
• Exception is an abnormal condition that arises in the code
sequence.
• Exceptions occur during compile time or run time.
• “throwable” is the super class in exception hierarchy.
• Compile time errors occurs due to incorrect syntax.
• Run-time errors happen when
– User enters incorrect input
– Resource is not available (ex. file)
– Logic error (bug) that was not fixed
Abstraction in Object-Oriented Programming
Procedural Abstraction
• Procedural Abstractions organize instructions.

Function Power
Give me two numbers (base & exponent)
I’ll return baseexponent

Implementation
Data Abstraction
• Data Abstractions organize data.

StudentType

Name (string)

Marks (num)

Grade (char)

Student Number (num)


Data Types

⚫Java defines eight simple types:


1)byte – 8-bit integer type
2)short – 16-bit integer type 3)int
– 32-bit integer type 4)long – 64-
bit integer type
5)float – 32-bit floating-point type
6)double – 64-bit floating-point type
7)char – symbols in a character set
8)boolean – logical values true and false
Variable Declaration
⚫ We can declare several variables at the same time:
type identifier [=value][, identifier [=value] …];
Examples:
int a, b, c;
int d = 3, e, f = 5;
byte g = 22;
double pi = 3.14159;
char ch = 'x';

L 2.4
Variable Scope
⚫ Scope determines the visibility of program elements with respect
to other program elements.
⚫ In Java, scope is defined separately for classes and methods:
1) variables defined by a class have a global scope
2) variables defined by a method have a local scope
A scope is defined by a block:
{

}
A variabledeclared inside the scope is not visible outside:
{
int n;
}
n = 1;// this is illegal
Arrays
⚫ An array is a group of liked-typed variables referred to by
a common
⚫ name, with individual variables accessed by their index.
⚫ Arrays are:
1) declared
2) created
3) initialized
4) used
⚫ Also, arrays can have one or several dimensions.
Array Declaration

⚫Array declaration involves:


1) declaring an array identifier
2) declaring the number of dimensions
3) declaring the data type of the array elements
⚫Two styles of array declaration:
type array-variable[];
or
type [] array-variable;

L 2.8
Array Creation
⚫After declaration, no array actually exists.
⚫In order to create an array, we use the new
operator:
type array-variable[];
array-variable = new type[size];
⚫This creates a new array to hold size elements of
type type, which reference will be kept in the
variable array-variable.
Array Indexing

⚫ Later we can refer to the elements of this array through


their indexes:
⚫ array-variable[index]
⚫ The array index always starts with zero!
⚫ The Java run-time system makes sure that all array
indexes are in the correct range, otherwise raises a run-
time error.
Array Initialization

⚫ Arrays can be initialized when they are declared:


⚫ int monthDays[] = {31,28,31,30,31,30,31,31,30,31,30,31};
⚫ Note:
1) there is no need to use the new operator
2)the array is created large enough to hold all specified
elements
Operators Types

⚫Java operators are used to build value expressions.


⚫Java provides a rich set of operators:
1) assignment
2) arithmetic
3) relational
4) logical
5) bitwise

L 2.13
Arithmetic assignments
+= v += expr; v = v + expr ;

-= v -=expr; v = v - expr ;

*= v *= expr; v = v * expr ;

/= v /= expr; v = v / expr ;

%= v %= expr; v = v % expr ;
Basic Arithmetic Operators
+ op1 + op2 ADD

- op1 - op2 SUBSTRACT

* op1 * op2 MULTIPLY

/ op1 / op2 DIVISION

% op1 % op2 REMAINDER

L 2.15
Relational operator
== Equals to Apply to any type

!= Not equals to Apply to any type

> Greater than Apply to numerical type

< Less than Apply to numerical type

>= Greater than or equal Apply to numerical type

<= Less than or equal Apply to numerical type


Logical operators
& op1 & op2 Logical AND

| op1 | op2 Logical OR

&& op1 && op2 Short-circuit


AND
|| op1 || op2 Short-circuit OR

! ! op Logical NOT

^ op1 ^ op2 Logical XOR


L 2.17
Selection Statements

⚫Java selection statements allow to control the flow


of program’s execution based upon conditions
known only during run-time.
⚫Java provides four selection statements:
1) if
2) if-else
3) if-else-if
4) switch
Iteration Statements
⚫ Java iteration statements enable repeated execution of
part of a program until a certain termination condition
becomes true.
⚫ Java provides three iteration statements:
1) while
2) do-while
3) for

L 3.3
Jump Statements

⚫ Java jump statements enable transfer of control to


other parts of program.
⚫ Java provides three jump statements:
1) break
2) continue
3) return
⚫ In addition, Java supports exception handling that can
also alter the control f low of a program.
Simple Java Program

⚫ A class to display a simple message:


class MyProgram
{
public static void main(String[] args)
{
System.out.println(“First Java program.");
}
}
What is an Object?

⚫Real world objects are things that have:


1) state
2)behavior
Example: your dog:
⚫state – name, color, breed, sits?, barks?, wages
tail?, runs?
⚫behavior – sitting, barking, waging tail, running
⚫A software object is a bundle of variables (state)
and methods (operations).
What is a Class?

⚫ A class is a blueprint that defines the variables and


methods common to all objects of a certain kind.
⚫ Example: ‘your dog’ is a object of the class Dog.
⚫ An object holds values for the variables defines in the
class.
⚫ An object is called an instance of the Class

L 4.3
Object Creation

⚫A variable is declared to refer to the objects of


type/class String:
String s;
⚫The value of s is null; it does not yet refer to any
object.
⚫A new String object is created in memory with
initial “abc” value:
⚫String s = new String(“abc”);
⚫Now s contains the address of this new object.
Object Destruction

⚫ A program accumulates memory through its


execution.
⚫ Two mechanism to free memory that is no longer need
by the program:
1) manual – done in C/C++
2) automatic – done in Java
⚫ In Java, when an object is no longer accessible through
any variable, it is eventually removed from the
memory by the garbage collector.
⚫ Garbage collector is parts of the Java Run-Time
Environment.

L 4.5
Class

⚫ A basis for the Java language.


⚫ Each concept we wish to describe in Java must be
included inside a class.
⚫ A class defines a new data type, whose values are
objects:
⚫ A class is a template for objects
⚫ An object is an instance of a class
Class Definition

⚫ A class contains a name, several variable declarations


(instance variables) and several method declarations. All
are called members of the class.
⚫ General form of a class:
class classname {
type instance-variable-1;

type instance-variable-n;
type method-name-1(parameter-list) { … }
type method-name-2(parameter-list) { … }

type method-name-m(parameter-list) { … }
}

L 4.7
Example: Class Usage
class Box {
double width;
double height;
double depth;
}
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println ("Volume is " + vol);
} }
Constructor
⚫ A constructor initializes the instance variables of an object.
⚫ It is called immediately after the object is created but before
the new operator completes.
1) it is syntactically similar to a method:
2) it has the same name as the name of its class
3)it is written without return type; the default
return type of a class
⚫ constructor is the same classWhen the class has no
constructor, the default constructor automatically initializes
all its instance variables with zero.
Example: Constructor

class Box {
double width;
double height;
double depth;
Box() {
System.out.println("Constructing Box");
width = 10; height = 10; depth = 10;
}
doublevolume() {
return width * height * depth;
}
}

L 5.2
Parameterized Constructor
class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
double volume()
{ return width * height * depth;
}
}
Methods

⚫ General form of a method definition:


type name(parameter-list) {
… return value;

}
⚫ Components:
1)type - type of values returned by the method. If a method
does not return any value, its return type must be void.
2) name is the name of the method
3) parameter-list is a sequence of type-identifier lists
separated by commas
4) return value indicates what value is returned by the
method.

L 5.4
Example: Method

⚫Classes declare methods to hide their internal data


structures, as well as for their own internal use: Within a
class, we can refer directly to its member variables:
class Box {
double width, height, depth;
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
Parameterized Method

⚫Parameters increasegenerality and applicability of


a method:
⚫1) method without parameters
int square() { return 10*10; }
⚫2) method with parameters
int square(int i) { return i*i; }
⚫Parameter: a variable receiving value at the time
the method is invoked.
⚫Argument: a value passed to the method when it is
invoked.

L 5.6
Access Control: Data Hiding and
Encapsulation
• Java provides control over the visibility of variables
and methods.
• Encapsulation, safely sealing data within the capsule
of the class Prevents programmers from relying on
details of class implementation, so you can update
without worry
• Helps in protecting against accidental or wrong
usage.
• Keeps code elegant and clean (easier to maintain)
Access Modifiers: Public, Private,
Protected
• Public: keyword applied to a class, makes it
available/visible everywhere. Applied to a
method or variable, completely visible.
• Default(No visibility modifier is specified): it
behaves like public in its package and private
in other packages.
• Default Public keyword applied to a class,
makes it available/visible everywhere.
Applied to a method or variable, completely
visible.

L 6.2
⚫ Private fields or methods for a class only visible within
that class. Private members are not visible within
subclasses, and are not inherited.
⚫ Protected members of a class are visible within the
class, subclasses and also within all classes that are in
the same package as that class.
Visibility
public class Circle {
private double x,y,r;

// Constructor
public Circle (double x, double y, double r) {
this.x = x;
this.y = y;
this.r = r;
}
//Methods to return circumference and area
public double circumference() { return 2*3.14*r;}
public double area() { return 3.14 * r * r; }
}
L 6.4
String Handling
⚫String is probably the most commonly used class in
Java's class library. The obvious reason for this is that
strings are a very important part of programming.
⚫The first thing to understand about strings is that
every string you create is actually an object of type
String. Even string constants are actually String
objects.
⚫For example, in the statement
System.out.println("This is a String, too");
the string "This is a String, too" is a String constant
⚫ Java defines one operator for String objects: +.
⚫ It is used to concatenate two strings. For example, this
statement
⚫ String myString = "I" + " like " + "Java.";
results in myString containing
"I like Java."

L 8.4
⚫ The String class contains several methods that you can use.
Here are a few. You can
⚫ test two strings for equality by using
equals( ). You can obtain the length of a string by calling the
length( ) method. You can obtain the character at a specified
index within a string by calling charAt( ). The general forms
of these three methods are shown here:
⚫ // Demonstrating some String methods.
class StringDemo2 {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1;
System.out.println("Length of strOb1: " +
strOb1.length());
System.out.println ("Char at index 3 in strOb1: " +
strOb1.charAt(3));
if(strOb1.equals(strOb2))

System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");
if(strOb1.equals(strOb3))
System.out.println("strOb1 == strOb3");
else
System.out.println("strOb1 != strOb3");
}}

This program generates the following output:


Length of strOb1: 12
Char at index 3 in strOb1: s
strOb1 != strOb2
strOb1 == strOb3
Inheritance
⚫ Methods allows a software developer to reuse a sequence of
statements
⚫ Inheritance allows a software developer to reuse classes by
deriving a new class from an existing one
⚫ The existing class is called the parent class, or superclass,
or base class
⚫ The derived class is called the child class or subclass.
⚫ As the name implies, the child inherits characteristics of
the parent
⚫ That is, the child class inherits the methods and data
defined for the parent class

107
I⚫nInhheerirtaintcae nrelcateionships are often shown
graphically in a class diagram, with the arrow
pointing to the parent class

Animal
weight : int
Inheritance
+ getWeight() : int should create an
is-a relationship,
meaning the
Bird child is a more
specific version
of the parent
+ fly() : void
108
Deriving Subclasses
⚫ In Java, we use the reserved word extends to establish an
inheritance relationship
class Animal
{
// class contents
int weight;
public void int getWeight() {…}
}

class Bird extends Animal


{
// class contents
public void fly() {…};
}

109
Class Hierarchy
⚫ A child class of one parent can be the parent of another
child, forming class hierarchies

Animal

Reptile Bird Mammal

Snake Lizard Parrot Horse Bat

 At the top of the hierarchy there’s a default class


called Object. 110
Class Hierarchy
⚫ Good class design puts all common features as high in the
hierarchy as reasonable
⚫ inheritance is transitive
⚫ An instance of class Parrot is also an instance of Bird, an instance of
Animal, …, and an instance of class Object
⚫ The class hierarchy determines how methods are executed:
⚫ Previously, we took the simplified view that when variable v is an
instance of class C, then a procedure call v.proc1() invokes the
method proc1() defined in class C
⚫ However, if C is a child of some superclass C’ (and hence v is both
an instance of C and an instance of C’), the picture becomes more
complex, because methods of class C can override the methods of
class C’ (next two slides).

111
Defining Methods in the Child Class:
Overriding by Replacement
⚫ A child class can override the definition of an inherited method in
favor of its own
⚫ that is, a child can redefine a method that it inherits from its parent
⚫ the new method must have the same signature as the parent's method,
but can have different code in the body

⚫ In java, all methods except of constructors override the methods of


their ancestor class by replacement. E.g.:
⚫ the Animal class has method eat()
⚫ the Bird class has method eat() and Bird extends Animal
⚫ variable b is of class Bird, i.e. Bird b = …
⚫ b.eat() simply invokes the eat() method of the Bird class

⚫ If a method is declared with the final modifier, it cannot be


overridden

112
Defining Methods in the Child Class:
Overriding by Refinement
⚫ Constructors in a subclass override the definition of an inherited constructor
method by refining them (instead of replacing them)
- Assume class Animal has constructors
Animal(), Animal(int weight), Animal(int weight, int livespan)
- Assume class Bird which extends Animal has constructors
Bird(), Bird(int weight), Bird(int weight, int livespan)

- Let’s say we createa Bird object, e.g. Bird b = Bird(5)


- This will invoke first the constructorof the Animal (the superclass of Bird) and
then the constructorof the Bird

⚫ This is called constructor chaining: If class C0 extends C1 and C1 extends C2


and … Cn-1 extends Cn = Object then when creating an instance of object C0
first constructor of Cn is invoked, then constructors of Cn-1, …, C2, C1, and
finally the constructorof C
- The constructors (in each case) arechosen by their signature, e.g. (), (int), etc…
- If no constructor with matching signature is found in any of the class Ci for i>0 then the
default constructor is executed for that class
- If no constructor with matching signature is found in the class C0 then this causes a
compiler errorFirst the new method must have the same signature as the parent's method,
but can have different code in the body

113
Recap: Class Hierarchy
⚫ In Java, a class can extend a single other class
(If none is stated then it implicitly extends an Object class)
Animal

Reptile Bird Mammal

Snake Lizard Parrot Horse Bat

 Imagine what would happen to method handling


rules if every class could extend two others…
(Answer: It would create multiple problems!) 114
Hierarchical Abstraction
⚫ An essential element of object-oriented programming is
abstraction.

⚫ Humans manage complexity through abstraction. For


example, people do not think of a car as a set of tens of
thousands of individual parts. They think of it as a well-
defined object with its own unique behavior.

⚫ This abstraction allows people to use a car without being


overwhelmed by the complexity of the parts that form the
car. They can ignore the details of how the engine,
transmission, and braking systems work.

⚫ Instead they are free to utilize the object as a whole.


Class Hierarchy
⚫ A child class of one parent can be the parent of another
child, forming class hierarchies

Animal

Reptile Bird Mammal

Snake Lizard Parrot Horse Bat

 At the top of the hierarchy there’s a default class called Object.


Class Hierarchy
⚫ Good class design puts all common features as high in
the hierarchy as reasonable

⚫ The class hierarchy determines how methods are


executed

⚫ inheritance is transitive
⚫ An instance of class Parrot is also an instance of Bird,
an instance of Animal, …, and an instance of class
Object
Base Class Object
⚫ In Java, all classes use inheritance.
⚫ If no parent class is specified explicitly, the base class Object is
implicitly inherited.
⚫ All classes defined in Java, is a child of Object class, which provides
minimal functionality guaranteed to e common to all objects.
⚫ Methods defined in Object class are;
1. equals(Object obj): Determine whether the argument object is the
same as the receiver.
2. getClass(): Returns the class of the receiver, an object of type Class.
3. hashCode(): Returns a hash value for this object. Should be
overridden when the equals method is changed.
4. toString(): Converts object into a string value. This method is also
often overridden.
Base class
1) a class obtains variables and methods from another class
2) the former is called subclass, the latter super-class (Base class)
3)a sub-class provides a specialized behavior with respect to its
super-class
4)inheritance facilitates code reuse and avoids duplication of
data
Extends
 Is a keyword used to inherit a class from another class
 Allows to extend f rom only one class
class One class Two extends One

{ int a=5; {

} int b=10;
}
Subclass, Subtype and Substitutability
⚫ A subtype is a class that satisfies the principle of
substitutability.
⚫ A subclass is something constructed using inheritance,
whether or not it satisfies the principle of substitutability.
⚫ The two concepts are independent. Not all subclasses are
subtypes, and (at least in some languages) you can
construct subtypes that are not subclasses.
⚫ Substitutability is fundamental to many of the powerful
software development techniques in OOP.
⚫ The idea is that, declared a variable in one type may hold
the value of different type.
⚫ Substitutability can occur through use of inheritance,
whether using extends, or using implements keywords.
Subclass, Subtype, and Substitutability
When new classes are constructed using inheritance, the argument
used to justify the validity of substitutability is as follows;
• Instances of the subclass must possess all data fields associated
with its parent class.
•Instances of the subclass must implement, through inheritance
at least, all functionality defined for parent class. (Defining new
methods is not important for the argument.)
•Thus, an instance of a child class can mimic the behavior of the
parent class and should be indistinguishable from an instance of
parent class if substituted in a similar situation.
Subclass, Subtype, and
Substitutability
The term subtype is used to describe the relationship between
types that explicitly recognizes the principle of substitution. A type
B is considered to be a subtype of A if an instances of B can legally
be assigned to a variable declared as of type A.
The term subclass refers to inheritance mechanism made by
extends keyword.
 Not all subclasses are subtypes. Subtypes can also be formed
using interface, linking types that have no inheritance relationship.
Subclass
⚫ Methods allows to reuse a sequenceof statements

⚫ Inheritance allows to reuse classes by deriving a new class from


an existing one

⚫ The existing class is called the parent class, or superclass, or base


class

⚫ The derived class is called the child class or subclass.

⚫ As the name implies, the child inherits characteristics of the


parent(i.e the child class inherits the methods and data defined
for the parentclass
Subtype
⚫ Inheritance relationships are often shown graphically in
a class diagram, with the arrow pointing to the parent
class
Animal
weight : int

+ getWeight() : int

Bird

+ fly() : void
Substitutability (Deriving Subclasses)
⚫ In Java, we use the reserved word extends to establish an
inheritance relationship

class Animal
{
// class contents
int weight;
public void int getWeight() {…}
}

class Bird extends Animal


{
// class contents
public void fly() {…};
}
Defining Methods in the Child Class:
Overriding by Replacement
⚫ A child class can override the definition of an inherited method in
favorof its own
⚫ that is, a child can redefine a method that it inherits from its parent
⚫ the new method must have the same signature as the parent's
method, but can have different code in the body

⚫ In java, all methods except of constructorsoverridethe methods


of theirancestorclass by replacement. E.g.:
⚫ the Animal class has method eat()
⚫ the Bird class has method eat() and Bird extends Animal
⚫ variable b is of class Bird, i.e. Bird b = …
⚫ b.eat() simply invokes the eat() method of the Bird class

⚫ If a method is declared with the final modifier, it cannot be


overridden
Construction
⚫ The parent class is used only for its behavior, the child class
has no is-a relationship to the parent.
⚫ Child modify the arguments or names of methods

⚫ An example might be subclassing the idea of a Set from an
existing List class.
⚫ Child class is not a more specialized form of parent class;
no substitutability
Forms of Inheritance
(- Inheritance for Extension -)
Subclassification for extension occurs when a child class only
adds new behavior to the parent class and does not modify or
alter any of the inherited attributes.
Such subclasses are always subtypes, and substitutability can be
used.
Example of this type of inheritance is done in the definition of
the class Properties which is an extension of the class HashTable.
Generalization or Extension
⚫ The child class generalizes or extends the parent class by
providing more functionality
⚫ In some sense, opposite of subclassing for specialization
⚫ The child doesn't change anything inherited from the
parent, it simply adds new features
⚫ Often used when we cannot modify existing base parent
class
⚫ Example, ColoredWindow inheriting from Window
⚫ Add additional data fields
⚫ Override window display methods
The Benefits of Inheritance
⚫ Software Reusability (among projects)
⚫ Increased Reliability (resulting from reuse and sharing
of well-tested code)
⚫ Code Sharing (within a project)
⚫ Consistency of Interface (among related objects)
⚫ Software Components
⚫ Rapid Prototyping (quickly assemble from pre-existing
components)
⚫ Polymorphism and Frameworks (high-level reusable
components)
⚫ Information Hiding
The Costs of Inheritance
⚫ Execution Speed

⚫ Program Size

⚫ Message-Passing Overhead

⚫ Program Complexity (in overuse of inheritance)


Types of inheritance
 Acquiring the properties of an existing Object into newly
creating Object to overcome the re-declaration of
properties in deferent classes.
 These are 3 types:
1.Simple Inheritance

SUPER SUPER

extends extends

SUB SUB 1 SUB 2


2. Multi Level 3. Multiple
Inheritance Inheritance
SUPER 1
SUPER SUPER 2

implement
extends
s
SUPER 1 SUPER 2
SUB
SUB
extends implement
extends
s

SUB SUB SUB


The protected Modifier
⚫ The protected visibility modifier allows a member of a base
class to be accessed in the child
⚫ protected visibility provides more encapsulation than
public does
⚫ protected visibility is not as tightly encapsulated as
private visibility

Book
protected int pages
+ getPages() : int
+ setPages(): void

Dictionary

+ getDefinitions() : int
+ setDefinitions(): void
+ computeRatios() : double
“super” uses
 ‘super’ is a keyword used to refer to hidden variables of super
class from sub class.
 super.a=a;

 It is used to call a constructor of super class from constructor of


sub class which should be first statement.
 super(a,b);

 It is used to call a super class method from sub class method to


avoid redundancy of code
 super.addNumbers(a, b);
Super and Hiding
⚫ Why is super needed to access super-class members?
⚫ When a sub-class declares the variables or methods with
the same names and types as its super-class:
class A {
int i = 1;
}
class B extends A {
int i = 2;
System.out.println(“i is “ + i);
}
⚫ The re-declared variables/methods hide those of the
super-class.
Example: Super and Hiding
class A {
int i;
}
class B extends A {
int i;
B(int a, int b) {
super.i = a; i = b;
}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
Example: Super and Hiding
⚫ Although the i variable in B hides the i variable in A,
super allows access to the hidden variable of the
super-class:
class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
subOb.show();
}
}
Polymorphism
⚫ Polymorphism is one of three pillars of object-
orientation.

⚫ Polymorphism: many different (poly) forms of objects


that share a common interface respond differently when
a method of that interface is invoked:
1) a super-class defines the common interface

2) sub-classes have to follow this interface


(inheritance), but are also permitted to provide their
own implementations (overriding)
⚫ A sub-class provides a specialized behaviors relying on
the common elements defined by its super-class.
Polymorphism
⚫ A polymorphic reference can refer to different types of
objects at different times
⚫ In java every reference can be polymorphicexcept of
references to base types and final classes.

⚫ It is the type of the object being referenced, not the


reference type, that determineswhich method is invoked
⚫ Polymorphicreferences are therefore resolved at run-
time, not during compilation; this is called dynamic
binding

⚫ Careful use of polymorphicreferences can lead to elegant,


robust software designs
Method Overriding

⚫ When a method of a sub-class has the same name


and type as a method of the super-class, we say that
this method is overridden.

⚫ When an overridden method is called from within


the sub-class:
1) it will always refer to the sub-class method

2) super-class method is hidden


Example: Hiding with Overriding 1
class A {
int i, j;
A(int a, int b) {
i = a; j = b;
}
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
Example: Hiding with Overriding 2
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() {
System.out.println("k: " + k);
}
}
Example: Hiding with Overriding 3
⚫ When show() is invoked on an object of type B,
the version of show() defined in B is used:
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show();
}
}
⚫ The version of show() in A is hidden through
overriding.
Overloading vs. Overriding
⚫ Overloading deals with ⚫ Overriding deals with two
multiple methods in the methods, one in a parent
same class with the same class and one in a child
name but different class, that have the same
signatures signature
⚫ Overloading lets you
define a similar operation o Overriding lets you define a
in different ways for similar operation in
different data different ways for different
object types

You might also like