Oops Using Java: By: Gurveen Vaseer
Oops Using Java: By: Gurveen Vaseer
Oops Using Java: By: Gurveen Vaseer
By:
Gurveen Vaseer
Objected Oriented Programming
Concepts
• Inheritance in Java is a
mechanism in which one object
acquires all the properties and
behaviors of a parent object.
• Class: A class is a group of objects which have
common properties. It is a template or blueprint
from which objects are created.
• Sub Class/Child Class: Subclass is a class which
inherits the other class. It is also called a derived
class, extended class, or child class.
• Super Class/Parent Class: Superclass is the class
from where a subclass inherits the features. It is
also called a base class or a parent class.
• Reusability: As the name specifies, reusability is a
mechanism which facilitates you to reuse the fields
and methods of the existing class when you create a
new class. You can use the same fields and methods
already defined in the previous class.
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.bo
nus);
}
}
Method OVERRIDING
class Main {
public static void main(String[] args) {
String greet = "Hello! World";
System.out.println("String: " + greet);
// get the length of greet
int length = greet.length();
System.out.println("Length: " + length); }}
import java.util.Scanner;
class ChkPalindrome
{ public static void main(String args[])
{ String str, rev = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
str = sc.nextLine();
int length = str.length();
for ( int i = length - 1; i >= 0; i-- )
rev = rev + str.charAt(i);
if (str.equals(rev))
System.out.println(str+" is a palindrome");
else
System.out.println(str+" is not a palindrome");
}
}
Exception Handling
• There are mainly two types of
exceptions: checked and unchecked.
1. Checked Exception
2.Unchecked Exception
3.Error
1) Checked Exception
The classes which directly inherit Throwable class
except RuntimeException and Error are known as
checked exceptions e.g. IOException, SQLException
etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes which inherit RuntimeException are known
as unchecked exceptions e.g. ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException
etc. Unchecked exceptions are not checked at compile-
time, but they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError,
VirtualMachineError, AssertionError etc.
Keyword Description
try The "try" keyword is used to specify a block where we should
place exception code. The try block must be followed by either
catch or finally. It means, we can't use try block alone.
finally The "finally" block is used to execute the important code of the
program. It is executed whether an exception is handled or
not.
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
class Main {
public static void main(String[] args) {
try {
// code that generates exception
int divideByZero = 5 / 0;
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
finally {
System.out.println("This is the finally block");
}
}}
Multiple catch
public class MultipleCatchBlock3 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
public class MultipleCatchBlock4 {
public static void main(String[] args) {
try{
String s=null;
System.out.println(s.length());
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Use of throws
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e)
{System.out.println("exception handled");}
System.out.println("normal flow...");
}
}
Multithreading in Java
• Multithreading in Java is a process of
executing multiple threads simultaneously.
• A thread is a lightweight sub-process, the
smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve
multitasking.
• However, we use multithreading than
multiprocessing because threads use a shared
memory area. They don't allocate separate
memory area so saves memory, and context-
switching between the threads takes less time
than process.
Process-based Multitasking (Multiprocessing)
• Each process has an address in memory. In other
words, each process allocates a separate memory
area.
• A process is heavyweight.
• Cost of communication between the process is high.
• Switching from one process to another requires
some time for saving and loading registers, memory
maps, updating lists, etc.
Thread-based Multitasking (Multithreading)
• Threads share the same address space.
• A thread is lightweight.
• Cost of communication between the thread is low.
Life cycle of thread
Creating a thread
There are two ways to create a thread:
1.By extending Thread class
2.By implementing Runnable interface.
class Multi extends Thread{
public void run(){
System.out.println("thread is running...")
;
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
class TestSleepMethod1 extends Thread{
public void run(){
for(int i=1;i<5;i++){
try
{Thread.sleep(500);}
catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestSleepMethod1 t1=new TestSleepMethod1();
TestSleepMethod1 t2=new TestSleepMethod1();
t1.start();
t2.start();
}
}
class TestJoinMethod1 extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestJoinMethod1 t1=new TestJoinMethod1();
TestJoinMethod1 t2=new TestJoinMethod1();
TestJoinMethod1 t3=new TestJoinMethod1();
t1.start();
try{
t1.join();
}catch(Exception e){System.out.println(e);}
t2.start();
t3.start();
}
}
class TestJoinMethod3 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestJoinMethod3 t1=new TestJoinMethod3();
TestJoinMethod3 t2=new TestJoinMethod3();
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
System.out.println("id of t1:"+t1.getId());
t1.start();
t2.start();
t1.setName(“XY");
System.out.println("After changing name of t1:"+t1.getName());
}
}
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentTh
read().getName());
System.out.println("running thread priority is:"+Thread.current
Thread().getPriority());
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
public class TestDaemonThread1 extends Thread{
public void run(){
if(Thread.currentThread().isDaemon()){
System.out.println("daemon thread work");
}
else{
System.out.println("user thread work");
}
}
public static void main(String[] args){
TestDaemonThread1 t1=new TestDaemonThread1();
TestDaemonThread1 t2=new TestDaemonThread1();
TestDaemonThread1 t3=new TestDaemonThread1();
t1.setDaemon(true);
t1.start();
t2.start();
t3.start();
}
}
Java Garbage Collection