0% found this document useful (0 votes)
203 views35 pages

Java PPT - 3 by Adi

The document discusses object-oriented programming concepts in Java including classes, objects, inheritance, polymorphism, abstraction, encapsulation, and interfaces. It provides details on inheritance in Java, the super keyword, abstract classes, and interfaces.
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)
203 views35 pages

Java PPT - 3 by Adi

The document discusses object-oriented programming concepts in Java including classes, objects, inheritance, polymorphism, abstraction, encapsulation, and interfaces. It provides details on inheritance in Java, the super keyword, abstract classes, and interfaces.
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/ 35

Java Programming

Unit-3

Dr. K ADISESHA
Java OOPs Tutorial 2

Introduction

Inheritance

Interfaces

Package

Multithreading

Prof. K. Adisesha
3
Introduction
Introduction:
Object-Oriented Programming is a methodology or paradigm to design a program using
classes and objects.
➢ It simplifies software development and maintenance by providing some concepts:
❖ Object
❖ Class
❖ Inheritance
❖ Polymorphism
❖ Abstraction
❖ Encapsulation
❖ Coupling & Cohesion
❖ Association
❖ Aggregation
❖ Composition
Prof. K. Adisesha
4
Introduction

OOPs Concepts in Java:


The basic concept of OOPs is to create objects, re-use them throughout the program, and
manipulate these objects to get results.
➢ Class − The class is one of the Basic concepts of OOPs which is a group of similar entities. It is
only a logical component and not the physical entity.
➢ Object - An object can be defined as an instance of a class, and there can be multiple instances of
a class in a program.
➢ Inheritance - Inheritance is one of the Basic Concepts of OOPs in which one object acquires the
properties and behaviors of the parent object.
➢ Polymorphism - Polymorphism refers to one of the OOPs concepts in Java which is the ability of
a variable, object or function to take on multiple forms.
➢ Abstraction - Abstraction is one of the OOP Concepts in Java which is an act of representing
essential features without including background details.
Prof. K. Adisesha
5
Introduction

OOPs Concepts in Java:


The basic concept of OOPs is to create objects, re-use them throughout the program, and
manipulate these objects to get results.
➢ Encapsulation − Encapsulation is one of the best Java OOPs concepts of wrapping the data and
code. In this OOPs concept, the variables of a class are always hidden from other classes.
➢ Association - Association is a relationship between two objects. It is one of the OOP Concepts in
Java which defines the diversity between objects. In this OOP concept, all objects have their
separate lifecycle, and there is no owner.
➢ Aggregation - In this technique, all objects have their separate lifecycle. However, there is
ownership such that child object can’t belong to another parent object.
➢ Composition - Composition is a specialized form of Aggregation. It is also called “death”
relationship. Child objects do not have their lifecycle so when parent object deletes all child
object will also delete automatically.
Prof. K. Adisesha
6
Java OOPs

Inheritance in Java:
Types of inheritance in java
➢ On the basis of class, there can be three types of inheritance in java: Single, Multilevel
and Hierarchical.
➢ In java programming, multiple and hybrid inheritance is supported through interface
only.

Prof. K. Adisesha
7
Java OOPs

Inheritance in Java:
Multiple and Hybrid inheritance in java
➢ Java does not support Multiple inheritance, where a class inherits from multiple classes.
This was done to avoid the diamond problem, where two super-classes of a class have a
common subclass and cause ambiguity in the subclass's implementation.
➢ Java does support Hybrid inheritance, where a class implements multiple interfaces. This
is done to provide a common interface for multiple classes to implement and share
behavior.
➢ Instead of multiple inheritance, Java provides alternatives such as aggregation and
interface implementation to achieve similar functionality.

Prof. K. Adisesha
8
Java OOPs

Java Abstraction:
Data abstraction is the process of hiding certain details and showing only essential
information to the user. Abstraction can be achieved with either abstract classes or
interfaces.
➢ To access the abstract class, it must be inherited from another class.
➢ The abstract keyword is a non-access modifier, used for classes and methods:
❖ Abstract class: is a restricted class that cannot be used to create objects (to access
it, it must be inherited from another class). abstract class ClassA {…}
❖ Abstract method: can only be used in an abstract class, and it does not have a
body. The body is provided by the subclass (inherited from).
// Abstract method (does not have a body)
Prof. K. Adisesha public abstract void Method1();
9
Java OOPs
Java Abstraction:
A class which is declared as abstract is known as an abstract class. It can have abstract
and non-abstract methods.
➢ It needs to be extended and its method implemented. It cannot be instantiated.
➢ An abstract class must be declared with an abstract keyword.
➢ It can have abstract and non-abstract methods.
➢ It cannot be instantiated.
➢ It can have constructors and static methods also.
➢ It can have final methods which will force the subclass not to change the body of the method.
➢ Example of abstract class ➢ Example of abstract method
abstract class A{} abstract void printStatus();//no method body and abstract

Prof. K. Adisesha
10
Java OOPs

Super Keyword in Java:


The super keyword in Java is a reference variable which is used to refer immediate
parent class object.
➢ Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
➢ Usage of Java super Keyword
❖ super can be used to refer immediate parent class instance variable.
❖ super can be used to invoke immediate parent class method.
❖ super() can be used to invoke immediate parent class constructor.
❖ The super keyword can also be used to invoke parent class method. It should be used if
subclass contains the same method as parent class. In other words, it is used if method is
overridden.
Prof. K. Adisesha
11
Java OOPs

Super Keyword in Java:


The super keyword in Java is a reference variable which is used to refer immediate
parent class object.
class College void Studying()
{ { super.Course();
void Course () Subject();
{System.out.println("Studying BCA..."); } }
} }
class TestSuper2
class Dept extends College {
{ void Course() public static void main(String args[])
{ System.out.println(“Studying BBA..."); } { Dept d=new Dept(); Output:
void Subject() d.Studying();
Studying BCA...
{ System.out.println(“Java Programming...");} }}
Java Programming...
Prof. K. Adisesha
12
Java OOPs
Java - Interfaces:
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.
➢ An interface in Java is a blueprint of a class.
➢ By interface, we can support the functionality of multiple inheritance.
➢ The interface keyword is used to declare an interface
Syntax: interface <interface_name>
➢ It can be used to achieve loose coupling. { // declare constant fields
➢ It is used to achieve abstraction. // declare methods that abstract
➢ Interface methods are by default abstract and public // by default. }
➢ Interface attributes are by default public, static and final
➢ An interface cannot contain a constructor (as it cannot be used to create objects)
Prof. K. Adisesha
13
Interfaces
Java - Interfaces:
Interfaces have the following properties −
➢ An interface is implicitly abstract. You do not need to use the abstract keyword while
declaring an interface.
➢ Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
➢ Methods in an interface are implicitly public.
➢ Declaring Interfaces: The interface keyword is used to declare an interface.
/* File name : NameOfInterface.java */ Example
import java.lang.*;
/* File name : Student.java */
// Any number of import statements
interface Student {
public interface NameOfInterface {
public void Personal();
// Any number of final, static fields
public void Course();
// Any number of abstract method declarations}
}
}
Prof. K. Adisesha
14
Interfaces
Java - Interfaces:
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body.
Key Difference Between Abstract Class and Interface in Java.
➢ In Interface, a class can implement multiple interfaces, whereas the class can inherit only one
Abstract Class.
➢ In Interface does not have access modifiers. Everything defined inside the Interface is assumed
to have a public modifier, whereas Abstract Class can have an access modifier.
➢ The Interface cannot contain data fields, whereas the abstract class can have data fields.
➢ Interfaces help define a class’s peripheral abilities, whereas an abstract class defines the
identity of a class. ➢ Example of abstract class : Example of interface :
public abstract class Shape public interface Shape
Prof. K. Adisesha { public abstract void draw(); } { void draw(); }
15
Interfaces
Java - Interfaces:
Implementing Interfaces− To understand the use of interface in Java better, let see an Java
interface example. The class “Media Player” has two subclasses: CD player and DVD player.
Each having its unique interface implementation in Java method to play music.

Prof. K. Adisesha
16
Interfaces
Java - Interfaces:
Implementing Interfaces− When a class implements an interface, you can think of the class as
signing a contract, agreeing to perform the specific behaviors of the interface. If not the class must
declare itself as abstract.
➢ A class uses the implements keyword to implement an interface. The implements keyword
appears in the class declaration following the extends portion of the declaration..
/* File name : BCA.java */ public static void main(String args[])
public class BCA implements Student { {
public void Personal () BCA obj = new BCA();
{ System.out.println(“K. ADISESHA"); obj. Personal();
} obj. Course();
public void Course () } Output:
{ System.out.println(“Java Programming"); } K. ADISESHA
} } Java Programming
Prof. K. Adisesha
17
Interfaces

Java - Multiple Interfaces:


To implement multiple interfaces, separate them with a comma−
interface FirstInterface public void myMethod2()
{ public void myMethod1(); // interface method } { System.out.println("Java Programming"); }
}
interface SecondInterface
{ public void myMethod2(); // interface method } class Main
{
class DemoClass implements FirstInterface, public static void main(String[] args)
SecondInterface { DemoClass myObj = new DemoClass();
{ myObj.myMethod();
public void myMethod1() myObj.myOtherMethod();
{ System.out.println("K. ADISESHA.."); } } Output:
} K. ADISESHA..
Prof. K. Adisesha Java Programming
18
Java Package

Java Package:
A java package is a group of similar types of classes, interfaces and sub-packages.
➢ Package in java can be categorized in two form, built-in package and user-defined package.
➢ There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
➢ Advantage of Java Package
❖ Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
❖ Java package provides access protection.
❖ Java package removes naming collision.

Prof. K. Adisesha
19
Java Package

Built-in Packages:
The Java API is a library of prewritten classes, that are free to use, included in the Java
Development Environment(JDE).
➢ The library is divided into packages and classes. Meaning you can either import a single
class (along with its methods and attributes), or a whole package that contain all the classes
that belong to the specified package.
➢ To use a class or a package from the library, you need to use the import keyword:
➢ Syntax
❖ import package.name.Class; // Import a single class import java.util.Scanner;
❖ import package.name.*; // Import the whole package import java.util.*;

Prof. K. Adisesha
20
Java Package

Creating a Package:
While creating a package, you should choose a name for the package and include a
package statement along with that name at the top of every source file that contains the
classes, interfaces, enumerations, etc., that you want to include in the package.
➢ The package statement should be the first line in the source file. There can be only one
package statement in each source file, and it applies to all types in the file.
❖ package <file_name>;
➢ To compile the Java programs with package statements, you have to use -d option as shown
below. package mypack;
class MyPackageClass {
❖ javac -d Destination_folder <file_name.java.> public static void main(String[] args) {
To compile the package: C:\Users>javac -d . MyPackageClass.java System.out.println("This is my package!");
To run the package : C:\Users>java mypack.MyPackageClass }}
Prof. K. Adisesha
21
Java Package

To access package from another package:


If a class wants to use another class in the same package, the package name need not be
used. Classes in the same package find each other without any special syntax.
➢ There are three ways to access the package from outside the package.
❖ Using packagename.* :If you use package.* then all the classes and interfaces of this
package will be accessible but not subpackages.
import package.*;
❖ Using packagename.classname : If you import package.classname then only declared
class of this package will be accessible.
import package.classname;
❖ Using fully qualified name : If you use fully qualified name then only declared class of
this package will be accessible. pack. A obj = new pack.A();//using fully qualified name .
Prof. K. Adisesha
22
Threads In Java

Threads In Java:
Threads allows a program to operate more efficiently by doing multiple things at the
same time.
➢ Threads can be used to perform complicated tasks in the background without interrupting the
main program.
➢ There are two ways to create a thread:
❖ It can be created by extending the Thread class and overriding its run() method:
❖ Another way to create a thread is to implement the Runnable interface:
Extend Syntax: Implement Syntax
public class Main extends Thread { public class Main implements Runnable {
public void run() { public void run() {
System.out.println("This code is running in a thread"); System.out.println("This code is running in a thread");
} } } }
Prof. K. Adisesha
23
Threads In Java

Running Threads:
The major difference is that when a class extends the Thread class, you cannot extend
any other class, but by implementing the Runnable interface, it is possible to extend from
another class as well.
➢ If the class extends the Thread class, the thread can be run by creating an instance of the class
and call its start() method:
➢ Extend Example public class Main extends Thread
{ public static void main(String[] args)
{ Main thread = new Main();
thread.start();
System.out.println("This code is outside of the thread"); }
public void run()
{ System.out.println("This code is running in a thread"); }
Prof. K. Adisesha
}
24
Threads In Java

Running Threads:
Thread class, by implementing the Runnable interface, it is possible to extend from
another class as well.
➢ If the class implements the Runnable interface, the thread can be run by passing an instance of
the class to a Thread object's constructor and then calling the thread's start() method:
➢ Implement Example: public class Main implements Runnable
{ public static void main(String[] args)
{ Main obj = new Main();
Thread thread = new Thread(obj);
thread.start();
System.out.println("This code is outside of the thread"); }
public void run()
{ System.out.println("This code is running in a thread"); } }
Prof. K. Adisesha
25
Threads In Java

Types Of Threads In Java:


Multithreading in Java is a process of executing multiple threads simultaneously.
➢ User Thread : User threads are threads which are created by the application or user.
❖ They are high priority threads and also called as foreground threads.
❖ JVM (Java Virtual Machine) will not exit until all user threads finish their execution. JVM
wait for these threads to finish their task.
➢ Daemon Thread : Daemon threads are threads which are mostly created by the JVM.
❖ These threads are less priority threads and these threads always run in background used to
perform some background tasks like garbage collection and house-keeping tasks.
❖ JVM will not wait for these threads to finish their execution.
❖ JVM will exit as soon as all user threads finish their execution.

Prof. K. Adisesha
26
Threads In Java

Thread Lifecycle in Java:


A thread goes through various stages in its life cycle. For example, a thread is born,
started, runs, and then dies.
➢ The complete life cycle of a thread.
❖ New State
❖ Runnable State
❖ Waiting State
❖ Timed Waiting State
❖ Terminated (Dead) State

Prof. K. Adisesha
27
Threads In Java
Thread Lifecycle in Java:
Following are the stages of the life cycle:
➢ New − A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
➢ Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this
state is considered to be executing its task.
➢ Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another
thread to perform a task.
➢ Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of
time. A thread in this state transitions back to the runnable state when that time interval expires
or when the event it is waiting for occurs.
➢ Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or
otherwise terminates.
Prof. K. Adisesha
28
Multithreading in Java

Multitasking in Java:
Multitasking is the process that lets users perform multiples tasks at the same time. There
are two ways to enable multitasking in Java:.
➢ Process-based multitasking: The processes in this type of multitasking are heavy and a
lot of time is consumed. This is because the program takes a long time to switch between
different processes.
➢ Thread-based multi tasking: Threads are light-weight compared to process-based multi
tasking, and the time taken to switch between them is shorter.
➢ There are two ways to create a thread:
❖ By extending Thread class (extend syntax)
❖ By implementing Runnable interface.
Prof. K. Adisesha
29
Multithreading in Java

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.
➢ Threads are independent. If there occurs exception in one thread, it doesn't affect other threads.
It uses a shared memory area.
➢ Java Multithreading is mostly used in games, animation, etc.
➢ Advantages of Java Multithreading
❖ It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
❖ You can perform many operations together, so it saves time.
❖ Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.
Prof. K. Adisesha
30
Multithreading in Java

Thread class in Java:


Thread class provide constructors and methods to create and perform operations on a
thread. Thread class extends Object class and implements Runnable interface.
➢ Commonly used Constructors of Thread class:
❖ Thread() syntax:
❖ Thread(String name) public class Main extends thread {
public void test() {
❖ Thread(Runnable r) System.out.println("Threads are very helpful in java");
❖ Thread(Runnable r,String name) } }
syntax:
public class Main implements runnable {
public void test() {
System.out.println("Threads are very helpful in java");
Prof. K. Adisesha
} }
31
Multithreading in Java

Thread Methods:
Thread methods in Java are very important while you're working with a multi-threaded
application. The thread class has some important methods.
➢ public void start(): you use this method to start the thread in a separate path of execution. Then
it invokes the run() method on the thread object.
➢ public void run(): this method is the starting point of the thread. The execution of the thread
begins from this process.
➢ public final void setName(): this method changes the name of the thread object.
➢ public final void setPriority(): you use this method to set the values of the thread object.
➢ public void sleep(): you use this method to suspend the thread for a particular amount of time.
➢ public void interrupt(): you use this method to interrupt a particular thread. It also causes it to
continue execution if it was blocked for any reason.
➢Prof.public
K. Adisesha
final boolean isAlive(): this method returns true if the thread is alive..
32
Multithreading in Java

Thread Priorities:
Every Java thread has a priority that helps the operating system determine the order in
which threads are scheduled.
➢ Java thread priorities are in the range between a constant of 1 -10:
❖ MIN_PRIORITY (a constant of 1).
❖ MAX_PRIORITY (a constant of 10).
❖ By default, every thread is given priority NORM_PRIORITY (a constant of 5).
➢ Threads with higher priority are more important to a program and should be allocated
processor time before lower-priority threads.
➢ However, thread priorities cannot guarantee the order in which threads execute and are
very much platform dependent.
Prof. K. Adisesha
33
Multithreading in Java

Example to creates a new thread and starts running it.


class RunnableDemo implements Runnable { public void start ()
private Thread t; { System.out.println("Starting " + threadName );
private String threadName; if (t == null) { t = new Thread (this, threadName);
RunnableDemo( String name) t.start (); }
{ threadName = name; } }
System.out.println("Creating " + threadName ); }
public class TestThread
public void run() { public static void main(String args[])
{ System.out.println("Running " + threadName ); { RunnableDemo R1 = new RunnableDemo( "Thread-1");
try { for(int i = 4; i > 0; i--) R1.start();
{ System.out.println("Thread: " + threadName + ", " + i); RunnableDemo R2 = new RunnableDemo( "Thread-2");
// Let the thread sleep for a while. R2.start(); }
Thread.sleep(50); } } }
catch (InterruptedException e)
{ System.out.println("Thread " + threadName + " interrupted."); }
System.out.println("Thread " + threadName + " exiting."); }
Prof. K. Adisesha
34
Multithreading in Java

Example implement thread using runnable interface in Java.


MyThread.java MainThread.java
class MyThread implements Runnable public class MainThread
{ String message; {
MyThread(String msg) public static void main(String[] args)
{ message = msg; } { MyThread obj1 = new MyThread("MyThread obj1");
public void run() MyThread obj2 = new MyThread("MyThread obj2");
{ for(int count=0;count<=5;count++) Thread t1 = new Thread(obj1);
{ try Thread t2 = new Thread(obj2);
{ System.out.println("Run method: " + message); t1.start();
Thread.sleep(100); } t2.start(); }
catch (InterruptedException ie) }
{ System.out.println("Exception in thread: "+ie.getMessage());}
}
}
}
Prof. K. Adisesha
35
Discussion

Queries ?
Prof. K. Adisesha
9449081542

Prof. K. Adisesha (Ph. D)

You might also like