0% found this document useful (0 votes)
43 views148 pages

Inheritance (Shivani Ma Am)

Uploaded by

moh24amme
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)
43 views148 pages

Inheritance (Shivani Ma Am)

Uploaded by

moh24amme
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/ 148

Inheritance

Dr.Srivani P
• Inheritance in Java is a mechanism in which one object acquires all
the properties and behaviors of a parent object. It is an important
part of OOPs (Object Oriented programming system).

• Reusability: Inheritance supports the concept of “reusability”, i.e.


when we want to create a new class and there is already a class that
includes some of the code that we want, we can derive our new class
from the existing class. By doing this, we are reusing the fields and
methods of the existing class.
• Code readability and interpretability.
Dr.Srivani P
Syntax

class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}

Dr.Srivani P
Dr.Srivani P
Dr.Srivani P
we must know a few concepts:
• Subclass
This is the class which inherits methods and values from the
superclass. It is the child class. It can have methods and values of its
own aside from possessing all the variables.
• Superclass
This is the class from which the child class inherits all the methods
and values. This is the parent class.

Dr.Srivani P
extends Keyword in Java
• The extends keyword extends the functionality of the child class by
inheriting values from the parent class.

• It defines an “is-a” relationship. It comes after the class definition


and carries the class name of the parent class.

• The syntax is as follows


• <child class> extends <parent-class>

Dr.Srivani P
Dr.Srivani P
Single Inheritance

class baseclass
{
.... methods
}
class derivedClass extends baseClass
{
methods ... along with this additional
feature
}

Dr.Srivani P
class Employee { class single_inheritance {
String name=“XYZ”; public static void main(String args[])
void salary() { {
System.out.println("Salary= 200000"); Programmer p = new Programmer();
} p.salary();
}
p.bonus();
class Programmer extends Employee }
{ }
void bonus() {
System.out.println("Bonus=50000");
}
}

Dr.Srivani P
Types of relationships in Java
• There are two types of relationships in java.
• They are:

1. “is-a” relationship
2. “Has-a” relationship”

Dr.Srivani P
Multilevel Inheritance in Java
• This represents a multi-tier inheritance wherein the child class
inherits from a parent class which in itself is a child class to another
parent class. A real-life example would be a child inheriting from his
father who inherited from his grandfather.

Dr.Srivani P
class GrandFather { class Son extends Father {
GrandFather() Son()
{ {
System.out.println("I am the grandfather!"); System.out.println("I am the son and I inherit from my father.");
} }
} }

class Father extends GrandFather { Public class sample {


String familyName; public static void main(String args[])
String houseaddress; {
Father() { Son s1 = new Son();
System.out.println("I am the father! I inherit from }
Grandfather"); }
}
}

Dr.Srivani P
Multiple Inheritance

Dr.Srivani P
Why Java does not support Multiple
inheritance through classes?
But in Java, one class cannot extend
more than one class simultaneously.
At most, one class can extend only one
class.

Dr.Srivani P
Hierarchical Inheritance

Dr.Srivani P
class Father { class Daughter extends Father {
String familyName; Daughter() {
String houseaddress; System.out.println("I am the Daughter");
System.out.println("My family name is " +this.familyName + "
Father() { and I am from " + this.houseaddress);
familyName = "Programmer"; }
houseaddress = "Delhi"; }
} class Main {
} public static void main(String[] args) {
class Son extends Father { Son s = new Son();
Son() { Daughter d = new Daughter();
System.out.println("I am the Son"); }
System.out.println("My family name is " + }
this.familyName + " and I am from " +
this.houseaddress);
}
}

Dr.Srivani P
Hybrid Inheritance

Dr.Srivani P
Dr.Srivani P
super

Dr.Srivani P
Super variables
class Vehicle
{
int maxSpeed = 120;
}

/* sub class Car extending vehicle */


class Car extends Vehicle
{
int maxSpeed = 180;

void display()
{
System.out.println("Maximum Speed: " + super.maxSpeed);
}
}

/* Driver program to test */


class Test
{
public static void main(String[] args)
{
Car c= new Car();
c.display();
}
}
Dr.Srivani P
Contd..
class Parent public static void main(String[] args)
{ {
int a=10,b=20; Child c = new Child();
} c.m1(1000,2000);
class Child extends Parent }
{ };
int a=100;
int b=200;
void m1(int a,int b)
{
System.out.println(a+b);
System.out.println(this.a+this.b);
System.out.println(super.a+super.b);
}

Dr.Srivani P
Super method
class Person void display()
{ {
void message() // will invoke or call current class message() method
{ message();
System.out.println("This is person class");
} // will invoke or call parent class message() method
} super.message();
}
/* Subclass Student */ }
class Student extends Person
{ /* Driver program to test */
void message() class Test
{ {
System.out.println("This is student class"); public static void main(String args[])
} {
Student s = new Student();
// Note that display() is only in Student class
// calling display() of Student
s.display();
}
}
Dr.Srivani P
Use of super with constructors:
class Person Student(int a)
{ {
Person() super();
{ System.out.println("Student 1- arg class Constructor");
System.out.println("Person class Constructor");
} }
} }

/* subclass Student extending the Person class */ class Test


class Student extends Person {
{ public static void main(String[] args)
Student() {
{ Student s = new Student();
this(10); }
}
System.out.println("Student 0-arg class Constructor");
}

Dr.Srivani P
Other Important points:
• Call to super() must be first statement in Derived(Student) Class
constructor.
• If a constructor does not explicitly invoke a superclass constructor, the Java
compiler automatically inserts a call to the no-argument constructor of the
superclass. If the superclass does not have a no-argument constructor, you
will get a compile-time error. Object does have such a constructor, so if
Object is the only superclass, there is no problem.
• If a subclass constructor invokes a constructor of its superclass, either
explicitly or implicitly, you might think that a whole chain of constructors
called, all the way back to the constructor of Object. This, in fact, is the
case. It is called constructor chaining..
Dr.Srivani P
• Design a called Staff with details as Staff Id, Name, Phone, Salary.
Extend this class by writing three subclasses namely Teaching
(domain, publications), Technical (skills), and Contract (period).

• Write a Java program to read and display at least 3 staff objects of all
three categories.

Dr.Srivani P
Dr.Srivani P
OVERRIDING
• The concept of method overriding is simply the redefining of the
parent class method in the child class. The name of the method
remains the same. However, the implementation of the same
changes.

Dr.Srivani P
Dr.Srivani P
class Father {
void career() {
System.out.println("I am the father! I am a doctor ! ");
} O/P
} I am the father! I am a doctor !
public class Child extends Father { I am the son! I am a singer!
void career () {
System.out.println("I am the son! I am a singer!");
}
public static void main(String[] args)
{
Father f = new Father();
f.career();
Father fc = new Child();
fc.career(); //This is dynamic methpod dispatch. The compiler decides method call
at runtime.
} Dr.Srivani P
No. Method Overloading Method Overriding
1) Method overloading is used to increase the Method overriding is used to provide the specific
readability of the program. implementation of the method that is already provided by its
super class.

2) Method overloading is performed within Method overriding occurs in two classes that have IS-A
class. (inheritance) relationship.

3) In case of method overloading, parameter In case of method overriding, parameter must be same.
must be different.
4) Method overloading is the example Method overriding is the example of run time polymorphism.
of compile time polymorphism.
5) In java, method overloading can't be Return type must be same or covariant in method overriding.
performed by changing return type of the
method only. Return type can be same or
different in method overloading. But you
must have to change the parameter.
6) Static methods can be overloaded Static methods cannot be overridden

Dr.Srivani P
class A
{
void m1()
{
System.out.println("Inside A's m1 method");
}
}

class B extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside B's m1 method");
}
}

class C extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside C's m1 method");
} Dr.Srivani P
}
class Dispatch
{
public static void main(String args[]) {
A a = new A();
B b = new B();
C c = new C();
// obtain a reference of type A
A ref;
// ref refers to an A object
ref = a;
// calling A's version of m1()
ref.m1();
// now ref refers to a B object
ref = b;
// calling B's version of m1()
ref.m1();
// now ref refers to a C object
ref = c;
// calling C's version of m1()
ref.m1();
}
}

Dr.Srivani P
Static methods in Java are non-overridable
• If you override a static method in the parent class with the static
method in the child class then the method in the parent class
hides the child class method.

Dr.Srivani P
class Father {
// private methods are not overridden
static void method1() {
System.out.println("From static Father method1()");
}
void method2() {
System.out.println("From Father method2()");
}
}

class Child extends Father {


static void method1() {
System.out.println("From static Child method1()");
}
void method2() {
System.out.println("From Child method2()");
}
}
class StaticOverride {
public static void main(String[] args) {
Father obj1 = new Father();
obj1.method2();
Father obj2 = new Child();
obj2.method1(); }} Dr.Srivani P
• O/P :
• From Father method2()
From static Father method1()

Dr.Srivani P
Final Methods- Cannot be overidden
class Father {
final void shoot() {
System.out.println("I am the father! I am a right handed shooter! ");
}
}
public class Child extends Father {
void shoot() {
super.shoot();
System.out.println("I am the son! I am a left handed shooter!");
}
public static void main(String[] args) {
Father fc = new Child();
fc.shoot(); //This is the method which houses the super keyword for calling the parent class method.
}
}

You cannot override final methods in java. If you have a method declared as final in your parent class
then that method is non-overridable. Dr.Srivani P
Dr.Srivani P
Dynamic Method Dispatch or Runtime
Polymorphism
• When Parent class reference
variable refers to Child class
object, it is known as Upcasting.

• In Java this can be done and is


helpful in scenarios where
multiple child classes extends one
parent class.

Dr.Srivani P
Java Packages
A package in Java is used to group related classes. Think of it as a folder in a file
directory.

Syntax: package <directorname1>.<directoryname2>…<finaldirectoryname>;

Dr.Srivani P
Private Protected Default
Public

Inside the same class Yes Yes Yes Yes

Inside the same


package and in a Yes No Yes Yes
subclass
Inside the same
package but not in a Yes No Yes Yes
subclass.
Inside different
packages but in a Yes No Yes No
subclass

Inside different
packages and not in a Yes No No No
subclass.

Dr.Srivani P
How to access package from another
package?
• There are three ways to access the package from outside the package.
1.import package.*;
2.import package.classname;
3.fully qualified name.

Dr.Srivani P
1) Using packagename.*
• If you use package.* then all the classes and interfaces of this package
will be accessible but not subpackages.
• The import keyword is used to make the classes and interface of
another package accessible to the current package.
//save by A.java package mypack;
package pack; import pack.*;
public class A{
public void msg(){ class B{
System.out.println("Hello"); public static void main(String args[]){
} A obj = new A();
} obj.msg();
}
}
Dr.Srivani P
2) Using packagename.classname
• If you import package.classname then only declared class of this
package will be accessible.

//save by A.java package mypack;


package pack; import pack.A;
public class A{ class B{
public void msg(){ public static void main(String args[]){
System.out.println("Hello"); A obj = new A();
} obj.msg();
} }
}

Dr.Srivani P
3) Using fully qualified name
• If you use fully qualified name then only declared class of this
package will be accessible. Now there is no need to import. But you
need to use fully qualified name every time when you are accessing
the class or interface.

package pack; package mypack;


public class A{ class B{
public void msg(){ public static void main(String args[]){
System.out.println("Hello");} pack.A obj = new pack.A();
} //using fully qualified name
obj.msg();
}
}

Dr.Srivani P
Advantages of Using Java Packages

• Implementing Data Encapsulation in Java is easy with the help of


packages.
• Packages help prevent naming conflicts.
• It orders the classes according to their functions. Hence it is easy to
search for classes.
• You can control the accessibility of the classes by using access
specifiers and packages together.

Dr.Srivani P
Built-in

Dr.Srivani P
1. java.lang – This package consists of classes that help in performing input out
operations in the program. It also contains language support for data types and
math operations. Whenever you create a class, this package is automatically
imported.
2.java.io – This package contains classes that specialize in input and output
operations only. One popular thing class you might have seen in programs is the
InputStreamReader class and the BufferedReader class.
3. java.util – This class contains basic utilities that can be useful while
implementing LinkedLists, Trees, HashMaps, and so on. It also has a Scanner class
for input-output operations to the program. It also contains support for date and
time.
4. java.applet – This package contains necessary classes for creating applets.
5. java.awt – This package specializes in providing support for designing GUI
elements in Java.
6. java.net – This package contains classes which help in performing network
operations.

Dr.Srivani P
class A{ package pack;
private int data=40; public class A{
private void msg(){System.out.println("Hello java protected void msg()
");} {System.out.println("Hello");}
} }
_________________________________________
public class Simple{ ___
public static void main(String args[]){ package mypack;
A obj=new A(); import pack.*;
System.out.println(obj.data);
//Compile Time Error class B extends A{
obj.msg();//Compile Time Error public static void main(String args[]){
} B obj = new B();
} obj.msg();
}
}

PRIVATE PROTECTED
Dr.Srivani P
1.statement 1;
Exceptions 2.statement 2;
3.statement 3;
4.statement 4;
5.statement 5;//exception occurs
6.statement 6;
7.statement 7;
8.statement 8;
9.statement 9;
10.statement 10;

Dr.Srivani P
Exceptions
• An exception is any abnormal condition arising during the execution of the
program.
• an exception is an event that disrupts the normal flow of the program

• A widely known exception is the division by zero which is an Arithmetic


Exception error.
• All errors and exceptions come under the throwable class in Java. The
throwable class has two subclasses:
• a. Exceptions (Ex: file not found)
b. Error (Ex:out of memory- Non recoverable)
• Examples:
• A user has entered an invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of communications or the JVM has
run out of memory

Dr.Srivani P
Dr.Srivani P
Dr.Srivani P
Dr.Srivani P
Checked Exception in Java
• Checked Exception is also known as compile-time exceptions because
it occurs at the compile time.
If there is some code within a method which throws a checked
exception, we must catch it in the same method or we have to
propagate it to the caller using throws keyword.

• which directly inherit from the Throwable class


• For example IOException, SQLException, File NotFoundException etc.

Dr.Srivani P
Unchecked Exception in Java
• Unchecked Exception is also known as Runtime Exceptions because it occurs
at Runtime. This kind of exception occurs at the time of execution. In C++,
all exceptions are unchecked, so it is not forced by the compiler to either
handle or specify the exception. It totally depends upon the programmer to
catch the exceptions.
• The exception classes inheriting the RuntimeException class
• For example:
ArithmeticException,
NullPointerException,ArrayIndexOutOfBoundsException etc.

Dr.Srivani P
Java Exception Handling Keywords
Java provides specific keywords for exception handling purposes,
• try
• catch
• finally
• throw
• throws

Dr.Srivani P
1. try: The try block is the block where the block of code that is needed to
be checked for exceptions is placed. The try block is followed by a catch
or finally block, it cannot stand alone.

2. catch: Using the catch block we can catch the exception thrown by the try
block. It is declared after the try block.

3. finally: Using the finally block we can execute an important piece of code
because the finally block will be executed regardless of what the outcome is
from the try block.

4. throw: Using the throw keyword we can throw a predefined exception.

5. throws: Using the throws keyword we can declare a new exception from
the exception classes.

Dr.Srivani P
Java Exception Methods:
SL. No. Method Description

This method returns a string message explaining


1 public String getMessage()
the exception that occurred.

This method throws the cause of the occurred


2 public Throwable getCause()
exception.

This method returns the message of the


3 public String toString() getMessage() method along with the class of
exception concatenated to it.

This method returns the output of the toString()


4 public void printStackTrace()
method along with its stack trace

This method returns an array containing all the


5 public StackTraceElement [] getStackTrace()
elements of the stack trace.

Dr.Srivani P
Syntax
try {
//code where exceptions may occur
}
catch(Exception e) {
//Code to handle the exception
}

Dr.Srivani P
Java Finally Block

• The “finally” block follows the try block or the catch block. This
segment houses the code which gets executed whether an exception
occurs or not. This may contain a cleanup code that you want to
execute after the protected block.
• The syntax is as follows:
finally {
//cleanup code
}

Dr.Srivani P
public class Main { public class Main {
public static void main(String[ ] args) { public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3}; try {
System.out.println(myNumbers[10]); // error! int[] myNumbers = {1, 2, 3};
} System.out.println(myNumbers[10]);
} }
catch (Exception e) {
System.out.println(„Array OutofIndex Bound.");
}
}
}

O/P: O/P:
ception in thread "main" Array OutofIndex Bound.
java.lang.ArrayIndexOutOfBoundsException: Index 100
out of bounds for length 50
at Main.main(Main.java:13)

Dr.Srivani P
class Excp class Excp
{ {
public static void main(String args[]) public static void main(String args[])
{ {
int a,b,c; int a,b,c;
{ try
a=0; {
b=10; a=0;
c=b/a; b=10;
System.out.println(c); c=b/a;
System.out.println("Thank you"); System.out.println("This line will not be executed");
}
} catch(ArithmeticException e)
} {
System.out.println("Divided by zero");
}
System.out.println("After exception is handled");
}
}

Dr.Srivani P
Multiple try-catch
try {
//Code where exception can occur
}
catch(ExceptionTypeA e1) {
//code that executes if Exception of type A occurs
}
catch(ExceptionTypeB e2) {
//code that executes if Exception of type B occurs.
}

Dr.Srivani P
Multiple try-catch
import java.io. * ; catch(ArithmeticException e) {
public class MultCatch { System.out.println("You are trying to divide by zero! That
public static void main(String[] args) throws IOException { is not right!");
try { }
int arr[] = {1,3,4,2,45,6}; catch(ArrayIndexOutOfBoundsException e) {
System.out.println(arr[131]); System.out.println("You are trying to access an index not
System.out.println(25 / 0); in the array!");
System.out.println("This statement will never get }
executed because the control has shifted to the catch finally {
block. "); System.out.println("This code is in the finally block. It
} does not depend on whether an exception occurs or not.
");
}
}
}

Dr.Srivani P
Java throws keyword
• It is used to indicate that an exception can be thrown by a function during
execution.
• On the other hand the throws keyword is useful in case of checked
exceptions.
• If a method performs a particular function that may result in one of the
checked exceptions, the throws keyword is added after the method
declaration..
• Syntax of java throws
return_type method_name() throws exception_class_name
{
//method code
}

Dr.Srivani P
public class sample{
int divison(int a, int b) throws ArithmeticException{
int intet = a/b;
return intet;
}
public static void main(String args[]){
sample obj = new sample();
try{
System.out.println(obj.divison(15,0));
}
catch(ArithmeticException e){
System.out.println("Division cannot be done using ZERO");
}
}
}

Dr.Srivani P
throw
The throw keyword explicitly throws Exceptions from a method or a
block of code. Generally “throw” keyword helps to throw custom
exceptions.
Sometime we might want to generate exception explicitly in our code,
for example in a user authentication program we should throw
exception to client if the password is null. throw keyword is used to
throw exception to the runtime to handle it.

• Throw instance();

Dr.Srivani P
void Votingage(int age){
if(age<18)
throw new ArithmeticException("you can't vote as not Eligible to vote");
else
System.out.println("Eligible for voting");
}

Dr.Srivani P
throw
public class TestThrow { public static void main(String[] args) {
TestThrow obj = new TestThrow();
public static void checkNum(int num) {
if (num < 1) { obj.checkNum(-3);
throw new ArithmeticException("\nNumber is negative, cannot calculate squ System.out.println("Rest of the code..");
are");
}
}
else {
System.out.println("Square of " + num + " is " + (num*num));
}
}

Dr.Srivani P
Java throw example
void m()
{
throw new ArithmeticException("sorry");
}
Java throws example
void m()throws ArithmeticException
{
//method code
}
Java throw and throws example
void m() throws ArithmeticException
{
throw new ArithmeticException("sorry");
}
Dr.Srivani P
No. throw throws

1) Java throw keyword is used to Java throws keyword is used to


explicitly throw an exception. declare an exception.
2) Checked exception cannot be Checked exception can be propagated
propagated using throw only. with throws.
3) Throw is followed by an instance. Throws is followed by class.

4) Throw is used within the method. Throws is used with the method
signature.
5) You cannot throw multiple exceptions. You can declare multiple exceptions
e.g.
public void method()throws
IOException,SQLException.

Dr.Srivani P
throws
import java.io.*; public static void main(String[] args) {
class Main { try{
public static void findFile() throws IOException { findFile();
// code that may produce IOException }
File newFile=new File("test.txt"); catch(IOException e){
FileInputStream stream=new FileInputStream(newFile); System.out.println(e);
} }
}
}

Dr.Srivani P
public static void writeToFile() throws IOException public static void main(String[] args)
{ {
try {
BufferedWriter bw = new BufferedWriter(new writeToFile();
FileWriter("myFile.txt")); }
bw.write("Test");
bw.close(); catch (IOException e) {
} e.printStackTrace();
}
}

Dr.Srivani P
• Create a custom exceptions in Java for bank class.
class InsufficientBalanceException extends Exception public void withdraw(double amount) throws
{ InsufficientBalanceException
public InsufficientBalanceException(String message) {
{ if (balance - amount < 1000) {
super(message); throw new InsufficientBalanceException("Insufficient
} balance. Minimum balance of 1000 required.");
} }
balance -= amount;
System.out.println("Withdrawn: " + amount);
}

Dr.Srivani P
Ways to achieve Abstraction in Java

Dr.Srivani P
Dr.Srivani P
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.

• 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 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).
Dr.Srivani P
Abstract Classes
• Any class which contains at least a single abstract method in itself is
an abstract class.

• Example of abstract method


• abstract void printStatus(); //no method body and abstract

Dr.Srivani P
Dr.Srivani P
Dr.Srivani P
Dr.Srivani P
Dr.Srivani P
abstract class Bike class Pulsor extends Bike
{ {
abstract void run(); void run()
} {
System.out.println("running safely");
}
public static void main(String args[])

{
Bike obj = new Honda4();
obj.run();
}
}

Dr.Srivani P
abstract class Shape class Rectangle extends Shape
{ {
abstract void draw(); void draw(){
} System.out.println("drawing rectangle");
}
}
class Circle extends Shape{
void draw(){System.out.println("drawing circle");}
}

class TestAbstraction1 {
public static void main(String args[]){
Shape s=new Circle1();
s.draw();
}
}
Dr.Srivani P
abstract class Animal Animal myObj = new Animal();
{
public abstract void animalSound(); // will generate an error
public void sleep()
{
System.out.println("Zzz");
}
}

Dr.Srivani P
Abstract class with abstract and normal method

abstract class BaseClass


{
//abstract method
abstract public void show1();
//concrete method
public void show2()
{
System.out.println("Concrete method of parent class");
}
}

Dr.Srivani P
Abstract class having constructor, data
member and methods
abstract class Content { class child extends Content {

int a; child()
{
// Constructor of abstract class super(2);
public Content(int a) }
{
this.a = a; public int multiply(int val)
} {
return a * val;
// Abstract method of abstract class }
abstract int multiply(int val); }
}

Content c = new child();


Dr.Srivani P
Dr.Srivani P
Programs

Dr.Srivani P
Dr.Srivani P
Interfaces
• Another way to achieve abstraction in Java, is with interfaces.

• An interface is a completely "abstract class" that is used to group


related methods with empty bodies

• Interfaces in Java are similar to abstract classes but with some key
differences. These are essential for defining a blueprint of the class
methods. It is one of the methods programmers use to achieve
abstraction. They contain names of methods that will be
implemented in classes using this interface.

Dr.Srivani P
Dr.Srivani P
Dr.Srivani P
• It contains all the functions that a class can perform. For example an
interface for a vehicle would have break(), accelerate(), turn()
methods.

• A class while implementing an interface must implement all the


methods inside the interface.

• Whenever you declare a variable inside an interface, the variable


automatically becomes public, static, and final. It is advisable not to
use interface variables in Java.

Dr.Srivani P
Declaring Interface in Java

• The syntax for using interfaces is simple.

Interfaces in Java
class <class_name> implements <interface_name>
Dr.Srivani P
interface Animal { class Main {
void animalSound(); public static void main(String[] args)
void sleep(); {
} Pig p1= new Pig();
p1.animalSound();
class Pig implements Animal { p1.sleep();
}
public void animalSound() }
{
System.out.println("The pig says: wee wee");
}
public void sleep()
{
System.out.println("Zzz");
}
}

Dr.Srivani P
interface Accelerate {
public void acceleratemethod();
}
interface Brake {
public void brakemethod();
}
class Car implements Accelerate, Brake
{
public void brakemethod() {
System.out.println("This car has disc brakes");
}
public void acceleratemethod() {
System.out.println("This car has BENZ OM654 engine with 503 HP");
}
}
class MultipleInheritance {
public static void main(String[] args) {
Car carobject = new Car();
carobject.acceleratemethod();
carobject.brakemethod();
}
}

Dr.Srivani P
Dr.Srivani P
• Java compiler automatically adds public and abstract keywords before
to all interface methods. Moreover, it also adds public, static, and
final keywords before interface variables. Look at the below figure to
understand better.

Dr.Srivani P
Notes on Interfaces:
• Like abstract classes, interfaces cannot be used to create objects (in the
example above, it is not possible to create an "Animal" object in the
MyMainClass)
• Interface methods do not have a body - the body is provided by the
"implement" class
• On implementation of an interface, you must override all of its methods
• Interface methods are by default abstract and public
• Interface attributes are by default public, static and final
• An interface cannot contain a constructor (as it cannot be used to create
objects)
Dr.Srivani P
interface Polygon {
void getArea();

default void getPerimeter(int... sides) {


int perimeter = 0;
for (int side: sides) {
perimeter += side;
}

System.out.println("Perimeter: " + perimeter);


}
}
Dr.Srivani P
Dr.Srivani P
interface Printable
{
void print();
}

interface Showable extends Printable{


void show();
}
class TestInterface4 implements Showable
{
public void print(){
System.out.println("Hello");}
public void show(){
System.out.println("Welcome");}

public static void main(String args[]){


TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}

Dr.Srivani P
Relationship

Dr.Srivani P
Multiple inheritance in Java by interface

Dr.Srivani P
Partial Implementation
• If a class includes an interface but does not fully implement the
methods defined by that interface, then that class must be declared
as abstract. For example:
• abstract class Incomplete implements animal
{
int a, b;
void sleep () {
System.out.println(“Sleep);
}
// ... } Dr.Srivani P
Threads

Dr.Srivani P
Dr.Srivani P
Life Cycle of a Thread

Dr.Srivani P
States
• NEW – As the name suggests, a thread that is brand new and still idle is in this state.
• RUNNABLE – When a thread is executing in the JVM(Java Virtual Machine) it is
said to be in the RUNNABLE state. A very important thing to note here is that the
thread might be running or is getting to run in an instant when it is in the
RUNNABLE state. The thread scheduler allocates the necessary resources and time
of running to each thread in the RUNNABLE state.
• BLOCK – The thread is waiting for a monitor lock when it is in the BLOCK state.
This means that the thread is waiting for a particular I/O operation to complete.
• WAITING – This is similar to the BLOCK state, however in this state the thread is
waiting for a different thread for some reason.
• TIMED_WAITING – In this state, the thread is waiting for a particular timeout
function to finish. After it finishes the thread is in the RUNNABLE state again.
• TERMINATED – Quite simply this means that the thread is now no longer alive.
This may be because of two reasons, either the thread has completed all its operations
or it has encountered a serious problem such as a segmentation fault.

Dr.Srivani P
Tasks of Thread
1. Multitasking
This essentially means performing multiple actions at the same time. When
you listen to music and code, you are essentially multitasking.
2. Multithreading
This means the action of multiple threads of a single process working
simultaneously to complete a single process.
3. Multiprocessing
This may seem similar to multithreading but there is a fundamental
difference in it that sets them apart.
Multiple processing involves the use of multiple cores of the CPU whereas
multithreading uses only a single core of the CPU.
Dr.Srivani P
Dr.Srivani P
How to create thread
Extends Thread Implement Runnable interface

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");
} }
} }

Main()- Start object Thread Class

Dr.Srivani P
Examples
Extends Thread Implement Runnable interface

public class Main extends Thread { public class Main implements Runnable {
public static void main(String[] args) { public static void main(String[] args) {
Main thread = new Main(); Main obj = new Main();
thread.start(); Thread thread = new Thread(obj);
System.out.println("This code is outside thread.start();
of the thread"); System.out.println("This code is outside
} of the thread");
public void run() { }
System.out.println("This code is running public void run() {
in a thread"); System.out.println("This code is running
} in a thread");
} }
}
Dr.Srivani P
Commonly used Constructors of Thread class:

• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r, String name)

Dr.Srivani P
Commonly used methods of Thread class
• getName(): This returns the thread name.
• getPriority(): This returns the priority of the thread.
• isAlive(): This method is useful for checking whether the thread is still
running.
• join(): This method waits for a thread to terminate.
• run(): This method invokes the start of the thread. This method is
generally used to denote the actions the thread will perform.
• sleep(): This method suspends the thread for a particular period of
time.
• start(): start a thread by calling its run() method
Dr.Srivani P
Dr.Srivani P
Multi-Thread

Dr.Srivani P
Dr.Srivani P
Case 1: Thread Scheduler:
• If multiple Threads are waiting to execute then which Thread will
execute 1st is decided by "Thread Scheduler" which is part of JVM.

• Which algorithm or behavior followed by Thread Scheduler we can't


expect exactly it is the JVM vendor dependent hence in
multithreading examples we can't expect exact execution order and
exact output.

Dr.Srivani P
Case 2: Difference between t.start() and t.run()
methods
• In the case of t.start() a new Thread will be created which is
responsible for the execution of run() method.
• But in the case of t.run() no new Thread will be created and run()
method will be executed just like a normal method by the main
Thread.

Dr.Srivani P
Case 3: importance of Thread class start() method.
• For every Thread the required mandatory activities like registering the
Thread with Thread Scheduler will takes care by Thread class start()
method
• Programmer is responsible just to define the job of the Thread inside run()
method.
• That is
• start()
{
1. Register Thread with Thread Scheduler
2. All other mandatory low level activities.
3. Invoke or calling run() method.
}
start() method acts as best assistant to the programmer.
Dr.Srivani P
Case 4: If we are not overriding run() method:
• If we are not overriding run() method then Thread class run() method will be executed which has empty
implementation and hence we won't get any output.

class MyThread extends Thread


{

}
class ThreadDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.start();
}
}

Dr.Srivani P
class MultithreadingDemo extends Thread { // Main Class
public void run() public class Multithread {
{ public static void main(String[] args)
try { {
// Displaying the thread that is running int n = 8; // Number of threads
System.out.println( for (int i = 0; i < n; i++) {
"Thread " + Thread.currentThread().getId() MultithreadingDemo object
+ " is running"); = new MultithreadingDemo();
} object.start();
catch (Exception e) { }
// Throwing an exception }
System.out.println("Exception is caught"); }
}
}
}

Dr.Srivani P
Case 5: Overloding of run() method.
We can overload run() method but Thread class start() method always invokes no
argument run() method the other overload run() methods we have to call explicitly then
only it will be executed just like normal method.

• Example:
class MyThread extends Thread
{
public void run()
{
System.out.println("no arg method");
}
public void run(int i)
{
System.out.println("int arg method");
}
}

Dr.Srivani P
Case 6: overriding of start() method:
If we override start() method then our start() method will be executed just like a normal method call
and no new Thread will be started.
class MyThread extends Thread
{
public void start() {
System.out.println("start method");
}
public void run() {
System.out.println("run method");
}}
class ThreadDemo {
public static void main(String[] args) {
MyThread t=new MyThread();
t.start();
System.out.println("main method");
}} Dr.Srivani P
Dr.Srivani P
Dr.Srivani P
Java Sleeping Thread

• To sleep a thread for a specified time, Java provides sleep method


which is defined in Thread class. The sleep method is an overloaded
method which are given below. It throws interrupted exception so
make sure to provide proper handler.
• Syntax

sleep(long millis)throws InterruptedException


sleep(long millis, int nanos)throws InterruptedException

Dr.Srivani P
Joining threads in Java
• Sometimes one thread needs to know when other thread is terminating.
In java, isAlive() and join() are two different methods that are used to
check whether a thread has finished its execution or not.
• The isAlive() method returns true if the thread upon which it is called
is still running otherwise it returns false.
• final boolean isAlive()
•join() method is used more commonly than isAlive(). This method waits until the
thread on which it is called terminates.
•final void join() throws InterruptedException

Dr.Srivani P
Dr.Srivani P
public class MyThread extends Thread
{
public void run()
{
System.out.println("r1 ");
try {
Thread.sleep(500);
}
catch(InterruptedException ie)
{
// do something
}
System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t2.start();
System.out.println(t1.isAlive());
System.out.println(t2.isAlive());
}
} Dr.Srivani P
Inter Thread Communication
• The methods that are essential for inter-thread communication are wait(),
notify(), and notifyAll().
• In Java, the monitor prevents other threads from using the resource if a
particular thread is using it at present. This is because the monitor can hold
only one thread.
• The wait method asks the monitor to give up the threads and go to sleep.

• notify() – This wakes up the first thread which was put on the wait() queue.
• notifyAll() – This wakes up all the threads which are sleeping.

Dr.Srivani P
• The threads can communicate with each other through wait(),
notify() and notifyAll() methods in Java.
• These are final methods defined in the Object class and can be called
only from within a synchronized context.
• The wait() method causes the current thread to wait until another
thread invokes the notify() or notifyAll() methods for that object.
• The notify() method wakes up a single thread that is waiting on that
object’s monitor. The notifyAll() method wakes up all threads that
are waiting on that object’s monitor.

Dr.Srivani P
Dr.Srivani P
Synchronization in Java

Dr.Srivani P
Thread Synchronization in Java

Dr.Srivani P
• We know that multithreading increases the speed of execution of a
program and optimizes computer resource usage.
• Normally, multiple threads in a single program run asynchronously if
threads do not share a common resource.
• when a thread is already accessing an instance of a class, preventing
any other thread from acting on the same instance is called ‘thread
synchronization in Java‘ or ‘ Thread safe‘.

Dr.Srivani P
• The code in Java program can be synchronized with the help of a lock.
A lock has two operations: acquire and release. The process of
acquiring and releasing object lock (monitor) of an object is handled
by Java runtime system (JVM).

In Java programming language, every object has a default object lock


that can be used to lock on a thread. This object lock is also known
as monitor that allows only one thread to use the shared resources
(objects) at a time.
Dr.Srivani P
Synchronized Method
• When we declare a synchronized keyword in the header of a method,
it is called synchronized method. Once a method is made
synchronized, and thread calls the synchronized method, it gets
locked on the method.
• All other threads will have to wait for the current thread to release
the lock. Using the synchronized keyword, we can synchronize the
entire method.

synchronized void show()


{
// statements to be synchronized
}
Dr.Srivani P
Synchronized Block
synchronized(object)
{
// statements to be synchronized
}

• Here, object is a reference variable of an object that has to be locked


or synchronized. The statements within the synchronized block are
available to only one thread at a time.
• A Java synchronized block doesn't allow more than one JVM, to
provide access control to a shared resource.
Dr.Srivani P
Synchronized Block

Table A B

Display(int i) A(Table t) B(Table t)


//constructor //constructor

Run () Run ()
{ {
Display(5) Display(8)
} }

Dr.Srivani P
Why use Synchronization?

• The synchronization is mainly used to prevent thread interference and


consistency problem.

Dr.Srivani P
Producer Consumer Problem

Dr.Srivani P
Dr.Srivani P
Contd..
• Problem:

To make sure that the producer won’t try to add data into the buffer if it’s
full and that the consumer won’t try to remove data from an empty buffer.

• Solution:
The producer is to either go to sleep or discard data if the buffer is full. The next
time the consumer removes an item from the buffer, it notifies the producer, who
starts to fill the buffer again. In the same way, the consumer can go to sleep if it
finds the buffer to be empty. The next time the producer puts data into the buffer,
it wakes up the sleeping consumer.

Dr.Srivani P
Bounded Buffer Problem

Dr.Srivani P

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy