Upload
aparnajanwalkar
View
215
Download
0
Embed Size (px)
Citation preview
8/12/2019 4OOPS (2 Days)
1/36
4 OOPS and its
application in Java
8/12/2019 4OOPS (2 Days)
2/36
Topics: Classes and Objects
Defining a class Defining instance variables and
methods
Creating objects out of a class
Method calls via object references
Abstraction Interfaces and Abstract classes
Abstract and non-abstract methods
Inheritance
Extends and implements keywords
in Java Super class and Sub class
this keyword, super keyword in Javafor inheritance
Concrete classes in Java
Polymorphism
Compile time polymorphism -- Overloading of methods
Run time polymorphism --Overriding of methods
Method Overriding rules andmethod overloading rules
Introduction to Object classand it's methods
Encapsulation
Protection of data
Java Bean, POJO
Getters/Setters
Memory management in Java
Heap
Stack
8/12/2019 4OOPS (2 Days)
3/36
2
Class
Definition:
A class is a blueprint or prototype
Defines the variables and methodscommon to all objects of a certain kind.
The Benefits of Classes
Reusability -- Software programmers use the
same class, and the same code to create many
objects.
8/12/2019 4OOPS (2 Days)
4/36
2
Object
An object is a chunk of memory:
holdsfield values
holds an associated object type
All objects of the same type share code
they all have same object type, but canhave different field values.
8/12/2019 4OOPS (2 Days)
5/36
Object & Class Comparison
Class ObjectClass is a type/template
for similar objects Object is an instance ofthe class, with eachinstance behaving
identically
Class is purely a staticconcept, represented by
program textObject is dynamic/run-time entity, occupying
space in memory
8/12/2019 4OOPS (2 Days)
6/36
Object Interaction Software World
As in real world, Software Objects also interact bypassing messages.
In Software World, messages are dispatched to
Methods : which defines the behavior of the object
for a message Code to be executed by an object (to invoke a
behavior of an object), when a message is sent to it
is known as a Method.
Message passing is achieved by invoking themethodsof the objects.
8/12/2019 4OOPS (2 Days)
7/36
The class hierarchy
Classes are arranged in a hierarchy
The root, or topmost, class is Object
Every class but Object has at least one
super class.
A class may have subclasses
Each class inheritsall the fields and
methods of its (possibly numerous)super classes
8/12/2019 4OOPS (2 Days)
8/36
Encapsulation
Hides the implementation details of a class
Forces an interface to access the data.
Makes the code more maintainable.
It encapsulates all members within class
Data can hide by using access specifiers.
MyDate
+Today :Date
getToday() : Date
setToday(Date d);
8/12/2019 4OOPS (2 Days)
9/36
Benefits of Encapsulation
The fields of a class can made read-only or
write-only.
A class can have total control over what data
should store in fields.
The user of a class do not know how data stores
in class.
A class can change Data Type of filed and userof the class need not to change their code.
8/12/2019 4OOPS (2 Days)
10/36
Inheritance We can understand this better by considering the is
aidea
A subclass object is a super class object
However, some extra instance variables andmethods may have been added and some othermethods may have been changed
Note that is a is a one way operation
Subclass is a super class (specific "is a" general)
With modifications / additions Super class is NOT a subclass (general not "is a"
specific
Missing some properties
Ex: Bird is a Animal
8/12/2019 4OOPS (2 Days)
11/36 2
Inheritance and is a
Animal
is a
is ais a
Bird
Human Fish
Bird, Human and Fish are all Animals However, an Animal is not necessarily a
Bird, Human or Fish
8/12/2019 4OOPS (2 Days)
12/36
Constructors
8/12/2019 4OOPS (2 Days)
13/36
Usageof this
Inside a constructor, you can usethisto invokeanother constructor in the same class. This is
called explicit constructor invocation. It MUST
be the first statement in the constructor body if
exists.
thiscan also be used as a reference of the current
object. It CANNOTbe used in a static method
8/12/2019 4OOPS (2 Days)
14/36
Usage ofsuper
Inside a constructor, you can usesuperto
invoke constructor of the parent class. This is
called explicit constructor invocation. It MUST
be the first statement in the constructor body ifexists.
supercan also be used as a reference of the
super class object. It CANNOTbe used in astatic method.
8/12/2019 4OOPS (2 Days)
15/36
Example: usage of thisas a reference of thecurrent object
class Body {
private long idNum;
private String name;
private Body orbits;
private static long nextID = 0;
private static LinkedList bodyList =
new LinkedList();. . .
Body(String name, Body orbits) {
this.name = name;this.orbits = orbits;
}. . .private void inQueue() {
bodyList.add(this);}
. . .
}
8/12/2019 4OOPS (2 Days)
16/36
Data Abstraction
It is a process of hiding data by encapsulating in a
class and wraps through access specifiers.
8/12/2019 4OOPS (2 Days)
17/36
Abstract class
Abstract classes created using the abstractkeyword:
public abstract class MotorVehicle { }
In an abstract class, several abstract methods are
declared.
An abstract method is not implemented in the class, only
declared. The body of the method is then implemented in
subclass.
An abstract methodis decorated with an extra abstract
keyword. Abstract classes can not be instantiated! So the
following is illegal:
MotorVehicle m = new MotorVehicle;
8/12/2019 4OOPS (2 Days)
18/36
Abstract methods
Abstract methods are declared but do not
contain an implementation.
For example, the Motor Vehicle class may
have an abstract method gas( ):
public abstractclass Motor Vehicle {
private double speed, maxSpeed;
void accToMax( ) { speed = maxSpeed;} public abstractvoid gas( );
8/12/2019 4OOPS (2 Days)
19/36
Abstract Class Syntax
abstractclass Class Name
{ ...
abstractType MethodName1();
Type Method2(){
// method body
}
}
When a class contains one or more abstract methods, itshould be declared as abstract class.
The abstract methods of an abstract class must bedefined in its subclass.
We cannot declare abstract constructors or abstractstatic methods.
8/12/2019 4OOPS (2 Days)
20/36
Abstract Classes Properties
A class with one or more abstract methods isautomatically abstract and it cannot beinstantiated.
A class declared abstract, even with no abstract
methods can not be instantiated. A subclass of an abstract class can be instantiated
if it overrides all abstract methods byimplementation them.
A subclass that does not implement all of thesuper class abstract methods is itself abstract; andit cannot be instantiated
8/12/2019 4OOPS (2 Days)
21/36
Example of Abstract Classes
Example:abstractclass Stack{
abstract void push(Object o);
abstract Object pop();
}
public class ArrayStack extends Stack{.... // declare elems[] and top;void push(Object o) { elems[top++] = o; }Object pop() { return elems[--top]; }
}
class LinkedStack extends Stack{.... // declare ...void push(Object o) { .... }Object pop() { .... }
}
8/12/2019 4OOPS (2 Days)
22/36
Creating and Using Interfaces
Interface
Keyword interface
Has set of public abstractmethods
Can contain public final staticdata
Using interfaces
Class specifies it uses interface with keyword
implements
Multiple interfaces use comma-separated list
Class must define all abstractmethods in interface Must use same number of arguments, same return
type
Using interface like signing a contract
"I will define all methods specified in the interface
8/12/2019 4OOPS (2 Days)
23/36
Using interfaces (continued)
Interfaces used in place of abstractclasses Used when no default implementation
Typicallypublicdata types
Interface defined in its own .javafile
Interface name same as file name
1 // Fig. 27.5: Shape.java
2 // Definition of interface Shape
3
4publicinterfaceShape {
5 publicabstractdoublearea();
6 publicabstractdoublevolume();
7 publicabstractString getName();
8 }8 }
8/12/2019 4OOPS (2 Days)
24/36
8/12/2019 4OOPS (2 Days)
25/36
Polymorphism
Many-forms
Two types:
Compile time: resolved at compile time
(method overloading)
Runtime time: resolved at runtime.
(method overridding)
8/12/2019 4OOPS (2 Days)
26/36
Method Overloading.
If a method has same name but a differentargument list in a same class is overload
method of the existing method.class overload{
public void show(){
System.out.println(Default show
method);
}
public void show(int i)
{
System.out.println(Parameterised show
method);
}
8/12/2019 4OOPS (2 Days)
27/36
Rules for method overloading..
The argument list of calling statement must
different enough to allow unambiguous
determination of the proper method call.
The return type of a method can be different,but it is not sufficient for the return type to
make the difference.
The argument can be differ in their count, type
or their order in method declaration.
8/12/2019 4OOPS (2 Days)
28/36
Rules continued
Method can be overload in same class as wellas in its child class.
It is also called as early binding or more
specifically we can say it is Compile time
polymorphism.
Compiler will decide which method should
get called based upon the parameters passed
during method call.
8/12/2019 4OOPS (2 Days)
29/36
2
Method Overriding
If a method in subclass has same name,
return type and argument list match with the
method in super class then the new method is
said to override the old one.
Class Animal
{
public void eat() {
System.out.println(Animal
Eat method);
}
}
Class Horse extends
Animal
{
public void eat() {
System.out.println(Hor
se Eat method);
}
}
Overridden
8/12/2019 4OOPS (2 Days)
30/36
Rules for method Overriding
The argument list should exactly match with
overridden method.
The return type must be same of super class.
The access level cant be more restrictive thanlevel use in super class.
Overridden method cant throw any new or wider
exception than the overridden method. We cant override the method marked final in
super class.
8/12/2019 4OOPS (2 Days)
31/36
Rules for method Overriding
Static methods can not be override.
The overriding method can throw
unchecked(runtime) exception regardless
that the overridden method has declared
exception.
Constructor cant override.
8/12/2019 4OOPS (2 Days)
32/36
Use of Final Declaring variables final
Indicates they cannot be modified after declaration
Must be initialized when declared
Declaring methods final
Cannot be overridden in a subclass staticandprivatemethods are implicitly final
Program can inline finalmethods
Actually inserts method code at method call locations
Improves program performance
Declaring classes final
Cannot be a subclass (cannot inherit from it)
All methods in class are implicitly final
8/12/2019 4OOPS (2 Days)
33/36
Assignment
WAP in java for the following inheritance:
Student
Test Sports
Result
WAP to demonstrate the use of constructors in inheritance
Default/no parameter constructor
1param
2 param
WAP to demonstrate the use of super keyword in inheritance.
8/12/2019 4OOPS (2 Days)
34/36
Assignment
WAP in java to demonstrate the use if this keyword
WAP to demonstrate the use of abstract classes and
abstract method in inheritance.
WAP for creating a interface STACK, which will contain 2
abstract methods: push() & pop(). Implement them in a
demo class.
WAP to demonstrate
one interface inheriting other interface.
One abstract class implementing interface.
8/12/2019 4OOPS (2 Days)
35/36
Assignment
WAP in java to demonstrate the use of final keyword
WAP for method overloading to find the area of:
square
Circle Rectangle
Cylinder
Define a Mango object which is derived from the Treeclass .In addition to the attributes of Tree, the Mango
class has yield attribute. Override the displayTree() and
annualUpdate() and suitable Constructor.
8/12/2019 4OOPS (2 Days)
36/36
Thank You