0% found this document useful (0 votes)
7 views37 pages

presentation8(1)

The document covers key concepts in Object-Oriented Programming (OOP) including the use of the 'instanceof' operator, abstract classes, interfaces, type casting, composition, and polymorphism in Java. It explains how these concepts facilitate code organization and reusability through inheritance and abstraction. Examples are provided to illustrate the implementation and usage of these concepts in Java programming.

Uploaded by

kakefon876
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views37 pages

presentation8(1)

The document covers key concepts in Object-Oriented Programming (OOP) including the use of the 'instanceof' operator, abstract classes, interfaces, type casting, composition, and polymorphism in Java. It explains how these concepts facilitate code organization and reusability through inheritance and abstraction. Examples are provided to illustrate the implementation and usage of these concepts in Java programming.

Uploaded by

kakefon876
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

IT 214

Object
Oriented
Programming
Dr. Abdulaziz Saleh Algablan
[email protected] :Email
2024

1
Topics
Instanceof
Abstract Classes
Interfaces
Type Casting
Composition
Polymorphism
2
instanceof
• The java instanceof operator is used to test whether the object is an
instance of the specified type (class or subclass).
• The instanceof in java is also known as type comparison operator
because it compares the instance with type.
• It returns either true or false.

3
instanceof
class Simple1{

public static void main(String args[]){


Simple1 s = new Simple1();
System.out.println(s instanceof Simple1); //true
}
}

4
instanceof
class Animal{} // super class
class Horse extends Animal{ } //Horse inherits Animal
// Test class
public class TestInstanceOf{
public static void main(String[] args){
Horse instance_1 =new Horse();
Horse instance_2 =null;
Animal instance_3 = new Animal();
Animal instance_4 =new Horse();

System.out.println(instance_1 instanceof Animal);//case 1: true

System.out.println(instance_1 instanceof Horse);// case 2: true

System.out.println(instance_2 instanceof Horse ); // case 3: false

System.out.println(instance_3 instanceof Horse);// case 4: false

System.out.println(instance_4 instanceof Horse);// case 5: true


} } 5
instanceof
• Instanceof focus on the object in the heap memory.
• An object of subclass type is also instanceof a type of parent class.
• instanceof operator returns true for case 1 in the previous example.
• instanceof operator returns false with a variable containing null value
(case 3).
• instanceof operator returns false with a variable containing object that
is:
• Not equal to the type specified after instanceof (case 4).
• The instanceof operator works on the principle of the is-a relationship.

6
Abstract Classes
• When we think of a class, we assume there will be objects of that
type.
• Sometimes it’s useful to declare classes(called abstract classes) for
which you never intend to create objects.
• They’re used only as superclasses in inheritance hierarchy.
• These classes cannot be used to instantiate objects, because abstract
classes are incomplete.
• At opposite, classes that are be used to instantiate objects are called
concrete classes.

7
Abstract Classes
• You make a class abstract by declaring it with keyword abstract.
abstract class AbstractClassExampe { }
• An abstract class normally contains one or more abstract methods.
• An abstract class can include:
• Attributes
• Constructors !!!?

8
Abstract Classes and Methods
• An abstract method is one with keyword abstract in its declaration as:
public abstract void draw(); // abstract method
• The abstract method does not have body. No curly brackets after parameters.
• Example:
abstract class Shape {
public abstract void draw();
}
class Circle extends Shape {
void draw() {
//method body
}
}
9
Abstract Classes and Methods
abstract class Shape {
public abstract void draw();
public String getClassName() {return “Shape”;}
}
class Circle extends Shape {
void draw() {}
}
• When a concreate-subclass extends an abstract class, all abstract
methods in the abstract subclass must be implemented in the
concrete class.
• Failure to implement a superclass’s abstract methods in a subclass is a
compilation error
10 unless the subclass is also declared abstract.
Concrete subclass extends abstract
class

A concrete-subclass
“ConcreateAbstractChild”
extends the class abstract
class “Shape” but it does
not implement draw()
method. 11
Goal of Abstract Classes and
Methods
• An abstract class’s purpose is to provide an appropriate superclass
from which other classes can inherit and thus share a common
design.

12
Using Abstract Classes to Declare
Variables
abstract class Shape {
public abstract void draw();
}
public class TestShape {
public static void main(String[] arg)
{
Shape aShape = new Shape(); // This causes ERROR.
}
}
• We cannot instantiate objects of abstract superclasses.
• But, we can use abstract superclasses to declare variables that can hold references to objects
of any concrete class derived from those abstract superclasse.
13
Using Abstract Classes to Declare
Variables
abstract class Shape {
public abstract void draw();
}
class Circle extends Shape {
void draw() {}
}
public class TestShape {
public static void main(String[] arg)
{
Shape aShape = new Circle(); // This OK.
}
}
14
Using Abstract Classes to Declare
Variables
• We cannot instantiate objects of abstract superclasses.
• But we can declare a variable type of an abstract class.
• An abstract class is not required to have an abstract method in it.
• Declaring a class as abstract only means that it can not be instantiated.

15
Abstract Class Example
• A good example is the Animal class, which can be used to represent
different kinds of animals, such as dogs, cats, birds, etc.
• The Animal class can have an abstract method called makeSound()
• It defines how the animal makes a sound
• But does not provide any specific code for it.
• Each subclass of Animal, such as Dog, Cat, Bird, etc., must override
the makeSound() method and provide the code for making the
sound according to the animal’s characteristics.
• The Animal class can also have some concrete methods, such as
eat(), sleep(), move(), etc., which can be inherited by the
subclasses without any modification.

16
Java Interfaces
• A Java interface describes a set of methods that can be called on an
object to tell it, for example, to perform some task or return some
piece of information.
• An interface declaration begins with the keyword interface and
contains only constants and abstract methods.
• Unlike classes, all interface members must be public, and interfaces
may not specify any implementation details, such as concrete method
declarations and instance variables.

17
Java Interfaces
• In its most common form, an interface is a group of related
methods with empty bodies.

18
Bicycle Interface Example
interface Bicycle {
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
}

19
Bicycle Interface Example
interface Bicycle {
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
}

public class ConBicycle implements Bicycle {


@Override
public void changeGear(int newValue) {
}
@Override
public void speedUp(int increment) {
}
@Override
public void applyBrakes(int decrement) {
}
} 20
Interface Extending Multiple
Interfaces
• An interface can extend other interfaces
interface A { ... }
interface B { ... }
interface C extends A, B { ... }
• Rember:
• A class implement an interface
• An interface extend other interfaces

21
Interface Instantiation interface Bicycle {
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int
public class TestConBicycle { decrement);
}

public static void main(String[] args) {


Bicycle b1; // This is OK.
Bicycle b2 = new Bicycle(); // This causes ERROE
}

22
Interface Instantiation
public class TestConBicycle {

public static void main(String[] args) {


Bicycle b3 = new ConBicycle(); // This is
OK.
}

}
23
Interfaces in Java
• Interfaces achieve high abstraction.
• java does not support multiple inheritances in the case of class
inheritance
• by using an interface, it can achieve multiple inheritances indirectly.
• Any class can extend only 1 class but can any class implement infinite
number of interfaces.
• Interfaces is used to achieve loose coupling.

24
Multiple Implementation of
Interfaces
public interface ISpeak {
public interface Ithink {
public void talk();
} public void thinking();
class Phone implements ISpeak }
{
public void talk(){ }
}
class Human implements ISpeak, IThink
// The Human class implements two interfaces
{
public void talk(){ }
public void thinking(){. }
}
class Robot implements ISpeak
{
public void talk(){. }
}
25
Casting in Java
• Parent and Child objects are two types of objects.
• There are two types of typecasting possible for an object, i.e., Parent
to Child and Child to Parent (Upcasting and Downcasting).
• Typecasting is used to ensure whether variables are correctly
processed by a function or not.
• In Upcasting and Downcasting, we typecast a child object to a parent
object and a parent object to a child object simultaneously.
• We can perform Upcasting implicitly or explicitly, but downcasting
cannot be implicitly possible.

26
Casting in Java

27
Casting in Java

28
Casting Examples
class Vehicle implements Inter_1 { public interface Inter_1{

void m1(){ System.out.println("m1() in Vehicle");} void aMethod();

public void aMethod() {} }


}
class Car extends Vehicle{
void m2(){System.out.println("m2() in Car");}
}
public class TestCasting {
public static void main(String[] args) {
Vehicle c1 = new Vehicle();
Vehicle c2 = new Car();
c2.m2(); // This causes ERROR
((Car) c2).m2(); // This is OK due to down-casting
Inter_1 c3 = new Car();
c3.m1(); // This causes ERROR
((Vehicle) c3).m1(); // This causes down-casting
}
29
Composition
• Composition in java is the design technique to implement has-a
relationship in classes.
• Java composition is achieved by using instance variables that refers to
other objects.
• For example, a Person has a Job. Let’s see this with a java composition
example code.

30
Composition
public class Person {
//composition has-a relationship
private Job job;
public Person(){
this.job=new Job();
job.setSalary(1000L);
}
public long getSalary() {
return job.getSalary();
}

}
31
When to Use Composition
• In object-oriented programming, we can use composition in cases
where one object "has" (or is part of) another object.
• Some examples would be:
• A car has a battery (a battery is part of a car).
• A person has a heart (a heart is part of a person).
• A house has a living room (a living room is part of a house).

32
Composition
• The engine and car relationship are implemented using Java classes as
below.
Class Car
{
Engine carEngine;
}
• In Java, the ‘final’ keyword is used to represent composition. This is
because the ‘Owner’ object expects a part object to be available and
function by making it ‘final’.

33
Polymorphism
{ public class Shape
{ )(public void area
;System.out.println("This is the parent class and has no formula for the area. ")
}}
{ class Triangle extends Shape
{ )(public void area
;System.out.println("The formula for area of Triangle is ½ * base * height ")
}}
{ class Circle extends Shape
{ )(public void area
;System.out.println("The formula for area of Circle is 3.14 * radius * radius ")
}}

34
Polymorphism
public class PolymorephismShape {
public static void main(String[] args) {
Shape [] shapeArray = new Shape[3];
shapeArray[0] = new Shape(); // Create a general Shape object
shapeArray[1] = new Triangle(); // Create a Triangle object
shapeArray[2] = new Circle(); // Create a Circle object
for(Shape myShape :shapeArray )
{
myShape.area();
} This is the parent class and has no formula for the
area.
}} The formula for area of Triangle is ½ * base * height
35 The formula for area of Circle is 3.14 * radius *
radius
Polymorphism
• Polymorphism means "many forms", and it occurs when we have
many classes that are related to each other by inheritance .

• Inheritance lets us inherit attributes and methods from another class.

• Polymorphism uses those methods to perform different tasks. This


allows us to perform a single action in different ways.

36
End

37

You might also like