0% found this document useful (0 votes)
22 views33 pages

5 Lecture5

Java oop lecture 5

Uploaded by

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

5 Lecture5

Java oop lecture 5

Uploaded by

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

Object-Oriented Programming

Lecture5: Classes - Objects


• Abstract class
• Type Wrapper classes for primitive
types
• Autoboxing and Auto Unboxing
• Recursion
Definition of Abstraction

• Abstraction is the process of hiding the complex


details of a system and showing only the essential
parts.
• The goal of abstraction is to simplify working with
the system or code by removing unnecessary details
and focusing on the important aspects.
Purpose of Abstraction
The purpose of abstraction is:
• Simplifying Complexity: By hiding
unnecessary details and focusing on the
essential parts.
• Improving Maintenance: Abstracted code is
easier to maintain and develop because it
focuses on what is important.
• Reusability: Abstracted code can be used in
different contexts without needing to modify
the internal details.
Abstract classes and Methods

• An abstract class is a class that is defined with the keyword
`abstract` to indicate that it is abstract.
• This means that you cannot create an object directly from this
class. Instead, it must be inherited by another class. At least
one subclass must implement the abstract methods in the
abstract class.
• An abstract class can contain both abstract methods (methods
without a body) and concrete methods (methods with a body).
If a class has even one abstract method, it must be defined as
an abstract class.
The general form of an abstract class definition:

Programmatically, we can create the abstract class in the same


way as the full class Prefixed with the keyword abstract as:

abstract Accessmodifier Abstract_class_name


{
......
}
example
abstract public Animal
{
}
abstract class
abstract class Shape {
String color; The class cannot be instantiated
on its own. It must be subclassed.

// Constructor
public Shape(String color) {
this.color = color; Assigns the passed color to
} the class's color field.

// Abstract method (no body)


public abstract double area();

// Concrete method
public String getColor() { In this example, Shape is an abstract class with an
return color; abstract method area() and a concrete method
} getColor().
} ‫باقي المثال في نهاية شرح‬
abstract
• They are functions that are defined using the keyword abstract
within abstract classes.
• They contain only the header of the function, and cannot
contain the body of the function. Their definition ends with a
semicolon. Just as an abstract class must have at least one
child class, an abstract function must It must be duplicated in
the abstract class (the parent class) and the child class derived
from it, so that it is in abstract form in the abstract class (the
parent class) and in non-abstract form in the non-abstract class
(the child class).
Abstract Class with Abstract Method

abstract class Animal {


// Abstract method (no body)
public abstract void makeSound();

// Concrete method
public void sleep() {
System.out.println("This animal is sleeping.");
}
} In this example, Animal is an abstract class
with an abstract method makeSound() and a
concrete method sleep().
Subclass Implementing the Abstract Method
class Dog extends Animal {
// Implementing the abstract method
@Override
public void makeSound() {
System.out.println("Woof");
}
}

class Cat extends Animal {


// Implementing the abstract method
@Override
public void makeSound() {
System.out.println("Meow");
}
}
Here, Dog and Cat are subclasses of Animal. They provide their
own implementations of the makeSound() method.
Cont..
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();

myDog.makeSound(); // Outputs: Woof


myDog.sleep(); // Outputs: This animal is sleeping.

myCat.makeSound(); // Outputs: Meow


myCat.sleep(); // Outputs: This animal is sleeping.
}
}
Cont…
Explanation:
1.Abstract Class (Animal):
•Contains an abstract method makeSound() that does
not have a body.
•Contains a concrete method sleep() that does have a
body.
2.Subclasses (Dog, Cat):
•Extend the Animal class.
•Provide concrete implementations of the makeSound()
method.
3.Main Class:
•Demonstrates creating instances of Dog and Cat.
•Calls the makeSound() and sleep() methods to show
how abstract and concrete methods work together.
abstract class
abstract class Shape {
String color; The class cannot be instantiated
on its own. It must be subclassed.

// Constructor
public Shape(String color) {
this.color = color; Assigns the passed color to
} the class's color field.

// Abstract method (no body)


public abstract double area();

// Concrete method
public String getColor() {
return color;
In this example, Shape is an abstract class with an
} abstract method area() and a concrete method
} getColor().
create subclasses that provide implementations for the area() method

public class Circle extends Shape { public class Rectangle extends Shape {
double radius; double width;
double height;
Circle ‫هي دالة بناء‬constructor
Rectangle ‫هي دالة بناء‬constructor
public Circle(String color, double radius) public Rectangle(String color, double
{ width, double height) {
super(color); // Call the constructor of super(color); // Call the constructor of
the Shape class the Shape class
this.radius = radius; this.width = width;
} this.height = height;
}

@Override @Override
public double area() { public double area() {
return Math.PI * radius * radius; return width * height;
} }
}
}
Main
public class Main {
public static void main(String[] args) {
Shape circle = new Circle("Red", 5);
System.out.println("Circle color: " + circle.getColor());
System.out.println("Circle area: " + circle.area());

Shape rectangle = new Rectangle("Blue", 4, 6);


System.out.println("Rectangle color: " + rectangle.getColor());
System.out.println("Rectangle area: " + rectangle.area());
}
}
output
Circle color: Red
Circle area: 78.53981633974483
Rectangle color: Blue
Rectangle area: 24.0
Importance of Abstract Classes
1. Code Reusability: Abstract classes allow you to define methods that
can be shared by all subclasses, reducing code duplication.
2. Polymorphism: Abstract classes enable polymorphic behaviour. You
can use abstract classes as types and use method overriding, allowing
the same method to behave differently in different contexts.
3. Encapsulation: Abstract classes can encapsulate common
functionality, ensuring that all subclasses have a consistent interface
while hiding the implementation details.
4. Inheritance: They provide a way to enforce a contract for subclasses.
Subclasses must provide implementations for the abstract methods
defined in the abstract class.
5. Partial Implementation: They allow you to provide partial
implementation. You can define some methods with actual code and
leave others as abstract, which subclasses must implement.
Type Wrapper classes for primitive types
In Java, type wrapper classes are used to convert primitive data
types into objects.
This is particularly useful when working with collection classes
in Java, like ArrayList, which can only store objects and not
primitive types. Each primitive data type has a corresponding
wrapper class in the java.lang package.
These features make the code cleaner and more readable,
reducing the need for manual conversions.
The wrapper classes for each primitive type:
Cont…….
The eight wrapper classes in Java are:

Integer: Wraps a value of the primitive type int.


Double: Wraps a value of the primitive type double.
Float: Wraps a value of the primitive type float.
Long: Wraps a value of the primitive type long.
Short: Wraps a value of the primitive type short.
Byte: Wraps a value of the primitive type byte.
Boolean: Wraps a value of the primitive type boolean.
Character: Wraps a value of the primitive type char.
Key Features of Wrapper Classes

1. Conversion between Primitives and Objects:


Wrapper classes provide methods to convert primitive types
to corresponding objects (boxing) and vice versa
(unboxing).
o Example:
int num = 10; // 'int' is a keyword for the
primitive data type, 'num' is a variable name
Integer numObject = Integer.valueOf(num); //
'Integer' is a wrapper class, 'valueOf' is a
method for boxing
int numPrimitive = numObject.intValue(); //
'intValue' is a method for unboxing,
'numPrimitive' is a variable name
Cont…
• numObject is a reference to an Integer object.
• Integer.valueOf(num) is a static method that returns an Integer object
representing the specified int value (num).
• This process is called boxing, where a primitive type (int) is converted
into a corresponding wrapper class object (Integer).

• numPrimitive is a primitive int.


• numObject.intValue() is an instance method of the Integer class that
returns the value of the Integer object as a primitive int.
• This process is called unboxing, where a wrapper class object (Integer) is
converted back to its corresponding primitive type (int).
More explain Autoboxing and Auto Unboxing

Autoboxing and Auto-Unboxing are features


introduced in Java 5 that simplify the interaction
between primitive data types and their
corresponding wrapper classes.
Autoboxing in Java is the Java compiler’s automatic
conversion between the primitive data types (like int, char,
etc.) and their corresponding object wrapper classes (Integer,
Character, etc.).
When a primitive data type is assigned (=) to a variable of the
corresponding wrapper class, Java automatically converts the
primitive type into the corresponding wrapper class object.
Cont…….
Auto unboxing is the reverse process of autoboxing. It is
the automatic conversion that the Java compiler makes from the
wrapper class object back to the corresponding primitive data
type.
When a wrapper class object is assigned to a variable of the
corresponding primitive type, Java automatically converts the
wrapper class object back into the primitive type.
Cont..
2. Utility Methods:
Wrapper classes provide utility methods for parsing ‫ لتحليل‬strings into
primitive types, comparing values, and more.
o Example:
String str = "123";
int num = Integer.parseInt(str);
// Parsing string to int

This line declares a variable num of type int and initializes it with the
result of the method call Integer.parseInt(str).
Integer is a wrapper class in Java that provides utility methods for
working with int values.
parseInt is a static method of the Integer class that converts a String to
an int.
str is passed as an argument to Integer.parseInt, which converts the
string "123" to the integer 123.
The result of Integer.parseInt(str) is assigned to the num variable, so
num now holds the integer value 123.
Cont…
3. Constants:
o Wrapper classes provide useful constants like
MAX_VALUE, MIN_VALUE to represent the maximum
and minimum values a primitive type can hold.
o Example:
• int maxInt = Integer.MAX_VALUE;
4. Immutability:
o Wrapper class objects are immutable, meaning once
they are created, their value cannot be changed.
5. Type Conversion: Cont..
o Wrapper classes provide methods to convert one type to another.
o Example:
double d = 10.5;
Double dObj = Double.valueOf(d);
int intValue = dObj.intValue();
Exploitation:
Double dObj = Double.valueOf(d);
Here, we are using the Double wrapper class to create an object dObj from
the primitive double value d.
Double.valueOf(d) is a method that returns a Double object holding the
value of the primitive double d.
This is an example of boxing, where a primitive type is converted into its
corresponding wrapper class object.
int intValue = dObj.intValue();

This line calls the intValue() method on the Double object dObj to convert
it back to a primitive int.
The intValue() method returns the value of the Double object as an int,
effectively performing an unboxing operation.
Since 10.5 is not an integer, this conversion will truncate the decimal part,
resulting in intValue being 10.
practical example that demonstrates the usage of wrapper classes:
import java.util.ArrayList;

public class WrapperClassExample {


public static void main(String[] args) {
// Primitive types
int primitiveInt = 5;
double primitiveDouble = 5.65; The valueOf method
returns an Integer
// Boxing: Converting primitives to wrapper objects instance representing
Integer wrappedInt = Integer.valueOf(primitiveInt); the specified int value.
This method is often
Double wrappedDouble = Double.valueOf(primitiveDouble);
used for converting a
// Unboxing: Converting wrapper objects to primitives primitive int to an
int unboxedInt = wrappedInt.intValue(); Integer object.
double unboxedDouble = wrappedDouble.doubleValue();

intValue(): This is a method of the Integer class. The intValue method


returns the value of the Integer object as a primitive int.
Cont…
// Auto-boxing and auto-unboxing
intList.add(10); // Auto-boxing: primitive int to Integer object
int num = intList.get(1); // Auto-unboxing: Integer object to primitive int

// Output values
System.out.println("Primitive int: " + primitiveInt);
System.out.println("Wrapped Integer: " + wrappedInt);
System.out.println("Unboxed int: " + unboxedInt);
System.out.println("Primitive double: " + primitiveDouble);
System.out.println("Wrapped Double: " + wrappedDouble);
Output:
System.out.println("Unboxed double: " + unboxedDouble); Primitive int: 5
} Wrapped Integer: 5
} Unboxed int: 5
Primitive double: 5.65
Wrapped Double: 5.65
Unboxed double: 5.65
‫ لتوضيح‬explain
Integer wrappedInt = Integer.valueOf(primitiveInt);:
‫توضيح معنى كل كلمة‬
1. Integer: This is a class in Java. It is part of the java.lang package and is
used to wrap a value of the primitive type int in an object. An object of type
Integer contains a single field whose type is int.
2. wrappedInt: This is a variable name. In this case, it is a reference
variable that will hold a reference to an Integer object. The name is chosen to
indicate that it will hold a wrapped primitive int value.
3. =: This is the assignment operator. It assigns the value on its right to the
variable on its left.
4. Integer.valueOf: This is a static method of the Integer class. The valueOf
method returns an Integer instance representing the specified int value. This
method is often used for converting a primitive int to an Integer object.
5. primitiveInt: This is a variable name that holds a primitive int value. It is
used as an argument to the valueOf method to create an Integer object that
represents this primitive int value.
Recursion in Java

Recursion in Java is a process where a


method calls itself continuously.
This technique solves problems by breaking
them into smaller, more manageable sub-
problems of the same type.
.‫هي عملية تستدعي فيها الطريقة نفسها بشكل مستمر‬Java ‫العودية في‬
‫تعمل هذه التقنية على حل المشكالت عن طريق تقسيمها إلى مشكالت فرعية‬
.‫أصغر وأكثر قابلية لإلدارة من نفس النوع‬
Cont…….
A recursive function typically has two main
components:
Base Case: This is the condition under which the
recursive function stops calling itself. Without a base
case, the function would continue to call itself
indefinitely, leading to a stack overflow error.
Recursive Case: This is the part of the function
where it calls itself with a modified argument,
gradually approaching the base case.
Cont…….
Explanation of Recursion with an Example

Consider a classic example of recursion:


Calculating the factorial of a number.
The factorial of a non-negative integer n is the product
of all positive integers less than or equal to n. It's
denoted by n!.
Mathematically:
•0!=1(Base Case)
•n!=n×(n−1)! (Recursive Case for n>0 )
Example The output of code :
A factorial of 5 is: 120
public class Factorial {
5*4*3*2*1=120
// Recursive method to calculate factorial
public static int factorial(int n) {
// Base case: when n is 0
if (n == 0) {
return 1; }
// Recursive case: n * factorial of (n - 1)
return n * factorial(n - 1); }
public static void main(String[] args) {
// Example usage
int number = 5;
int result = factorial(number);
System.out.println("Factorial of " + number + " is: " +
result); } }
Cont……
Explanation
Here’s a step-by-step breakdown of how the factorial of 5 is calculated using
recursion:
Initial Call: factorial(5) is called.
Recursive Calls:
factorial(5) calls factorial(4)
factorial(4) calls factorial(3)
factorial(3) calls factorial(2)
factorial(2) calls factorial(1)
factorial(1) calls factorial(0)
Base Case: factorial(0) returns 1 (base case).
Unwinding: Each recursive call returns to its caller:
factorial(1) returns 1 * 1 = 1
factorial(2) returns 2 * 1 = 2
factorial(3) returns 3 * 2 = 6
factorial(4) returns 4 * 6 = 24
factorial(5) returns 5 * 24 = 120
Thus, when the code System.out.println("Factorial of " + number + " is: " +
result); is executed, it prints Factorial of 5 is: 120

You might also like