Você está na página 1de 36

4 OOPS and its

application in Java
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 Java
for inheritance
Concrete classes in Java
Polymorphism
Compile time polymorphism -
- Overloading of methods
Run time polymorphism --
Overriding of methods
Method Overriding rules and
method overloading rules
Introduction to Object class
and it's methods
Encapsulation
Protection of data
Java Bean, POJO
Getters/Setters
Memory management in Java
Heap
Stack
2
Class
Definition:
A class is a blueprint or prototype
Defines the variables and methods
common 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.
2
Object
An object is a chunk of memory:
holds field values
holds an associated object type

All objects of the same type share code
they all have same object type, but can
have different field values.
Object & Class Comparison
Class Object
Class is a type/template
for similar objects
Object is an instance of
the class, with each
instance behaving
identically
Class is purely a static
concept, represented by
program text
Object is dynamic/run-
time entity, occupying
space in memory
Object Interaction Software World
As in real world, Software Objects also interact by
passing 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 the
methods of the objects.



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 inherits all the fields and
methods of its (possibly numerous)
super classes

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

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 user
of the class need not to change their code.
Inheritance
We can understand this better by considering the is
a idea
A subclass object is a super class object
However, some extra instance variables and
methods may have been added and some other
methods 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
2
Inheritance and is a
Animal
is a
is a
is a
Bird
Human
Fish
Bird, Human and Fish are all Animals
However, an Animal is not necessarily a
Bird, Human or Fish

Constructors

Usage of this
Inside a constructor, you can use this to invoke
another constructor in the same class. This is
called explicit constructor invocation. It MUST
be the first statement in the constructor body if
exists.
this can also be used as a reference of the current
object. It CANNOT be used in a static method

Usage of super
Inside a constructor, you can use super to
invoke constructor of the parent class. This is
called explicit constructor invocation. It MUST
be the first statement in the constructor body if
exists.
super can also be used as a reference of the
super class object. It CANNOT be used in a
static method.
Example: usage of this as a reference of the
current 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);
}
. . .
}
Data Abstraction
It is a process of hiding data by encapsulating in a
class and wraps through access specifiers.

Abstract class
Abstract classes created using the abstract
keyword:
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 method is decorated with an extra abstract
keyword.
Abstract classes can not be instantiated! So the
following is illegal:
MotorVehicle m = new MotorVehicle;
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 abstract class Motor Vehicle {
private double speed, maxSpeed;
void accToMax( ) { speed = maxSpeed;}
public abstract void gas( );
Abstract Class Syntax
abstract class Class Name
{ ...

abstract Type MethodName1();

Type Method2()
{
// method body
}
}
When a class contains one or more abstract methods, it
should be declared as abstract class.
The abstract methods of an abstract class must be
defined in its subclass.
We cannot declare abstract constructors or abstract
static methods.
Abstract Classes Properties
A class with one or more abstract methods is
automatically abstract and it cannot be
instantiated.
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 by
implementation them.
A subclass that does not implement all of the
super class abstract methods is itself abstract; and
it cannot be instantiated
Example of Abstract Classes
Example:
abstract class 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() { .... }
}

Creating and Using Interfaces
Interface
Keyword interface
Has set of public abstract methods
Can contain public final static data
Using interfaces
Class specifies it uses interface with keyword
implements
Multiple interfaces use comma-separated list
Class must define all abstract methods 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
Using interfaces (continued)
Interfaces used in place of abstract classes
Used when no default implementation
Typically public data types
Interface defined in its own .java file
Interface name same as file name

1 // Fig. 27.5: Shape.java

2 // Definition of interface Shape

3

4 public interface Shape {

5 public abstract double area();

6 public abstract double volume();

7 public abstract String getName();

8 }

8 }
Difference between Abstract Class and Interface
An abstract class is a class containing several
abstract methods.
Each abstract method is prefixed with the
keyword abstract.
An abstract class can not be instantiated but can
be extended (subclassed).
An interface contains only abstract methods and
constants. Each abstract method is not prefixed
with the keyword abstract.
An interface can only be implemented.

Polymorphism
Many-forms
Two types:
Compile time: resolved at compile time
(method overloading)
Runtime time: resolved at runtime.
(method overridding)

Method Overloading.
If a method has same name but a different
argument 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);
}

}


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.

Rules continued
Method can be overload in same class as well
as 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.
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);
}
}

Overridde
n
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 than
level 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.
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.
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
static and private methods are implicitly final
Program can inline final methods
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

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.



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.



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 Tree
class .In addition to the attributes of Tree, the Mango
class has yield attribute. Override the displayTree() and
annualUpdate() and suitable Constructor.



Thank You

Você também pode gostar