Object Oriented Thinking
Object Oriented Thinking
Object Oriented Thinking
UNIT – 5
Object Oriented Programming -I (3140705)
Class abstraction and Encapsulation, thinking in objects and class relationships, Primitive
data type and wrapper class types, Big integer and Big decimal class, string class, String
Builder and String Buffer class, super class and subclass, using super keyword, overriding
and overloading methods, polymorphism and dynamic binding, casting objects and
instanceof operator, The ArrayList class and its methods, The protected data and methods
Class Abstraction and Encapsulation
• Java provides many levels of abstraction, and class abstraction
separates class implementation from how the class is used.
• The creator of a class describes the functions of the class and lets
the user know how the class can be used.
• The collection of methods and fields that are accessible from
outside the class, together with the description of how these
members are expected to behave, serves as the class’s contract.
• As shown in Figure, the user of the class does not need to know
how the class is implemented. The details of implementation are
encapsulated and hidden from the user. This is called class
encapsulation.
2
Cont’d
• Class abstraction is the separation of class implementation
from the use of a class.
• The details of implementation are encapsulated and hidden
from the user. This is known as class encapsulation.
• Class abstraction and encapsulation are two sides of the same
coin.
Encapsulation
Inheritance
Polymorphism
Abstraction
3
4
Class Relationships
• Association
– Association is a general binary relationship that describes an activity
between two classes.
5
Class Relationships – Contd…
• Aggregation and Composition
– Aggregation is a special form of association that represents an ownership
relationship between two objects.
– Aggregation models has-a relationships. The owner object is called an
aggregating object, and its class is called an aggregating class. The subject
object is called an aggregated object, and its class is called an aggregated
class.
– An object can be owned by several other aggregating objects. If an object is
exclusively owned by an aggregating object, the relationship between the
object and its aggregating object is referred to as a composition.
6
Primitive data types and wrapper class
• A Wrapper class is a class whose object wraps or contains
primitive data types.
• When we create an object to a wrapper class, it contains a field
and in this field, we can store primitive data types.
• The wrapper class in Java provides the mechanism to convert
primitive into object and object into primitive.
• Autoboxing and unboxing feature convert primitives into
objects and objects into primitives automatically.
• The automatic conversion of primitive into an object is known
as autoboxing and object to primitive is known as unboxing.
7
Need for wrapper class
• Change the value in Method: Java supports only call by value. So, if we
pass a primitive value, it will not change the original value. But, if we
convert the primitive value in an object, it will change the original value.
• Serialization: We need to convert the objects into streams to perform the
serialization. If we have a primitive value, we can convert it in objects
through the wrapper classes.
• Synchronization: Java synchronization works with objects in
Multithreading.
• java.util package: The java.util package provides the utility classes to deal
with objects.
• Collection Framework: Java collection framework works with objects
only. All classes of the collection framework (ArrayList, LinkedList,
Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque,
etc.) deal with objects only.
8
Eight classes of the java.lang package
known as wrapper classes
9
Example: convert primitive into objects
1. // Java program to convert primitive into objects
2. // Autoboxing example of int to Integer
10
Example: Unboxing
1. // Java program to convert object into primitives
2. // Unboxing example of Integer to int
11
BigInteger Class in Java
• BigInteger class is used for mathematical operation which involves very big integer
calculations that are outside the limit of all available primitive data types.
• For example factorial of 100 contains 158 digits in it so we can’t store it in any
primitive data type available.
• We can store as large Integer as we want in it. There is no theoretical limit on the
upper bound of the range because memory is allocated dynamically but practically
as memory is limited you can store a number which has Integer.
import java.math.BigInteger; import java.util.Scanner;
public class Example
{
static BigInteger factorial(int N) {
BigInteger f = new BigInteger("1"); // Or BigInteger.ONE
for (int i = 2; i <= N; i++)
f = f.multiply(BigInteger.valueOf(i));
return f;
}
public static void main(String args[]) throws Exception {
int N = 20;
System.out.println(factorial(N));
}
} 12
BigDecimal Class in Java
• Java includes a BigDecimal class for performing high-precision arithmetic
which can be used in banking or financial domain based application.
import java.math.BigDecimal;
public class BigDecimalDemo {
public static void main(String[] argv) {
System.out.println("--- Normal Print-----");
System.out.println(2.00 - 1.1); System.out.println(2.00 - 1.2);
System.out.println(2.00 - 1.3); System.out.println(2.00 - 1.4);
System.out.println(2.00 - 1.5); System.out.println(2.00 - 1.6);
System.out.println(2.00 - 1.7);
System.out.println("--- BigDecimal Usage Print---");
System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.1")));
System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.2")));
System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.3")));
System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.4")));
System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.5")));
System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.6")));
System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.7")));
BigDecimal bd1 = new BigDecimal ("1234.34567");
bd1= bd1.setScale (3, BigDecimal.ROUND_CEILING);
System.out.println(bd1);
}}
13
The String Class
• A String object is immutable: Its content cannot be changed
once the string is created.
• The String class has 13 constructors and more than 40
methods for manipulating strings.
• Constructing a String
1. String message = new String("Welcome to Java");
2. String message = "Welcome to Java";
3. char[] charArray = {'G', 'o', 'o', 'd', ' ', 'D', 'a', 'y'};
String message = new String(charArray);
14
Why String Objects are Immutable in Java and Its Benefits
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
System.out.println(s5);
System.out.println(s6);
}
} 16
// This program demonstrates the length, charAt and getChars methods of the String
class (Note: Java Swing is not in syllabus)
import javax.swing.*;
public class string2 {
public static void main( String args[] ) {
String s1 = "hello there";
char charArray[] = new char[ 5 ];
s1 == s2 is false
s1 == s3 is true
s2 == s3 is false
18
Replacing and Splitting Strings
Replace:
"Welcome".replace('e', 'A') returns a new string, WAlcomA.
"Welcome".replaceFirst("e", "AB") returns a new string, WABlcome.
"Welcome".replace("e", "AB") returns a new string, WABlcomAB.
"Welcome".replace("el", "AB") returns a new string, WABcome.
Split:
String[] tokens = "Java#HTML#Perl".split("#");
for (int i = 0; i < tokens.length; i++)
System.out.print (tokens[i] + " ");
19
Matching, Replacing and Splitting by Patterns
System.out.println("Java".matches("Java")); True
"Java".equals("Java"); True
"440-02-4534".matches("\\d{3}-\\d{2}-\\d{4}") True
20
Conversion between Strings and Arrays
Strings are not arrays, but a string can be converted into an array, and vice
versa.
char[] chars = "Java".toCharArray(); //chars[0] is now J…
char[] dst = {'J', 'A', 'V', 'A', '1', '3', '0', '1'};
"CS3720".getChars(2, 6, dst, 4);
//2,6 means 2nd to 6-1st , dst array and 4 means from 4th character.
System.out.println (dst);
Output: JAVA3720
21
StringBuffer class
• Java StringBuffer class is used to create mutable (modifiable)
string.
• The StringBuffer class in java is same as String class except it
is mutable i.e. it can be changed.
• Important Constructors of StringBuffer class
Constructor Description
StringBuffer() creates an empty string buffer with the initial capacity
of 16.
StringBuffer(String str) creates a string buffer with the specified string.
StringBuffer(int capacity) creates an empty string buffer with the specified
capacity as length.
22
Examples
StringBuffer append() method
1.class StringBufferExample{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);
6. }
7.} Hello Java
23
Examples
StringBuffer replace() method
1.class StringBufferExample3{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);
6. }
7.} HJavalo
1.class StringBufferExample4{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);
6. }
7.}
Hlo
24
Examples
StringBuffer reverse() method
1.class StringBufferExample5{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.reverse();
5. System.out.println(sb);//prints olleH
6. }
7.}
Constructor Description
StringBuilder() creates an empty string Builder with the initial
capacity of 16.
StringBuilder(String str) creates a string Builder with the specified string.
StringBuilder(int length) creates an empty string Builder with the specified
capacity as length.
26
Java StringBuilder Examples
• StringBuilder append() method
1.class StringBuilderExample{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7.}
29