Object Oriented Thinking

Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

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

The Four Principles of Object-


Oriented-Programming (OOP)

Encapsulation
Inheritance
Polymorphism

Abstraction
3
4
Class Relationships
• Association
– Association is a general binary relationship that describes an activity
between two classes.

– This UML diagram shows that


• a student may take any number of courses,
• a faculty member may teach at most three courses,
• a course may have from five to sixty students,
• and a course is taught by only one faculty member.

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

Primitive Type Wrapper class


boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double

9
Example: convert primitive into objects
1. // Java program to convert primitive into objects
2. // Autoboxing example of int to Integer

3. public class WrapperExample1{


4. public static void main(String args[]){
5. //Converting int into Integer
6. int a=20;
7. Integer i = Integer.valueOf(a); //converting int into Integer explicitly
8. Integer j = a; //autoboxing, now compiler use Integer.valueOf(a) internally
9.
10. System.out.println(a + " " + i + " " + j);
11. }
12. }

10
Example: Unboxing
1. // Java program to convert object into primitives
2. // Unboxing example of Integer to int

3. public class WrapperExample2{


4. public static void main(String args[]){
5. //Converting Integer to int
6. Integer a = new Integer(3);
7. int i = a.intValue(); //converting Integer to int explicitly
8. int j = a; //unboxing, now compiler use a.intValue() internally
9. System.out.println(a + " " + i + " " + j);
10. }
11. }

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

String s1 = "Hello"; // String literal


String s2 = "Hello"; // String literal
String s3 = s1; // same reference

• Strings in Java are specified as immutable, as seen above because strings


with the same content share storage in a single pool to minimize creating a
copy of the same value.
• That is to say, once a String is generated, its content cannot be changed and
hence changing content will lead to the creation of a new String.
15
// String class constructors
public class stringConstructors {
public static void main( String args[] ) {
char charArray[] = { 'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y' };
byte byteArray[] = { ( byte ) 'n', ( byte ) 'e', ( byte ) 'w', ( byte ) ' ',
( byte ) 'y', ( byte ) 'e', ( byte ) 'a', ( byte ) 'r' };

String s = new String( "hello" );


// use String constructors
String s1 = new String( );
String s2 = new String( s );
String s3 = new String( charArray );
String s4 = new String( charArray, 6, 3 ); //offset, count
String s5 = new String( byteArray, 4, 4 ); //offset, length
String s6 = new String( byteArray );

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 ];

String output = "s1: " + s1;

// test length method


output += "\nLength of s1: " + s1.length();
// loop through characters in s1 and display reversed
output += "\nThe string reversed is: ";

for ( int count = s1.length() - 1; count >= 0; count-- )


output += s1.charAt( count ) + " ";
// copy characters from string into charArray
s1.getChars( 0, 5, charArray, 0 );

output += "\nThe character array is: ";


for ( int count = 0; count < charArray.length; count++ )
output += charArray[ count ];

JOptionPane.showMessageDialog( null, output, "String class character manipulation


methods", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
} 17
interned string
• Because strings are immutable, the JVM uses a unique
instance for string literals with the same character sequence in
order to improve efficiency and save memory.

• Such an instance is called an interned string.

String s1 = "Welcome to Java";


String s2 = new String("Welcome to Java");
String s3 = "Welcome to Java";
System.out.println("s1 == s2 is " + (s1 == s2));
System.out.println("s1 == s3 is " + (s1 == s3));

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] + " ");

Java HTML Perl

19
Matching, Replacing and Splitting by Patterns
System.out.println("Java".matches("Java")); True

"Java".equals("Java"); True

"Java is fun".matches("Java.*") True


"Java is cool".matches("Java.*") True
"Java is powerful".matches("Java.*") True

"440-02-4534".matches("\\d{3}-\\d{2}-\\d{4}") True

String s = "a+b$#c".replaceAll("[$+#]", "NNN"); ?

String[] tokens = "Java,C?C#,C++".split("[.,:;?]");


for (int i = 0; i < tokens.length; i++)
System.out.println(tokens[i]);
Java C C# C++

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

To convert an array of characters into a string, use the String(char[])


constructor or the valueOf(char[]) method.
String str = new String(new char[] {'J', 'a', 'v', 'a'});
String str = String.valueOf(new char[] {'J', 'a', 'v', 'a'});

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

StringBuffer insert() method


1.class StringBufferExample2{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);
6. }
7.} HJavaello

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

StringBuffer delete() method

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

StringBuffer capacity() method


1.class StringBufferExample6{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity()); //now (16*2)+2=34 i.e (oldcapacity*2)+2
9. }
10.}
25
StringBuilder class
• Java StringBuilder class is used to create mutable (modifiable)
string.
• The Java StringBuilder class is same as StringBuffer class
except that it is non-synchronized. It is available since JDK
1.5.
• Important Constructors of StringBuilder class

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

• StringBuilder insert() method


1.class StringBuilderExample2{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
7.}
27
• StringBuilder replace() method
1.class StringBuilderExample3{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7.}

• StringBuilder delete() method


1.class StringBuilderExample4{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
7.}
28
• StringBuilder reverse() method
1.class StringBuilderExample5{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.reverse();
5. System.out.println(sb); //prints olleH
6. } }

• StringBuilder capacity() method


1.class StringBuilderExample6{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder();
4. System.out.println(sb.capacity()); //default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity()); //now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity()); //now (16*2)+2=34 i.e (oldcapacity*2)+2
9.} }

29

You might also like