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

Chapter 4

Chapter 4 discusses object design and programming with Java, focusing on inheritance, which allows one class to acquire properties and methods from another class, promoting code reusability. It explains the use of the 'extends' keyword to establish parent-child relationships between classes, the types of inheritance (single, multilevel, hierarchical, and multiple), and the concept of method overriding. The chapter also covers encapsulation, polymorphism, and access control in Java, emphasizing the importance of these concepts in object-oriented programming.

Uploaded by

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

Chapter 4

Chapter 4 discusses object design and programming with Java, focusing on inheritance, which allows one class to acquire properties and methods from another class, promoting code reusability. It explains the use of the 'extends' keyword to establish parent-child relationships between classes, the types of inheritance (single, multilevel, hierarchical, and multiple), and the concept of method overriding. The chapter also covers encapsulation, polymorphism, and access control in Java, emphasizing the importance of these concepts in object-oriented programming.

Uploaded by

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

Chapter 4

4. Object Design and Programming with Java


4.1. Inheritance
 The process by which one class acquires the properties(data members)
and functionalities(methods) of another class is called inheritance.
 Inheritance aims to provide the reusability of code.
 It permits to creation of a general class that defines traits common to a
set of related items.
 This class can then be inherited by other, more specific classes, that
inherited class is called a superclass.
 The class that does the inheriting is called a subclass. Therefore,
 It inherits all of the instance variables and methods defined by the
1
Inheritance Basics

• To inherit a class, you simply incorporate the definition of one


class into another by using the extends keyword.

• 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.

2
Lookout the Following example

3
Cont.…
• The extended “extends” keyword in
Java programming is used to establish
inheritance between two classes.

• When a class uses extends, it means it is


inheriting (or "borrowing") properties and
methods from another class, called the parent or
superclass.

• This allows the new class, called the child or


subclass, to reuse existing code and add its
features. 4
Syntax Of extends keywords in Java

class Superclass {
………..// Fields and methods of the superclass
}
class Subclass extends Superclass {
……// Additional fields and methods of the subclass
}
Here
• Extends: It establishes an inheritance relationship
between two classes. Indicates that the subclass is
inheriting from the superclass.
• Superclass: The base class that provides common
features to be inherited.
• Subclass: The derived class that inherits from the
5
superclass using extends.
Cont.
// A simple example of inheritance.
// 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));
6
}}
Cont.

• The short form of a class declaration that inherits a


superclass is shown here:
class subclass-name extends superclass-name {
// body of class
}
• You can only specify one superclass for any subclass that you
create.
• Java does not support the inheritance of multiple super
classes into a single subclass.
• You can create a hierarchy of inheritance in which a subclass
7
becomes a superclass of another subclass.
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 private.

• For example, consider the following simple class

hierarchy:

8
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 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.println("Total is " + subOb.total); 9
A Superclass Variable Can Reference a Subclass Object

• A superclass reference variable can be assigned a


reference to any subclass derived from that superclass.

• A superclass reference can be used for any of its


subclass objects, but you cannot assign an object of the
parent class to the reference of its subclass.

• N.B, that when referring to objects with a superclass


reference you cannot invoke (call up) methods and
fields of a subclass.
10
class RefDemo {
public static void main(String args[]) {
BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37);
Box plainbox = new Box();
double vol;
vol = weightbox.volume();
System.out.println("Volume of weightbox is " + vol);
System.out.println("Weight of weightbox is “
+weightbox.weight);
System.out.println();
// assign BoxWeight reference to Box reference
plainbox = weightbox;
vol = plainbox.volume(); // OK, volume() defined in Box
System.out.println("Volume of plainbox is " + vol);
/* The following statement is invalid because plainbox
does not define a weight member. */
// System.out.println("Weight of plainbox is " + plainbox.weight);
}} 11
Cont.
• Here, weightbox is a reference to BoxWeight objects,
and plainbox is a reference to Box objects.

• Since BoxWeight is a subclass of Box, it is


permissible to assign plainbox a reference to the
weightbox object.

12
Using super

• super has two general forms.

• The first is called the superclass constructor.

• The second is used to access a member of the superclass that has been

hidden by a member of a subclass.


• Using Super to Call Superclass Constructors

• A subclass can call a constructor defined by its superclass by use of the

following form of super:

super(arg-list);
• Here, arg-list specifies any arguments needed by the constructor in the

superclass.
• super( ) must always be the first statement executed inside a subclass’
13
Cont.
// BoxWeight now uses super to initialise its Box
attributes.
class BoxWeight extends Box {
double weight; // weight of box
// initialize width, height, and depth using super()
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}}
14
Cont.
• Here, BoxWeight( ) calls super( ) with the arguments w,
h, and d.

• This causes the Box( ) constructor to be called, which


initializes width, height, and depth using these values.

• BoxWeight no longer initializes these values itself.

• It only needs to initialize the value unique to it: weight.

• This leaves Box free to make these values private if


desired.
15
Types of inheritance

• Single Inheritance: refers to a child and parent class


relationship where a class extends the another class.

16
Cont.
• Multilevel inheritance: refers to a child and parent class
relationship where a class extends the child class.

• For example class C extends class B and class B extends


class A.

17
Cont.
• Hierarchical inheritance: refers to a child and parent class
relationship where more than one classes extends the same
class.
• For example, classes B, C & D extends the same class A.

18
Cont.
• Multiple Inheritance: refers to the concept of one class
extending more than one classes, which means a child
class has two parent classes.

• For example class C extends both classes A and B.

19
When Constructors Are Called

• 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 parameter less


constructor of each superclass will be executed.

20
class A {
A() { // Constructor
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.");
}}
class CallingCons {
public static void main(String args[]) {
C c = new C();
21
}}
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 version of that
method defined by the subclass.

22
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
void show() {
System.out.println("i and j: " + i + " " + j);
}}
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);
}}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B 23
Cont.
• The output produced by this program is:
k: 3
• 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.
24
• This allows all instance variables to be displayed.
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);
}}
If you substitute this version of A into the previous
program, you will see the following output:
i and j: 1 2
k: 3
25
Overridden Methods

• Overridden methods allow Java to support run-time


polymorphism.

• Polymorphism allows a general class to specify methods


that will be common to all of its derivatives, while allowing
subclasses to define the specific implementation of some or
all of those methods.

• Overridden methods are another way that Java implements


the “one interface, multiple methods” aspect of
polymorphism. 26
Abstract Classes

• The general form to declare an abstract method is:

abstract type name(parameter-list);

• Any class that contains one or more abstract methods must also be
declared abstract.

• To declare a class abstract, you simply use the abstract keyword


in front of the class keyword at the beginning of the class
declaration.

• There can be no objects of an abstract class.

• That is, an abstract class cannot be directly instantiated with the


27
Any subclass of an abstract class must either implement all of the abstract
methods in the superclass, or be itself declared abstract.
// A Simple demonstration of abstract.

abstract class A {

abstract void callme();

// concrete methods are still allowed in abstract classes

void callmetoo() {

System.out.println("This is a concrete method.");

}}

class B extends A {

void callme() {

System.out.println("B's implementation of callme.");

}}

class AbstractDemo {

public static void main(String args[]) {

B b = new B();

b.callme();
28
b.callmetoo();
Polymorphism
• Polymorphism is one of the OOPs feature that allows us to perform a

single action in different ways.

• For example, lets say we have a class Animal that has a method sound().

• Since this is a generic class so we can’t give it a implementation like:

Roar, Meow, Oink etc. We had to give a generic message.

public class Animal{

...

public void sound(){

System.out.println("Animal is making a sound");


29
Cont.
• Now lets say we two subclasses of Animal
class: Horse and Cat that extends (Animal class.

• We can provide the implementation to the same method like this:

public class Horse extends Animal{

...

@Override

public void sound(){

System.out.println("Neigh");
30
}}
Cont.

and
public class Cat extends Animal{
...
@Override
public void sound(){
System.out.println("Meow");
}
}
31
Encapsulation
• Encapsulation is the wrapping up of data under a single unit.
• It is the mechanism that binds together code and the data it manipulates.
• It is a protective shield that prevents the data from being accessed by the
code outside this shield.
• To allow the outside access to the instance variables, public methods
called getters and setters are defined, which are used to retrieve and
modify the values of the instance variables, respectively.
• By using getters & setters, the class can enforce its own data
validation rules and ensure that its internal state remains consistent.
• Encapsulation links data with the code that manipulates it.
• Encapsulation provides an important attribute: access control.
• Through encapsulation, you can control what parts of a program can
32
access the members of a class.
Cont.

• By controlling access, you can prevent misuse.


• Java’s access specifiers are public, private, and protected.

• When a member of a class is modified by the public specifier,


then that member can be accessed by any other code.

• When a member of a class is specified as private, then that


member can not be accessed by other members of its class.

• Protected members can be accessed inside the class in which


they are declared and in the sub-classes in the same package
and sub-classes in the other packages. 33
public class Person {
// Encapsulating the name and age methods defined
Private String name;
Private int age;
Public String getName () {return name;}
Public void setName (String name) {this.name=name;}
Public int setAge() {return age;} {this.age = age;} }
//Driver class
Public class Main {
// main function
Public void main (String[] args) {
//person object created
person person = new person();
person.setName(“Chala”);
person.setAge(25);
//using methods to “get” the values from the variables
System.out.println(“Name:” + person.getName());
System.out.println(“Age:” + person.getAge()); 34
Summary
• Inheritance is a programming construct that software developers use

to establish is-a relationships between categories.

• A subclass (child class) inherits from the superclass and potentially adds its own

unique features.

• To call a superclass method from the overriding subclass method, prefix the method

name with the reserved word “super "and the member access operator.

• Java uses the extends that specifies a parent-child relationship b/n two classes.

• The extends keyword is specified after the class name and before another class name.

• The class name before extends identifies the child and the class name after extends

identifies the parent.

• It is impossible to specify multiple class name after extends, b/c java doesn’t support
35
THE END
THANK YOU !!!

36

You might also like