You are on page 1of 59

Object Oriented Programming and

Design Pattern
Mayur V. Shrirame
(mayurshrirame@gmail.com)

Birla Institute of Technology, Mesra


Source: Google Images Ranchi
OOP Concepts or Java
If You Then You
don’t love don’t deserve
me at me at
OOP
JAVA
Concepts

Source: Google Images


1) Abstraction

• Hiding background details or explanations

Source: Google Images


2) Encapsulation=Data hiding + Abstraction

• Wrapping up of data and methods into a single


unit (called class) is known as Encapsulation.

Source: Google Images


3) Inheritance

• Reusability

Source: Google Images


4) Polymorphism

• eatBurger(void);

• eatBurger(withCoke);

• eatBurger(withSnacks);

• Ability to take more than one form.

Source: Google Images


How to
Features of Java remember
these 8 terms ?

 Simple
 Object Oriented language
 Distributed
 Interpreted
 Robust & Secure
 Portable
 Multi-threaded
 Garbage Collection

Source: Google Images


Installation
 Download and install jdk from oracle official website or DC++.

1) Right click on This PC (My Computer).


2) Click on Properties.
 Set Environment variables.
3) Head over to Advanced System Settings.
4) Click on Environment Variables.
5) Under System Variables, edit PATH variable,
add java path
 Done. C:\Program Files\Java\jdk_1.x\bin
Compile & Run

JDK
Sample Sample
.java javac.exe .class

JRE
OS
Sample JIT
.class Compiler

• JIT Compiler is platform-dependent, however it provides platform


independent java file.
First Java Code
1) Class name starts with a
capital letter.

class SampleData
1) public keyword is used so that every
{ class can access main() function.
public static void main(String[] args) 2) static keyword is used because we are
{ not accessing it with object reference.
3) String[] args is an array of string used for
command line arguments.
System.out.println (“Java language is easy”);

}
1) System is a predefined class name.
2) out is a static reference variable of System
class.
} 3) println() is a function to print desired
output.
Predefined Keywords

Source: Google Images


Datatypes & Default Values

 boolean (implementation dependent) (False)


 char (2 bytes) (null character ‘\0’)
 byte (1 byte) (0)
 short (2 bytes) (0)
 int (4 bytes) (0)
 long (8 bytes) (0L)
 float (4 bytes) (0.0f)
 double (8 bytes) (0.0d)

Source: Google Images


TypeCasting
int c=4;
• This is known as widening.
float b=c; • #No error.

float a=3.2f; • This is known as narrowing. double


int b=a; • #Error.

Narrowing
Widening
float

long
• Error is removed.
float a=3.2f • But data is lost.
int b=(int)a; • ‘b’ value will be 3. int

short
float f=3.5; ------ //error
float f=3.5f; ----- //no error byte
Command Line Arguments
You must
public class Dog follow my
{ orders….

public static void main(String[] args)


{
for(int i=0; i<args.length; i++)
{ Yes, I will follow
System.out.println (args[i]); your orders if and
only if your java file
}
is error free.
}
}

Source: Google Images


Variables & their Scopes
 Instance Variables Hiee all, I am an Instance Variable. My
 Class Variables scope is inside a class. You can use me
when you are able to create an object.
 Local Variables To access me, write
Object-name.variable-name;

Hey, I am a Class Variable. My I am a Local Variable.


scope is global to a class. Use me My legs are weak now.
without creating any object. To You can use me inside
access me, write function only. My scope
Class-name.static-variable-name; is inside a block.

Source: Google Images


Variables & their Scopes (Contd…)

public class Dog


{
String name="PUG"; //instance variable
static int noOfEar=2; //class variable a.k.a static variable
public static void main(String[] args)
{
Dog d1= new Dog();
int sleepHours=3; // Local Variable
System.out.println(sleepHours);
System.out.println(Dog.noOfEar);
System.out.println(d1.name);
}
}
Classes & Objects
Wo JAVA padhne ke liye classes & objects padhna zaroori hai kya ?

Source: Google Images


Classes & Objects Stack
Heap

public class Dog breed=Labrador;


age=6;
{
public String breed; Heap Area
public static int noOfLegs=4;
noOfLegs
int age; ...
public static void main(String[] args)
noOfEar=2 Method Area
{
Dog d1=new Dog(); d1 Native Area
d1.breed=“Labrador”;
1) Stack is for local variables, heap is for objects.
d1.age=6;
int noOfEar=2; 2) Objects are stored onto heap because of large memory
System.out.println space.

("The age of " + d1.breed +" is " + d1.age); 3) Stack is faster for accessing local variables.
}
4) Variables stored onto heap are accessible to whole class
}
whereas variables stored onto stack are accessible to
respective method only.
Static Keyword
Variable Method

• To declare any method as static, specify static


• To declare any variable as static, write static keyword.
keyword.
• Static variable belongs to class rather than object of a
• Static method belongs to class rather than object of
class.
a class.
• To access, use class-name.variable-name.
• To access, use Class-name.method-name.
• Memory Efficient.
• Static method can access only static variables.
collegeName=“BIT”;
Class A
{
id=201; int a=20; //non-static variable
Name=“xyz”; static int b=30; //static variable
public static void main(String[] args)
{
id=202; System.out.println(a); //Compile Time Error
S2 Name=“abc”;
System.out.println(b); //Value of b is printed
S1 }
Stack Memory }
Heap Memory
Constructors
public class Dog
{ Default Constructor
public String breed;
public static int noOfLegs = 4; Parameterized Constructor
int age;
public Dog(String breedName, int ageInYears)
{
this.breed = breedName;
this.age = ageInYears;
} 1) Constructor is used to initialize objects.
public static void main(String[] args)
{ 2) Constructor is called when object is
Dog d1=new Dog(“Labrador”, 4);
created.
d1.breed=“Labrador”;
3) Constructor name must be same as class
d1.age=6;
name.
int noOfEar = 2;
System.out.println 4) Constructor doesn’t have a return type.
("The age of " + d1.breed +" is " + d1.age);
}
}
Inheritance

Class A

Class B Class C

Single Inheritance Hierarchical Inheritance


Class D
Class A Class A
Multi-Level Inheritance Hybrid Inheritance

Class A Class B Class C


Class B

Class B

 Multiple inheritance is not supported in java through class.


Class C
1

2
Output

4
Simple Inheritance

class Employee{
float salary=40000;
}

class Programmer extends Employee


{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();

System.out.println("Programmer salary is:"+p.salary);


System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
super Keyword
• The super keyword in java is a reference variable which is used to refer immediate class object.
• Whenever we create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
• It can be used to refer immediate parent class instance variable.
• Super can be used to invoke immediate parent class method.
• It is used to invoke immediate parent class constructor.
class Dog extends Animal{
Dog()
{
super();
class Animal
System.out.println("dog is created");
{
}
Animal()
}
{
class TestSuper3
System.out.println("animal is created");}
{
}
public static void main(String args[])
void eat()
{
{
Dog d=new Dog();
System.out.println(“Animal is eating”);
super.eat();
}
}
}
Method Overloading vs Method Overriding
Overloading Overriding

• Method overloading only occurs in same class. • Method overriding occurs in different class.

• It is called as compile time polymorphism. • It is called as runtime polymorphism.

• A method is overloaded when it has same • A method is said to be overridden when it has
method name and same return type but same name, same parameter list and same return
different parameters. type.

• There are two ways to overload a method :-


• Using number of parameters.
• By changing the datatype of parameters.
Function Overloading Overloading
with datatype
class FunOverload Overloading class FunOverload of arguments
{ with no. of {
int length, breadth; parameters
void area(int l, int b)
{
void area(int l, int b)
int area=0; {
this.length=l; System.out.println("Area of rectangle is: "+(l*b));
this.breadth=b; }
area=this.length*this.breadth;
System.out.println("Area of rectangle is: "+area); void area(float l, float b)
} {
void area(int l)
System.out.println("Area of rectangle is: "+(l*b));
{ }
this.length=l;
int area=this.length*this.length; public static void main(String[] args)
System.out.println("Area of square is: "+area); {
} FunOverload rectangle=new FunOverload();
rectangle.area(4,5);
public static void main(String[] args)
{
rectangle.area(4.5f,5.2f);
FunOverload rectangle=new FunOverload(); }
rectangle.area(4,5); }
FunOverload square=new FunOverload();
square.area(5);
}
} Source: Google Images
Method Overriding

class Vehicle
{

void run()
{
System.out.println("Vehicle is running");}
}

class Bike2 extends Vehicle


{

void run()
{
System.out.println("Bike is running safely");
}
public static void main(String args[])
{
Bike2 obj = new Bike2();
obj.run();
}
}
Source: Google Images
final Keyword
class Child extends Parent
{
class Parent void area(int l, int b)
{ {
final int length=4; System.out.println("Area of rectangle is: "+(l*b));
final void area(int l, int b) }
{ public static void main(String[] args)
System.out.println("Area of rectangle is: "+(l*b)); {
} Parent rectangle=new Child();
} rectangle.area(4,5);
Rectangle.length=5;
}
}

C:\Users\Mayur\Documents>javac Child.java C:\Users\Mayur\Documents>javac Child.java


Child.java:24: error: cannot assign a value to final variable
Child.java:14: error: area(int,int) in Child cannot override
area(int,int) in Parent
length
void area(int l, int b) rectangle.length=5;
^ ^
overridden method is final 1 error
1 error
Aggregation (has-a relationship)

3
4
Upcasting & Downcasting
instanceof Operator
class Dog
{
public static void main(String[] args)
{
Dog d1 = new Dog();
if ( d1 instanceof Dog)
{ • In java, instanceof operator is used to check
System.out.println("Yes it’s working"); the type of an object at runtime.
}
} • instanceof operator returns Boolean value, if
} an object reference is of specified type then it
returns true otherwise false.
Output:-
Yes it’s working
class Try
{
public void add()
{ Downcasting
int c=0;
System.out.println(c);
}

}
public class Try1 extends Try
{
public static void main(String[] args)
{
Try1 t1 = (Try1) new Try();
t1.add();
}
}

C:\Users\Mayur\Documents\Java>java Try1
Exception in thread "main" java.lang.ClassCastException: Try cannot be
cast to Try1
at Try1.main(Try1.java:15)
Access Modifiers

Package 1 Package 2

Rule of Thumb:-
1) Use public if the field is to be visible everywhere.
2) Use protected if the field is to be visible everywhere in the current package and also
subclasses in other packages.
3) Use default if the field is to be visible everywhere inside package only.
4) Use private if the field is not to be visible anywhere except in its own class.

Source: Google Images


package Java;
package Java;
public class Test1
public class Test1
{
{
protected String name="BIT";
protected String name="BIT";
}
}
package Java; package Documents;
import Java.Test1; import Java.Test1;

public class Test public class Test


{ {
public static void main(String[] args) public static void main(String[] args)
{ {
Test1 t1= new Test1(); Test1 t1= new Test1();
System.out.println(t1.name); System.out.println(t1.name);
} }
} }

C:\Users\Mayur\Documents>javac Java/Test.java C:\Users\Mayur\Documents>javac Test.java


Test.java:8: error: name has protected access in Test1
C:\Users\Mayur\Documents>java Java.Test System.out.println(t1.name);
BIT ^
1 error
Encapsulation

1 3

4
Arrays
datatype[] variable_name;
datatype []variable_name; Declaring an array
datatype variable_name[];

variable_name = new datatype[size]; Allocating memory in heap

class Student{
public static void main(String[] args)
{
int []studentArray = new int[5]; // declaring and allocating memory to array

studentArray[0]=12;
studentArray[1]=34;
studentArray[2]=45;
studentArray[3]=56;
studentArray[4]=67;

int []facultyArray = {98,45,23,45}; // facultyArray with 4 elements.

for(int i=0; i<studentArray.length; i++)


{
System.out.println(studentArray[i]);
}
}
}
Array of Objects
class Student{ class Main{
int roll_no; public static void main(String[] args){
String name;
Student(int roll, String name){ Student[] studentArray;
this.roll_no=roll; studentArray= new Student[5];
this.name=name;
} studentArray[0] = new Student(1011, “Amit”);
} studentArray[1] =new Student(1004, “Atish”);
studentArray[2] =new Student(1014, “Deepak”);
studentArray[3] =new Student(1021, “Ashish”);
studentArray[4] =new Student(1025, “Faizan”);

Output:- for(int i=0; i<studentArray.length; i++)


{
System.out.println(studentArray[i].roll_no
1011 Amit + “\t” + studentArray[i].name);
1004 Atish }
1014 Deepak }
1021 Ashish }
1025 Faizan
Passing Arrays to Methods

class Test
{
public static void main(String args[])
{
int arr[] = {3, 1, 2, 5, 4};
sum(arr);
}

public static void sum(int[] arr)


{
int sum = 0;
for (int i = 0; i < arr.length; i++)
sum=sum+arr[i];
System.out.println("sum of array values : " + sum);
}
}

Output:-

Sum of array values :15


Abstract Classes
1. Abstract classes are not Interfaces. They
are different, we will study this when we
will study Interfaces.

2. An abstract class may or may not have an


abstract method. But if any class has even
a single abstract method, then it must be
declared abstract.

3. Abstract classes can have Constructors,


Member variables and Normal methods.

4. Abstract classes are never instantiated.

5. When you extend Abstract class with


abstract method, you must define the
abstract method in the child class.

Source: Google Images


abstract class Try1
{
Abstract class Example
abstract void add();
public void multiply(int a, int b)
{
int c= a*b;
System.out.println(c);
}
}

public class Try extends Try1


{
public void add() Output
{
System.out.println("ADD Method called"); C:\Users\Mayur\Documents\Java>javac Try.java
} Try.java:19: error: Try1 is abstract; cannot be instantiated
public static void main(String[] args) Try1 t1 = new Try1();
{ ^
Try1 t1 = new Try1(); 1 1 error 1
t1.add();
t1.multiply(3,4);

C:\Users\Mayur\Documents\Java>javac Try.java
Try1 t2 = new Try();
t2.add(); 2 C:\Users\Mayur\Documents\Java>java Try
t2.multiply(4,5); ADD Method called
} 20 2
}
String and StringBuffer class
char charArray[] = new char[6];

charArray[0]= ‘F’;
charArray[1]= ‘R’;
charArray[2]= ‘I’;
charArray[3]= ‘E’;
charArray[4]= ‘N’;
charArray[5]= ‘D’;

• Why String and StringBuffer were introduced ?


- Copying one character array into another requires lot of book keeping effort.

• Java String is not a character array and is not NULL terminated.


• String objects are immutable. Immutable means once it is created, cannot be
altered.

• To declare:-
String stringName;
stringName = new String (“Happy Friendship Day”);
Creating String Object
• Using a string literal
String str1= “Hello”;

• Using another string object


String str2 = new String (str1);

• Using new keyword


String str3 = new String(“Fraanndds…….”);

• Using + operator (concatenation)


String str4 = “Chai” + “Pilo”;
or
String str5 = str1 + str2;

System.out.println(str1+ “ ”+str3+“ ”+str4);

Hello Fraanndds……. Chai Pilo


How String object are stored ?

• Each time you create a String literal, the JVM checks the string pool
first.

• If the string literal already exists in the pool, a reference to the pool
instance is returned. If string does not exist in the pool, a new string
object is created, and is placed in the pool.

• String objects are stored in a special memory area known as string


constant pool inside the heap memory.

• When we create a new string object using string literal, that string
literal is added to the string pool, if it is not present there already.

• String str1 = “Bit Mesra”;

Bit Mesra
str1
String object

Heap
class BitMesra
{
public static void main(String[] args)
{
String a = new String("Hello");
String c ="Hello";
System.out.println(a.equals(c));
System.out.println(a==c);
}
}

Output:-
true
false

• == operator compares two object references to check whether they refer to


same instance.
• equals() checks the string and not object references

Source: Studytonight.com
class BitMesra
{
public static void main(String[] args)
{
String a = new String("Hello");
a.concat("bit");
a = a.concat("bit");
System.out.println(a);
}
}

Source: Balaguruswamy
StringBuffer class
• Why StringBuffer class is better than String class ?
• S1.setCharAt(n, ‘x’);
• S1.append(s2);
• S1.insert(n, s2);
• S1.setLength(n);

class BitMesra
{ C:\Users\Mayur\Documents\Java>javac
public static void main(String[] args) BitMesra.java
{ BitMesra.java:8: error: cannot find symbol
String a = new String("Hello"); c.insert(1,b);
String b=new String("Bit"); ^
String c = new String(“Hello”); symbol: method insert(int,String)
StringBuffer c =new StringBuffer("Hello"); location: variable c of type String
c.insert(1,b); 1 error
System.out.println(c);
}
} C:\Users\Mayur\Documents\Java>javac BitMesra.java
C:\Users\Mayur\Documents\Java>java BitMesra
HBitello
String class

Programmer

StringBuffer class

Source: Google Images


Difference between StringBuffer and
StringBuilder

Thread-safe
Interfaces
1. Interface is a pure abstract class. They are syntactically similar to classes, but
you cannot create instance of an Interface and their methods are declared
without any body.

2. Interface is used to achieve complete abstraction in Java. When you create an


interface it defines what a class can do without saying anything about how the
class will do it.

3. Syntax:-
interface interface-name { }

Example of Interface:-

interface Moveable
{
int AVERAGE-SPEED=40;
void move();

}
What compiler sees ?

Compiler automatically converts methods of interface as public and abstract,


and the data members as public, static and final by default.
Rules of interface

• Methods inside Interface must not be static, final.

• We cannot create constructor of interface.

• An interface is written in a file with a .java extension, with the name of


the interface matching the name of the file.

• All variables declared inside interface are implicitly public static final
variables(constants).

• All methods declared inside Java Interfaces are implicitly public and
abstract, even if you don't use public or abstract keyword.

• Interface can extend one or more other interface.

• Interface cannot implement a class.

• Interface can be nested inside another interface.


//BitMesra.java

interface result
{
int maxmarks=100;
int minmarks=40;
void pass(int n);
}
class BitMesra implements result C:\Users\Mayur\Documents\Java>javac BitMesra.java
{
public void pass(int n) C:\Users\Mayur\Documents\Java>java BitMesra
{ Pappu pass ho gaya
if (n>=40 && n<=100)
{
System.out.println("Pappu pass ho gaya");
}
}
public static void main(String[] args)
C:\Users\Mayur\Documents\Java>javac BitMesra.java
{
BitMesra.java:19: error: cannot assign a value to final variable
BitMesra cse = new BitMesra(); minmarks
cse.pass(45); cse.minmarks=30;
cse.minmarks=30; // Error ^
} 1 error
}
Multiple Inheritance is achieved using interface
interface result class BitMesra implements result, hostel
{ {
int maxmarks=100; public void pass(int n)
{ if (n>=40 && n<=100)
int minmarks=40;
{
void pass(int n); System.out.println("Pappu pass ho gaya");
} }
interface hostel }
{
int[] hostel_no={7,8}; public void allotted(char gender)
void allotted(char gender); {
if (gender= ='M' || gender= ='m')
}
{
System.out.println("Allotted Hostel is : "+hostel_no[0]);
}
if (gender= ='F' || gender= ='f')
{
System.out.println("Allotted Hostel is : "+hostel_no[1]);
}
C:\Users\Mayur\Documents\Java>javac BitMesra.java }
public static void main(String[] args)
C:\Users\Mayur\Documents\Java>java BitMesra {
Pappu pass ho gaya BitMesra cse = new BitMesra();
Allotted Hostel is : 7 cse.pass(45);
Allotted Hostel is : 8 BitMesra imsc = new BitMesra();
imsc.allotted('M');
cse.allotted('f');
}
}
Difference between abstract class and interface
Passing Objects to Methods

public class Cat


{
int noOfEyes;
public void display(Cat c)
{
System.out.println(c.noOfEyes);

public static void main(String[] args)


{
Cat c1= new Cat();
c1.noOfEyes=2;
c1.display(c1);
}
}
Returning objects
public class Cat
{
int noOfEyes;
public Cat display()
{
Cat c= new Cat();
c.noOfEyes=2;
return c;
}
public static void main(String[] args)
{
Cat c1= new Cat();
Cat c2;
c2=c1.display();
System.out.println(c2.noOfEyes);
}
}

You might also like