2 Object Oriented Programming

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

Chapter 2

Object Oriented Programming

Prof. Amruta Deshmukh


1
What is OOP?

• Object oriented programming is a model that


provides different type of concepts, such as
inheritance, abstraction, polymorphism etc.
• These concepts implement real-world entities in
programs, and they create methods and variables
to reuse them without compromising security.
• Object oriented programming is about creating
objects that contain both data and methods.
• Object-Oriented Programming is a methodology
to design a program using classes and objects. It
simplifies the software development and
maintenance.

Prof. Amruta Deshmukh


2
2.1 Class Fundamentals
• Class is a blue print which is containing only list of variables and
methods and no memory is allocated for them. It is a logical entity.
• A class is a group of objects that has common properties.
• A class in java contains Data Member, Methods and Constructor.
• Once a class has been defined, we can create any number of objects.
• Syntax to declare a Class
class Class_Name
{ data member;
method;
}

Prof. Amruta Deshmukh


3
Class Rectangle
{ int length;
int width; // Variable declaration
// Method declaration
void getdata(int x, int y)
{ length=x;
width=y;
}
} // end of class

Prof. Amruta Deshmukh


4
Object
• An object is an entity which has a well defined
structure and behavior.
• It can be physical and logical.
• Object has identity, state, Behavior and responsibility.
• An object can be conceptual.
• E.g. Air, hard disk, pen, person, sound, instrument,
bank account, contract, signal, industrial process,
transaction, training course etc.

Prof. Amruta Deshmukh


5
State of an Object
• The state of an object includes the current values of
all its attributes.
• An attribute can be static or dynamic.
• E.g. Employee Attributes
• Static Attributes
- empid, name, gender
• Dynamic Attributes
- age, address, phone, basicsal, education, experience.

Prof. Amruta Deshmukh


6
Behavior of the Object
• Behavior is how an object acts and reacts, in terms of
its state changes and message passing.
• The behavior of an object corresponds to its
functions. The change in the state of an object reflects
in its behavior.
• E.g. calculate salary and print details are the behaviors
of the employee. They can either help to retrieve the
information or change the state of the attributes.

Prof. Amruta Deshmukh


7
Identity of an object
•Identity is that property of an object which
different it from all other objects.
•Every object has its own identity.
•A single or group of attributes can be identity
of an object.
•It is easier to interact with an object that has
identity.
•E.g. 1. Empid is an identity of an employee.
•2. Fan and Mobile phone would have a unique
product number as an identity.
Prof. Amruta Deshmukh
8
Attribut State Ident Behaviour Responsibility
es ity
Empid Empid=10 Empi Swipe Card To be present in the
d=10 office on time.

name Name=”Raj” Fill Do allocated work.


Timesheet
gender Gender=”male” Wear Icard Identity with
organization.

age Age=27 Calculate Get salary


Salary

address pune Print Provide personal


Details information

phone 9862145256
Basic 9000
salary
educati
on
experie
nce

Prof. Amruta Deshmukh


9
Create an Object
• Object is an instance of class. It is created using new
keyword in java.
• To create object of type Rectangle use statement as
Rectangle rect1 = new Rectangle();
• Every rectangle object will contain its own copies of
instance variables, length & width.
• To access these variables use Dot (.) operator.
• E.g. rect1.width=100;
• You can use dot operator to access both the instance
variables & the methods within an object.

Prof. Amruta Deshmukh


10
• In Java, all class objects must be dynamically
allocated.

Prof. Amruta Deshmukh


11
Simple Example of Object and Class//D
class Employee
{
int eid; // data member
String ename; // data member
eid=101;
ename="Hitesh";
public static void main(String args[])
{
Employee e=new Employee(); // Creating an object of class Employee
System.out.println("Employee ID: "+e.eid);
System.out.println("Name: "+e.ename);
}
} Prof. Amruta Deshmukh
12
class Rectangle
{
private int l,b;

public void setDimension(int x, int y)


{
l=x;
b=y;
}

public int area()


{
return l*b;
}
public void display()
{
System.out.println("Length="+l);
System.out.println("Breadth="+b);
}
public static void main(String [] args)
{
Rectangle r=new Rectangle();
r.setDimension(5,10);
r.display();
System.out.println("Area="+ r.area());
} }
Prof. Amruta Deshmukh
13
Access Specifiers
•Access Specifiers allow to specify the scope of
class members.
•Access Specifiers are of 4 types.
1. public
2. private
3. protected
4. Default
In java, encapsulation is implemented using
access Specifier.
Prof. Amruta Deshmukh
14
Java Access Modifiers
• Let's understand the access modifiers in Java by a simple table.

Access Modifier within class within package outside package outside package
by subclass only

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

Prof. Amruta Deshmukh


15
1)Public:
• The public access allows anyone to access the data or method specified
with this access.
• The public access modifier is the direct opposite of the private
access modifier. A class, method or variable can be declared as
public and it means that it is accessible from any class.

• To Compile: d//javac -d . A.java


• To Run: d//java pp.A

//save by A.java
package pp;
public class A{
public void msg(){
System.out.println("Hello");}
}
Prof. Amruta Deshmukh
16
2//save by B.java
To Compile :D:\>javac -d . B.java
To Run : D:\>java pack.B

package pack;
import pp.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

Prof. Amruta Deshmukh


17
Private:
• The access level of a private modifier is only within the class. It cannot
be accessed from outside the class.

• Example Save D:\>javac PrivateA.java


class A{

private void msg()

System.out.println("Hello java");}

public class PrivateA{

public static void main(String args[]){

A obj=new A();//Compile Time Error

obj.msg();

}
Prof. Amruta Deshmukh
} 18
3)Protected
• Protected variables & methods are accessible by the
package classes and any subclasses that are in other
packages.
//save by D:\>javac -d . Ap.java
package packAp;
public class Ap{
protected void
msg(){System.out.println("Hello");}
}

Prof. Amruta Deshmukh


19
//save by Bp.java
To Compile: D:\>javac -d . Bp.java
To Run: D:\>java mypackBp.Bp
package mypackBp;
import packAp.*;

class Bp extends Ap{


public static void main(String args[]){
Bp obj = new Bp();
obj.msg();
}
}
Prof. Amruta Deshmukh
20
Default
• If you don't use any modifier, it is treated as default by default.
• Data and methods declared without any access Specifiers are said to
have default access.
• The default modifier is accessible only within package.
• It cannot be accessed from outside the package.
• The default access allows all the classes within the same package to
access the data and methods.
• Example:
//save by A.java javac -d . Ad.java
package packD;
class Ad{
void msg(){System.out.println("Hello");}
}

Prof. Amruta Deshmukh


21
//save by BD.java and
D:\>javac -d . BD.java
package mypackD;
import packD.*;
class BD{
public static void main(String args[]){
AD obj = new AD();//Compile Time Error
obj.msg();//Compile Time Error
}
}

Prof. Amruta Deshmukh


22
Garbage Collection
• Garbage collection in Java is the process by which Java programs
perform automatic memory management.
• Java programs compile to bytecode that can be run on a Java
Virtual Machine.
• When Java programs run on the JVM, objects are created on the
heap, which is a portion of memory allocated to the program.
• Eventually, some objects will no longer be needed. The garbage
collector finds these unused objects and deletes them to free up
memory.
• The object is subject to a garbage collection when it becomes
unreachable to the program in which it is used.
• Objects which are no longer in use. Garbage collector destroys
these objects.
• The main objective of Garbage Collector is to free heap memory
by destroying unreachable objects
Prof. Amruta Deshmukh
23
finalize() Method
• finalize() method in Java is a method of the Object class. that
is used to perform cleanup activity before destroying any
object.
• finalize( ) method when it detects that the object has become
unreachable.
• The purpose of finalize() method is to give an unreachable object the
opportunity to perform any clean up processing before the object is
garbage collected (destroying any object).
• Inside the finalize( ) method you can specify those actions that must
be performed before an object is destroyed.
• Syntax:
• protected void finalize( ) { // code }
• finalize() method receives no parameters and returns no value.
• Finalization: Just before destroying any object, the garbage
collector always calls finalize() method to perform clean-up
activities on that object. This process is known as Finalization in
Java. Prof. Amruta Deshmukh 24
Example finalize() Method
• package amruta;
• public class TestGarbage1 {
• void h()
• {
• System.out.println("hi");
• }
• public void finalize(){System.out.println("object is garbage
collected");}
• public static void main(String[] args) {

• TestGarbage1 s1=new TestGarbage1();



• TestGarbage1 s2=new TestGarbage1();

• s1=null;
• s2=null;
• System.gc();
• }
• }
Prof. Amruta Deshmukh
25
• Java System gc() Method
• The gc() method of System class runs the garbage collector.
• this method, JVM makes best effort to reuse the memory of discarded
objects for quick reuse.
• Syntax
• public static void gc() ;

• Example
• package amruta;
• public class SystemGCExample1 {

• public static void main(String[] args) {


• // TODO Auto-generated method stub
• String i="amruta";
• System.out.println("before garbage collection = "+i);
• i= null; System.gc();
• System.out.println("after garbage collection = "+i);}

• }
Prof. Amruta Deshmukh
26
Constructor
• A constructor is a special member function used to initialize the
values of the attributes of an object.
• This function is implicitly called when an object is created.
• It is not compulsory to define a constructor. In this case the
compiler provides a default constructor but the attributes are
initialized to default values. E.g. Zero for numeric type, null for
object references and false for boolean.
• A constructor in Java is a special method that is used to
initialize objects. The constructor is called when an
object of a class is created.

Prof. Amruta Deshmukh


27
Rules to create constructor

• Constructor name is same as class name.


• No return type for constructor. Not even void.
• Constructors are implicitly called when objects are created.
• There is no return statement in the body of the constructor.
• Constructor can be overloaded.

• Overloading refers to a technique where same name is used for another


method but the signature of the methods are different.
• Constructor which does not accept any argument is called as default
constructor.

Prof. Amruta Deshmukh


28
Types of Java constructors
• There are two types of constructors in Java:
1.Default constructor (no-arg constructor)
2.Parameterized constructor

Prof. Amruta Deshmukh


29
Output:
Bike is created
Bik is created

Java Default Constructor


• A constructor is called "Default Constructor" when it doesn't
have any parameter.
• Syntax of default constructor:
<class_name>(){}
Example: D:\>javac ACD.java

class ACD{
ACD()
{
System.out.println("Default constructor");
}
public static void main(String args[])
{
ACD b=new ACD();
} Prof. Amruta Deshmukh
} 30
Java Parameterized Constructor

• A constructor which has a specific number of


parameters is called a parameterized constructor.

Prof. Amruta Deshmukh


31
1.//Java Program to demonstrate the use of the parameterized constructor.
2.D:\>javac Student4.java

class Student4{
int id;
String name;
Student4(int i,String n)
{
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[]){

Student4 s1 = new Student4(11,"Kunal");


Student4 s2 = new Student4(22,"Amol");
s1.display();
s2.display(); Prof. Amruta Deshmukh
}
32
}
2.7 Nested and Inner Classes
• Inner Class
• Definition of one class within the definition of another class.
• Inner class is a member of the enclosing class just like another class
member.
• Syntax of Inner class
class Outer_class {
// details of outer class
class Inner_class {
// details of inner class
}
// more details of outer class
}

Prof. Amruta Deshmukh


33
// Example of member inner class that is invoked inside a class
package deshmukh;
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
} }
}
class InnerClassDemo {
public static void main(String args []) {
Outer outer = new Outer();
outer.test();
} }
Output : display: outer_x = 100 Prof. Amruta Deshmukh
34
// member inner class that is invoked outside a class
Example 1
• package deshmukh;
• class Outer1 {
• private int data=30;
• class Inner
• {
• void msg()
• {
• System.out.println("data is"+ data);
• }
• }
• }

• public class TestMemberInner {

• public static void main(String[] args) {

• Outer1 obj=new Outer1();


• Outer1.Inner in=obj.new Inner();
• in.msg();

• }

• } Prof. Amruta Deshmukh


Output: data is 30
35
• //member inner class that is invoked outside a class
• Example 2

• class A
• {
• class B
• {
• void show()
• {
• System.out.println("Class B");
• }
• }
• }
• class MainC
• {
• public static void main(String argc[])
• {
• A a1=new A();
• A.B b2=a1.new B();
• b2.show();
• }
• }
Prof. Amruta Deshmukh
36
Types of Inner Classes
1.Nested Inner Class/Member Inner Class
2.Static Inner Classes
3.Method Local Inner Classes
4. Anonymous Inner Classes

Prof. Amruta Deshmukh


37
1Nested Inner Class/Member Inner Class
• In Java, you can define a class within another class. Such class is known as nested inner
class.
• Example
• package deshmukh;
• class Outer {
• int outerx = 100;
• void test() {
• Inner inner = new Inner();
• inner.display();
• }
• class Inner {
• void display() {
• System.out.println("display: outerx = " + outerx);
• }
• }
• }
• public class InnerClassDemo {

• public static void main(String[] args) {


• // TODO Auto-generated method stub
• Outer outer = new Outer();
• outer.test();

• }
Prof. Amruta Deshmukh
• } 38
• 2) Static Nested Classes:
• In Java, we can also define a Static class inside another class. Such class
is known as Static nested class.
• Example.

• class MotherBoard {

• // static nested class


• static class USB{
• int usb2 = 2;
• int usb3 = 1;
• int getTotalPorts(){
• return usb2 + usb3;
• }
• }

• }
• public class staticinnerclass {

• public static void main(String[] args) {

• MotherBoard.USB usb = new MotherBoard.USB();


• System.out.println("Total Ports = " + usb.getTotalPorts());
• }

• }
Prof. Amruta Deshmukh
39
1Nested Inner Class/Member Inner Class
• In Java, you can define a class within another class. Such class
is known as nested inner class.
• 2) Static Nested Classes:
• In Java, we can also define a Static class inside another class.
Such class is known as Static nested class.

3.Method Local Inner Classes


• Inner class can be declared within a method of an outer class.

Prof. Amruta Deshmukh


40
3.Method Local Inner Classes
• Inner class can be declared within a method of an outer class.
• Example 1: Method Local Inner Classes
• class OuterM {

• void outerMethod()
• {
• System.out.println("inside outerMethod");

• class Inner {

• void innerMethod()
• {
• System.out.println("inside innerMethod");
• }
• }
• //inner object
• Inner y = new Inner();
• y.innerMethod();
• }
• } Prof. Amruta Deshmukh
41
• public class Localinner {

• public static void main(String[] args) {


• // TODO Auto-generated method stub
• OuterM x = new OuterM();
• x.outerMethod();
•}

•}

Prof. Amruta Deshmukh


42
• //Example 2 Method Local Inner Classes
• class A
• {
• void methodA()
• {
• class B
• {
• void show()
• {
• System.out.println("Class B");
• }
• }
• B b1=new B();
• b1.show();
• }
• }
• class MCA
• {
• public static void main(String argc[])
• {
• A a1=new A();

• a1.methodA();
• }
• }
Prof. Amruta Deshmukh
43
4 Anonymous Classes
• Anonymous inner classes are declared without any name at all.
• They are created in two ways.
1.As a subclass of the specified type
2.As an implementer of the specified interface

• An inner class with no name is called anonymous inner class.


• Anonymous classes enables you to define and create object of class at
the same time.
• Generally, they are used whenever you need to override the method of
a class or an interface.
• An Anonymous class has access to the members of its enclosing class.
• An Anonymous class can have final variables.
• Anonymous classes are often used in GUI applications.
Prof. Amruta Deshmukh
44
Syntax
AnonymousInner an_inner = new AnonymousInner() {
public void my_method()
{ ........ ........
}
};

Prof. Amruta Deshmukh


45
• Anonymous Classes
• class Demo {
• void show()
• {
• System.out.println(
• "i am in show method of super class");
• }
• }
• public class Anonymous {
• static Demo d = new Demo() {

• void show()
• {
• System.out.println("i am in Flavor1Demo class");
• }
• };
• public static void main(String[] args) {
• // TODO Auto-generated method stub
• d.show();
• }
• }

Prof. Amruta Deshmukh


46
• Example 2 Anonymous Classes

• class A
• {
• void show()
• {
• System.out.println("Class A");
• }
• }
• class M1
• {
• static A a1=new A()
• {
• void show()
• {
• System.out.println("Class New");
• }
• };

• public static void main(String argc[])
• {
• a1.show();
• }
• }
Prof. Amruta Deshmukh
47
Abstract class in Java
• A class which is declared as abstract is known as an abstract class.
• It can have abstract and non-abstract methods.
• An abstract is a java modifier applicable for classes and methods in
java but not for Variables.
• It cannot be instantiated.
• Abstract class: is a restricted class that cannot be used to create
objects (to access it, it must be inherited from another class).

• Java Abstraction
• The major use of abstract classes and methods is to achieve
abstraction in Java.
• Abstraction is an important concept of object-oriented programming
that allows us to hide unnecessary details and only show the needed
information.

Prof. Amruta Deshmukh


48
Key Points to Remember
• We use the abstract keyword to create abstract
classes.
• We cannot create objects of an abstract class.
• It can have abstract and non-abstract methods.
• Abstract class must be inherited from another class.
• A subclass must override all abstract methods of an
abstract class.
• We can define static methods in an abstract class

Prof. Amruta Deshmukh


49
The Syntax for Abstract Class
• To declare an abstract class, we use the access modifier first, then the
"abstract" keyword, and the class name shown below.
• //Syntax:
• <Access_Modifier> abstract class <Class_Name> {
• //Data_Members;
• //Methods;
•}

Prof. Amruta Deshmukh


50
Example Abstract Class With Non Abstract Method
• package deshmukh;
• abstract class AbstractSimple
• {
• void show()
• {
• System.out.println("Abstract class");
• }
• }
• public class ATclass extends AbstractSimple {

• public static void main(String[] args) {


• // TODO Auto-generated method stub
• ATclass obj=new ATclass();
• obj.show();
• }

• }
Prof. Amruta Deshmukh
51
Example Abstract Class With Non Abstract Method and
Abstract Method
• package deshmukh;
• abstract class Book {
• public abstract void show();
• // method of abstract class
• public void display() {
• System.out.println("This is Java Programming");
• }
• }
• public class abstractclass extends Book {
• public void show()
• {
• System.out.println("abstract method");
• }
• public static void main(String[] args) {
• // TODO Auto-generated method stub
• abstractclass obj=new abstractclass();
• obj.show();
• obj.display();
• }
Prof. Amruta Deshmukh
• }
52
Abstract method:
• A method declared using the abstract keyword within an abstract
class and does not have a definition (implementation) is called an
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).
• An abstract method must be declared with an abstract keyword.

• Syntax for abstract method:


• abstract return_type method_name( [ argument-list ] );

Prof. Amruta Deshmukh


53
Example: Abstract Class With Abstract Method and non Abstract
Method
• abstract class Multiply {
• public abstract int MultiplyTwo (int n1, int n2);
• public abstract int MultiplyThree (int n1, int n2,
int n3);

• // regular method with body
• public void show() {
• System.out.println ("Method of abstract class
Multiply");
• }
•}

Prof. Amruta Deshmukh


54
• public class AbstractMethod extends Multiply {
public int MultiplyTwo (int num1, int num2) {
• return num1 * num2;
• }
• public int MultiplyThree (int num1, int num2, int num3) {
• return num1 * num2 * num3;
• }
• public static void main(String[] args) {
• // TODO Auto-generated method stub
• AbstractMethod obj=new AbstractMethod();
• System.out.println("Method two="+obj.MultiplyTwo(5,6));
• obj.show();
• System.out.println("Method
three="+obj.MultiplyThree(2,3,4));
• obj.show();
•}
}
Prof. Amruta Deshmukh
55
Example : Abstract Class With Inheritance Concept
• abstract class Fruit
• {
• abstract void show();
• }
• class Apple extends Fruit
• {
• public void show()
• {
• System.out.println("Apple");
• }
• }
• class Mango extends Fruit
• {
• void show()
• {
• System.out.println("Mango");
• }
• }
Prof. Amruta Deshmukh
56
• public class abstractC1 {

• public static void main(String[] args) {

• // TODO Auto-generated method stub


• Apple a1=new Apple();
• a1.show();
• Mango m1= new Mango();
• m1.show();

•}
•}

Prof. Amruta Deshmukh


57
Interfaces
• An interface is basically a kind of class.
• Like classes, interfaces contain methods and variables.
• But interfaces define only abstract methods and final variables. i.e.
• interface can be only abstract methods in the Java interface, not the
method body.
• Data fields contain only constants.
• It is used to achieve abstraction and multiple inheritance in Java.
• Therefore, it is the responsibility of the class that implements an
interface to define the code for implementation of these methods.

Prof. Amruta Deshmukh


58
Characteristics of an Interface
• An interface can have only abstract methods.
• Methods in an interface are always public.
• Variables in an interface are always static & final.
• An interface can extend other interfaces, just as a class can extend
another class. However, while a class can only extend one another class
an interface can extend any number of interfaces.
• Interface do not have constructor.
• It is used to achieve abstraction and multiple inheritance in Java.
• The interface in Java is a mechanism to achieve abstraction.

Prof. Amruta Deshmukh


59
The relationship between classes and interfaces
• As shown in the figure given below, a class extends another class, an
interface extends another interface, but a class implements an
interface.

Prof. Amruta Deshmukh


60
• Valid combinations
a. class extends class
b. class implements interface
c. interface extends interface

Prof. Amruta Deshmukh


61
Syntax:-
interface InterfaceName
{
variable declaration;
method declaration;
}
Here, interface is keyword and InterfaceName is any
valid java identifier.

Variables are declared as –


static final type variableName=value;
Prof. Amruta Deshmukh
62
Remember

• An interface can’t extend classes.


• Implementing Interfaces
• Using implements Keyword
class class_name implements interface_name
{ // body of class_name
}

Prof. Amruta Deshmukh


63
• Methods declaration will contain only a list of methods without any
body statement.

retun_type methodname1(parameterlist);

e.g. interface Item


{
static final int code=1001;
static final String name=“Raj”;
void display();
}

Prof. Amruta Deshmukh


64
Remember
• The code for method is not included in the interface.
• Interface is used only when we wish to implement multiple inheritance
feature in the program.
• Interfaces defines only abstract methods and final fields.

e.g. interface Area


{ final static float pi=3.14;
float compute(float x, float y);
void show();
}

Prof. Amruta Deshmukh


65
Example: Interface
• interface A2p
•{
• void printA2();
•}
• class InterfaceD implements A2p{
• public void printA2(){
• System.out.println("Hello");
•}
• public static void main(String[] args) {
• // TODO Auto-generated method stub

• InterfaceD obj=new InterfaceD();


• obj.printA2();
•}

•}
Prof. Amruta Deshmukh
66
• Example 2 interface
• interface xyz
• {
• void show();
• }

• class abcd implements xyz


• {
• public void show()
• {
• System.out.println("xyz");
• }
• public static void main(String args[])
• {

• abcd obj= new abcd();


• obj.show();
• }
• }
Prof. Amruta Deshmukh
67
Extending Interfaces
• Like classes, interfaces can also be extended i.e. an interface can be sub
interfaced from another interfaces. The new sub interface will inherit all
the members of the super interface in the manner similar to subclasses.
• This is achieved using keyword extends.

interface name2 extends name1


{ body of name2
}

Prof. Amruta Deshmukh


68
• We can put all constants in one interface and the methods in the other.
This will enable us to use the constants in classes where the methods
are not required.
interface Itemconstants
{
int code=1001;
String name=“Fan”;
}
interface Item extends Itemconstants
{
void display();
}

Prof. Amruta Deshmukh


69
Example: Interface with Single Level Inheritance
• interface interfaceX1
• {
• void show();

• }
• interface interfaceY1 extends interfaceX1
• {
• void print1();
• }
• public class classInterface implements interfaceY1
• {
• public void show()
• {
• System.out.println("Base interface in interfaceX1");
• }
• public void print1()
• {
• System.out.println("Derived interface in interfaceY1");
• }
Prof. Amruta Deshmukh
70
• public static void main(String[] args) {
• // TODO Auto-generated method stub
• classInterface obj=new classInterface();
• obj.show();
• obj.print1();

•}

•}

Prof. Amruta Deshmukh


71
Multiple inheritance in Java by interface
• If a class implements multiple interfaces, or an interface extends
multiple interfaces, it is known as multiple inheritance.

Prof. Amruta Deshmukh


72
Example : Class implements multiple interfaces (Different
Methods Name)

• interface interface1
•{
• void show1();
•}
• interface interface2
•{
• void show2();

•}

Prof. Amruta Deshmukh


73
• public class MultipleInterface implements
interface1,interface2 {
• public void show1() {
• System.out.println("First Interface");
• }
• public void show2()
• {
• System.out.println("Second Interface");
• }
• public static void main(String[] args) {
• // TODO Auto-generated method stub
• MultipleInterface obj=new MultipleInterface();
• obj.show1();
• obj.show2();
•}
•} Prof. Amruta Deshmukh
74
Example : Class implements multiple interfaces (Same Method)
• package deshmukh;
• interface interfaceAa
• {
• void show();
• }
• interface interfaceBb
• {
• void show();

• }
• public class MI implements interfaceAa , interfaceBb {
• public void show() {
• System.out.println("2 Base Interface method is same ");
• }

• public static void main(String[] args) {
• // TODO Auto-generated method stub
• MI obj=new MI();
• obj.show();
• }

• }
Prof. Amruta Deshmukh
75
Interface extends multiple interfaces
• interface interfaceA1
• {
• void show1();
• }
• interface interfaceK1
• {
• void show2();
• }
• interface interfaceC extends interfaceA1,interfaceK1
• {
• void show3();

•}

Prof. Amruta Deshmukh


76
• public class interfaceE implements interfaceC {
• public void show1() {
• System.out.println("Base First Interface");
• }
• public void show2()
• {
• System.out.println("Base Second Interface");
• }
• public void show3()
• {
• System.out.println("Child Second Interface");

• }
• public static void main(String[] args) {
• // TODO Auto-generated method stub
• interfaceE obj=new interfaceE();
• obj.show1();
• obj.show2();
• obj.show3();
• }
}

Prof. Amruta Deshmukh


77
Differences between abstract class and interface

Abstract class Interface

Abstract class can have abstract and Interface can have only
non-abstract methods. abstract methods.

2) Abstract class doesn't support Interface supports multiple


multiple inheritance. inheritance.

3) Abstract class can have final, non- Interface has only static and final
final, static and non-static variables.
variables.
4) Abstract class can provide the Interface can't provide the
implementation of interface. implementation of abstract class.

5) The abstract keyword is used to The interface keyword is used to


declare abstract class. declare interface.
Prof. Amruta Deshmukh
78
Abstract class Interface

6) An abstract class can extend An interface can extend another


another Java class and implement Java interface only.
multiple Java interfaces.
7) An abstract class can be An interface can be implemented
extended using keyword "extends". using keyword "implements".

8) A Java abstract class can have Members of a Java interface are


class members like private, public by default.
protected, etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Prof. Amruta Deshmukh
79
2.8Method in Java
• a method is a way to perform some task.
• Similarly, the method in Java is a collection of instructions that
performs a specific task.
• It provides the reusability of code.
• We can also easily modify code using methods.
• A method is a block of code or collection of statements or a set of
code grouped together to perform a operation.
• We write a method once and use it many times
• . We do not require to write code again and again.
• It also provides the easy modification of code,
• . The method is executed only when we call or invoke it.

Prof. Amruta Deshmukh


80
• A simple Java method requires a minimum of three items:
• 1. Visibility : public, private, protected
• 2. Return Type: void, int, double, (etc.)
• 3. name: whatever you want to call the method

Prof. Amruta Deshmukh


81
Return Values
• The void keyword, used in method should not return a value.
• If you want the method to return a value, you can use a primitive
data type (such as int, char, etc.) :

Prof. Amruta Deshmukh


82
Java Method Parameters and Arguments
• You can pass data, known as parameters, into a method.
• Information can be passed to methods as parameter. Parameters act
as variables inside the method.
• Parameters are specified after the method name, inside the
parentheses. You can add as many parameters as you want, just
separate them with a comma.

Prof. Amruta Deshmukh


83
Method Overloading,
• If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.
• If we have to perform only one operation, having same name of the
methods increases the readability of the program
• . Method overloading is one of the ways that java implements
polymorphism.
• The methods calls are resolved at compile time using method
signature. i.e. When java encounters a call to an overloaded method,
it simply executes the version of the method whose parameters
match the arguments used in the call.

Prof. Amruta Deshmukh


84
Method Overloading…
• Compile time error occurs if compiler can not match the arguments or if
more than one match is possible.
• In addition to overloading normal methods, constructors can also be
overloaded.
• Method Signature consists of-
1. Number of arguments passed to a function.
2. Data types of arguments
3. Sequence in which they are passed.
• e.g. TestOverloading.java

Prof. Amruta Deshmukh


85
Example : Method Overloading
• class Calculator
•{

• int addition(int var1, int var2)
• {
• return var1+var2;
• }
• int addition(int var1, int var2, int var3)
• {
• return var1+var2+var3;
• }

•}

Prof. Amruta Deshmukh


86
• public class Additionoverloading {

• public static void main(String[] args) {


• // TODO Auto-generated method stub

• Calculator obj = new Calculator();
• System.out.println(
• "Addition of two operands is"+obj.addition(10, 20));
• System.out.println(
• "Addition of three operands is "+obj.addition(10, 20,
30));

•}
•}

Prof. Amruta Deshmukh


87
Recursion
• Recursion is a process in which a method calls itself continuously.
• A method in java that calls itself is called recursive method.

Syntax: returntype methodname()


{
//code to be executed
methodname();//calling same method
}

Prof. Amruta Deshmukh


88
Java Recursion Example 1: Unlimited times

• package deshmukh;

• public class RE1 {


• static void p(){
• System.out.println("hello");
• p();
• }
• public static void main(String[] args) {
• // TODO Auto-generated method stub
• p();
• }

•}
Prof. Amruta Deshmukh
89
Java Recursion Example 2: Limited times
• package deshmukh;

• public class RE2 {


• static int count=0;
• static void p(){
• count++;
• if(count<=5){
• System.out.println("hello "+count);
• p();
• }
• }
• public static void main(String[] args) {
• // TODO Auto-generated method stub
• p();
• }

• }
Prof. Amruta Deshmukh
90
Static
• The main purpose of using the static keyword is to manage the
memory so that we can use the memory efficiently
• The static keyword in Java is mainly used for memory management.
• We can apply static keyword with variables, methods, blocks
and nested classes.
• The static keyword in Java is used to share the same variable or
method of a given class.
• The static keyword is used for a constant variable or a method that is
the same for every object of a class.

Prof. Amruta Deshmukh


91
1) Java static variable

• If you declare any variable as static, it is known as a static variable.


• The static variable can be used to refer to the common property of all
objects.
• Change in static variable value affects all objects.
• E.g. static int count;
• Static variable is shared by all the objects of the class.
• Static variables are, essentially, global variables.

Prof. Amruta Deshmukh


92
Example Static Variable
• package amruta;
• class sv
• {
• static int c=1;
• void a1()
• {
• c=c+4;
• System.out.println("method a1 value of c="+c);
• }
• void a2()
• {
• c=c+10;
• System.out.println("method a1 value of c="+c);
• }
• }

• public class Svariable {

• public static void main(String[] args) {


• // TODO Auto-generated method stub
• sv obj= new sv();
• sv obj1= new sv();
• obj.a1();
• obj1.a2();
• }
• } Prof. Amruta Deshmukh
93
Static Method
• The JVM runs the static method first
• It can be called without an Objects.
• Static method can access static members only.
• Static method is invoked using class name.
• <class name>.<method name> ( )
• Reference ‘this’ is never passed to a static method.
• main() method is a static method. It is an entry point method that is
called automatically.

Prof. Amruta Deshmukh


94
• Syntax:
• [access specifier] static [return type] [function name] (parameter list)

•{
• //body of the function
•}
• Calling Static Function
• In Java, we cannot call the static function by using the object. It is
invoked by using the class name.
• [class name].[method name]

Prof. Amruta Deshmukh


95
Example Static Method Call Same Class

• package deshmukh;

• public class StaticMethod2 {


• static int add(int a,int b)
• {
• return a+b;
• }

• public static void main(String[] args) {


• // TODO Auto-generated method stub
• System.out.println("Addition="+add(10,20));
• }

• }
Prof. Amruta Deshmukh
96
Example Static Method Call Another Class
• package deshmukh;
• class Adder{
• static int add(int a,int b)
• {
• return a+b;
• }
• }

• public class StaticMethod {

• public static void main(String[] args) {


• // TODO Auto-generated method stub
• System.out.println(Adder.add(11,11));
• }

• }

Prof. Amruta Deshmukh


97
static initialization blocks
• Sometimes initialization is required before main application starts, like
database connections.
• Executed before main( ) when class is loaded.
• Used for initializing static variables.
• A class can have more than one static blocks.
• If more than one static blocks exits in a program then called in the order
they appear in the source code.
static {
// manipulation of static variables
}

Prof. Amruta Deshmukh


98
Example Static Block
• package deshmukh;

• public class StaticBlock {

• static
• {
• // Print statement
• System.out.println("Static Block ");

• }
• public static void main(String[] args) {
• // TODO Auto-generated method stub
• System.out.println("Main Method ");
• }

• }
Prof. Amruta Deshmukh
99
Execution Order:

• There is an order in which static block/method/variable gets


initialized.
1.Static Block
2.Static Variable
3.Static Method

Prof. Amruta Deshmukh


100
Example :Execution Order:
• package deshmukh;

• public class SBVM {

• public static void main(String[] args) {


• // TODO Auto-generated method stub
• SBVM obj=new SBVM();

• System.out.println("Static Variable=" +count);


• System.out.println("Static Method");
• }
• static int count = 3;

• // Called even before Main Method
• static {
• System.out.println("Static Block");

• }

• }
Prof. Amruta Deshmukh
101
Use of “this” reference
• ‘this’ is a keyword in java.
• ‘this’ points to the current object.
• ‘this’ always holds address of an object which invokes the member
function.
• The keyword this can be used inside any method to refer to the current
object.
• Box(double w, double h, double d) {
this.width=w; this.height=h;
this.depth=d; }
Inside Box(), ‘this’ always refers to the invoking object.

Prof. Amruta Deshmukh


102
• “this” can also be used to:
1. Invoke current class constructor
2. Invoke current class method
3. Return the current class object
4. Pass an argument in the method call
5. Pass an argument in the constructor call

The most common use of the this keyword is to eliminate the confusion
between class attributes and parameters with the same name .

Prof. Amruta Deshmukh


103
Example 2:this Keyword
public class Main {
int x;
// Constructor with a parameter
public Main(int x) {
this.x = x;
}
// Call the constructor
public static void main(String[] args) {
Main myObj = new Main(5);
System.out.println("Value of x = " + myObj.x);
}
}
o/p- Value of x = 5
Prof. Amruta Deshmukh
104
Example 2:this Keyword
• package deshmukh;
• class Tk
• {
• int p;
• Tk(int p)
• {
• this.p=p;
• }
• void show()
• {
• System.out.println("p="+p);
• }
• }
• public class thiskeyword {

• public static void main(String[] args) {


• // TODO Auto-generated method stub
• Tk obj=new Tk(2);
• obj.show();

• }

• } Prof. Amruta Deshmukh


105
Native Method
• The native keyword is applied to a method to show that the method is
implemented in Native Code (c,c++) using JNI(Java Native Interface).
• The ‘native’ keyword is used before a method to indicate that it is
implemented in other language.
• Native methods allow you to use code from other languages
such as C or C++ in your java code. You use them when java
doesn't provide the functionality that you need.
• A method marked as native cannot have a body and should end with a
semicolon:
• [ public | protected | private] native [return_type] method ();
• Its used to improve the performance.
Its used for Machine level communication.

Prof. Amruta Deshmukh


106
Native Method
• We can use them to:
• implement an interface with system calls or libraries written in other
programming languages
• access system or hardware resources that are only reachable from the
other language
• integrate already existing legacy code written in C/C++ into a Java
application
• call a compiled dynamically loaded library with arbitrary code from Java

Prof. Amruta Deshmukh


107
Class Native
{
Static
{
System.LoadLibrary(“Native library path”);
}
public native void m();
}
Class Test
{
public static void main(String[] args)
{
Native n = new Native();
n.m();
}
}
Prof. Amruta Deshmukh
108
Important points about native Method
• For native methods implementation is already available in old languages
like C, C++ and we are not responsible to provide implementation.
Hence native method declaration should end with ; (semi-colon).
• We can’t declare native method as abstract.
• The main advantage of native keyword is improvement in performance
but the main disadvantage of native keyword is that it breaks platform
independent nature of java.

Prof. Amruta Deshmukh


109
Cloning Objects
• The object cloning is a way to create exact copy of an object. The clone()
method of Object class is used to clone an object.
• The java.lang.Cloneable interface must be implemented by the class
whose object clone we want to create.
• If we don't implement Cloneable interface, clone() method
generates CloneNotSupportedException.
• The clone() method is defined in the Object class. Syntax of the clone()
method is as follows:
• protected Object clone() throws CloneNotSupportedException

Prof. Amruta Deshmukh


110
Creating Copy of Java Object
• We can create a replica or copy of java object by
1. Creating a copy of object in a different memory location. This is called a
Deep copy.
2. Creating a new reference that points to the same memory location. This
is also called a Shallow copy.

Prof. Amruta Deshmukh


111
• Shallow copy
• This basically creates a new instance of the object and copies all the data
from the original data set to the newly created instance.
• This object will have an exact copy of all the fields of source object
including the primitive type and object references.
• If we make changes in shallow copy then changes will get reflected in
the source object.
• Example:
When we do a copy of some entity to create two or more than two
entities such that changes in one entity are reflected in the other
entities as well, then we can say we have done a shallow copy.
In shallow copy, new memory allocation never required for the
other entities, and the only reference is copied to the other entities.
The following example demonstrates the same.
• Both instances are not independent.
• it will copy the reference, not value

Prof. Amruta Deshmukh


112
Example :Shallow copy
• package deshmukh;
• class ABCD
•{
• int x = 30;
•}
• public class ShallowCopyExample {

• public static void main(String[] args) {



• ABCD obj1 = new ABCD();
• ABCD obj2 = obj1;
• obj2.x = 6;
• System.out.println("The value of x is: " + obj1.x);
•}
•}
Prof. Amruta Deshmukh
113
• Deep Copy
• When we do a copy of some entity to create two or more than two
entities such that changes in one entity are not reflected in the
other entities, then we can say we have done a deep copy.
• In the deep copy, a new memory allocation happens for the other
entities, and reference is not copied to the other entities. Each
entity has its own independent reference.
• This means that both source and destination objects are independent of
each other. Any change made in the cloned object will not impact the
source object.
• it will copy the reference, not value

Prof. Amruta Deshmukh


114
Example: Deep Copy
• package deshmukh;
• class ABC
• {
• int x = 30;
• }
• public class DeepCopyExample1 {

• public static void main(String[] args) {


• // TODO Auto-generated method stub
• ABC obj1 = new ABC();
• ABC obj2 = new ABC();

• obj2.x = 6;
• System.out.println("The value of x is: " + obj1.x);
• }
• }
Prof. Amruta Deshmukh
115
Differences Between Shallow Copy and Deep Copy

Shallow Copy Deep Copy

It is fast as no new memory is It is slow as new memory is


allocated. allocated.

Changes in one entity is reflected Changes in one entity are not


in other entity. reflected in changes in another
identity.

The default version of the clone() In order to make the clone()


method supports shallow copy. method support the deep copy,
one has to override the clone()
method.
A shallow copy is less expensive. Deep copy is highly expensive.

Cloned object and the original Cloned object and the original
Prof. Amruta Deshmukh
object are not disjoint. object are disjoint.
116
Advantage of OOPs over Procedure-oriented
programming language
1) OOPs make development and maintenance easier where as in
Procedure-oriented programming language it is not easy to manage if
code grows as project size grows.
2) OOPs provide data hiding whereas in Procedure-oriented
programming language a global data can be accessed from anywhere.
3) OOPs provide ability to simulate real-world event much more
effectively. We can provide the solution of real word problem if we
are using the Object-Oriented Programming language.

Prof. Amruta Deshmukh


117

You might also like