Object Oriented Programming in Java. Characteristics of Object Oriented Programming Object...

Preview:

Citation preview

Object Oriented Programming in Java

Characteristics of Object Oriented Programming Object Programming classes Encapsulation Polymorphism Inheritance Dynamic Binding

What are Objects?

Object are s/w programming models consisting of variable and related methods.

S/w objects are modeled after real life objects.

Method 1

Method 2

Variable 1

Variable 2

S/w Objects Examples:

Buttons Scrollbar Menu Spreadsheet

Characteristics of Real life Objects:

State Behavior

Characteristics of S/W Objects:

State (Variable) Behavior (functions/methods)

What are Classes?

A class is a s/w construct that defines the instance variables and methods of an object.

A class is itself not an object.

What are Classes?

A class is a blueprint / template that defines structure of similar objects.

Advantages of Class

ModularityInformation hidingReusability

Benefits of Encapsulation

Encapsulating related variables and methods into a neat s/w programming model that provides two benefits.1) Modularity

2) Information hiding

P O L Y M O R P H I S M

The same message sent to the different objects result in behavior that is dependent on the nature of the object receiving the message.

I N H E R I T A N C E

Inheritance allows to define new classes and behavior based on existing classes to obtain code reusability and code organization.

I N H E R I T A N C E

Employee

Part-time Employee Full-time Employee

Manager Engineer Admin.

staff

Consultant Daily Wage Worker

Advantage of Inheritance

Reduces s/w development time

Dynamic Binding

Objects could come from anywhere possibly across the network. You need to be able to send messages to objects without having to know their specific type at the time you write your code. It provides maximum flexibility while a program is executing.

Date tomorrow = new Date( );

This single statement actually performs three functions:

Declaration :

Instantiation:

Initialisation

Creating, Declaring & Instantiating an object:

OBJECT ORIENTED PROGRAMMING IN JAVA

Date tomorrow;Instantiation of an object:

Contd.

Declaration of an Object:

The new operator instantiates a class by allocating memory for a new object of that type. The new requires a single argument: a call to a constructor method.

Contd.

Declaration of an Object:

Constructor methods are special methods provided by each Java class that are responsible for initializing new objects of that type. The new operator creates the object and the constructor initializes it.

Contd.

Constructor Methods:

Date tomorrow = new Date( ) does not take any argument.

Declaration of an Object:

A constructor that takes no argument is called default constructor. Like Date ( ), most classes have at least one default constructor.

Contd.

Declaration of an Object:

If a class has multiple constructors, they all have the same name but different number or types of arguments. Date class type provides with another constructor that initialises the new Date with a year, month,day and date.

Date HisBirthday = new Date (1971, 6, 30);

Declaration of an Object:

No need of keeping track of objects for destroying.

The Java runtime environment has a garbage collector that frees the memory used by objects that are no longer needed.

Contd.

OOP : GARBAGE COLLECTOR

An object is eligible for garbage collection when there are no more references to objects.

The garbage collector run in a low-priority thread and runs both synchronously and asynchronously depending on the situation and the system on which Java is running.

OOP : GARBAGE COLLECTOR

A class declaration looks like this:[modifiers] class ClassName [extends SuperClassName]

[implements Interface Names]{--------}

The items between the square are optional.

Contd.

OOP : CLASS DECLARATION

modifiers declares whether the class is public, abstract or final.

extends is used to specify a single inheritance mechanism.

Implements is used to specify multiple inheritance.

OOP : CLASS DECLARATION

In Java, every class has a superclass. If you don’t specify a superclass for your class it is assumed to be the Object class (declared in Java.lang).

The keyword extends is used to specify the superclass.

Contd.

OOP : Declaring a class’s superclass

Class NameOfClass extends SuperClassName {

----------

----------

}

OOP : Declaring a class’s superclass

The Public modifier declares that the class can be used by objects outside the current package.

Contd.

OOP : Public, Abstract and Final Class

The abstract modifiers declares that the abstract class may contain methods (without any implementation). These classes are intended to be sub-classed and can not be instantiated.

OOP : Public, Abstract and Final Class

The Final modifier declares that this class can not be sub-classed for security reasons & design reasons.

It does not make sense for a class to be both final and abstract.

OOP : Public, Abstract and Final Class (Contd...)

Package:

A package is a container of related classes and interfaces

Used to access related classes as well as to hide the internals of a package.

Contd.

Package:

Package is declared using package keyword Package my-package; Package java.awt.image; All of Java built-in classes are put under the Java

package. Six sub packages are defined under the Java package

Java.lang, Java.awt, Java.io, Java.net, Java.applet, Java.util

Object Oriented Feature

The Import Statement The Import statement loads existing classes for

using their definition and methods.

Contd.

Object Oriented Feature

Example: Importing the class from the package: import

Java.awt.Graphics; Importing the entire package that the class

belongs to: Import Java.awt.*.

OOP : Access control mechanism:

PRIVATEPROTECTEDPUBLICSTATICFINALABSTRACT

OOP : Access control mechanism:PRIVATE:

A PRIVATE MEMBER AND METHOD ARE ACCESSIBLE ONLY TO THE CLASS IN WHICH IT IS DEFINED.

Contd. ...

EXAMPLE: class Alpha { private int privateX;

private void privateMethod( ){System.out.println(“PrivateMethod”);}}

Contd. ...

OOP : Access control mechanism:PRIVATE:

OOP : Access control mechanism: PRIVATE:

Class Beta {void accessMethod ( ) {Alpha a = new Alpha ( ) ;a.privateX = 15; // illegala.privateMethod ( ) ; // illegal}}

Contd.

Beta class cannot access private variable and private methods on an object of type Alpha because Beta is not the type of Alpha.

OOP : Access control mechanism:PRIVATE:

OOP : Access control mechanism: PRIVATE:

Objects of same type can access to one another’s private members. This is because access restriction apply at the class or type level rather than at the object level.

Contd.

Example:

class Alpha {private int privateX ;boolean isEqualTo (Alpha anotherAlpha) {if (this.privateX= =anotherAlpha.privateX) //legalreturn true;else return false;}}

this is a java language keyword that refers to the current object.

Protected

It allows the class itself, subclasses and all classes in the same package to access the members.

Contd. ...

Protected

Package Greek ;Class Alpha { //declared in a Greek packageprotected int protectX ;protected void protectedMethods ( ) {system.out.println(“protectedMethods”) }}

Protected

Suppose class Gama is also declared to the member of the Greek package. The class can legally access an alpha object’s privateX member variable and protected.

Protected

Methods Package Greek ;

Class Gamma{void access Method ( ) {Alpha a = new Alpha ( ) ;a.protectX=10; // legala.protectedMethod ( ) ; // legal}}

Public

Any class in any package has access to class’s public member. Declare members to be public only if such access cann’t produce undesirable results if an outsider uses them.

Contd. ...

Public

Package Greek ;public class Alpha {

public int publicX;public void publicMethod ( ) {System.out.println (“publicMethod”);}

}

Contd. ...

Public

Beta class is defined in a different package and not a sub class of Alpha.

Contd.

Public

Package Roman ;import Greek.*;

Class Beta {void accessMethod ( ) {Alpha a=new Alpha ( ) ;a.publicX = 10; // legala.publicMethod ( ) ; // legal}

}

Beta can legally inspect and modify the public X and public method in Alpha class.

OOP : What Method does subclass inherit

Subclasses inherit those superclass method declared as public or protected

SubClass inherit those superclass methods declared with no acces specifier as long as the subclass is in the same package as the superclass.

Contd.

OOP : What Method does subclass inherit

Subclass don’t inherit a superclass’s method if the subclass declares a method using the same name. The method in the subclass is said to override the one in the superclass.

Subclass do not inherit the superclass private methods

Static

Used with methods and variables but not with classes.

used to specify a method that can be declared only once such as main ( )

Contd.

Static

no sub classes are allowed to implement the method of the same name.

static methods are not over ridden in subclasses.

Final

Used with classes, methods and variables

when used with a class this class never have any subclass

Contd ..

Final

when used with any method, this method cannot overridden.

When used with any member variable the variable remains constant.

Final

example 1: // final used with a classfinal class classFinal {

::

}class classInherited extends classFinal{ // illegal

:}

Contd ...

Final

example 2:class NeverChanging {// a Final variableFinal int unchangeble = 21;// a Final methodFinal int unchangingMethod (int a, int b) {}}

Final:

It defines a complete programming interface, providing its subclasses with the method declaration for all of the methods necessary to support the interface.

Abstract classes & methods

An abstract class is a class that can only be sub-classed - it can not be instantiated.

It contains abstract methods with no implementation. It defines abstract methods.

Used to create a template class or methods. Similar to function prototypes in C or C++.

Abstract classes & methods

abstract class GraphicsObject {int x , y;:void moveTo (int newX, int newY) {:}abstract void draw ( ) ; // to be implemented by all

// subclasses}

Contd. ...

Abstract classes & methods:

Each non-abstract subclass of Graphic object such as circle and rectangle has to provide an implementation for the draw method.

class Circle extends GraphicObject {void draw ( ) {:}

}

Contd.

Abstract classes & methods:

class Rectangle extends GraphicObject {void draw ( ) {:}}

Contd.

Abstract classes & methods:

An abstract class is not required to have an abstract method in it. But any class that has an abstract method in it or does not provide an implementation, any abstract method declared in its superclass must be declared as an abstract class.

OOP : Interface

An interface is a collection of abstract methods (without implementations) and constant values

Interfaces add most of the functionality that is required for many applications which would normally resort to using multiple inheritance in a language such as C++

Contd. …

OOP : Interface

Java program can use interface to make it unnecessary for related classes to share a common abstract super class to add methods to object.

Accessing multiple implementation of an interface through an interface reference variable is the most powerful way that Java achieves run-time polymorphism.

Contd. …

OOP : Interface

Because dynamic lookup of a method at run-time incurs a significant overhead when compared with normal method invocation in java, you should be careful not to use interfaces casually in performance critical code.

Contd. …

OOP : Interface

A class may be declared to directly implement one or more interfaces, meaning that any instance of the class implements all the abstract methods specified by the interface or interfaces.

Contd. …

JAVA OVERVIEW (CONTD...)

OOP : Interface Declaration

interface Countable { the interface body; }

[Public] interface InterfaceName [extends list of SuperInterfaces]{ the interface body ------- }

OOP : Interface

The public access specifies indicates that the interface can be used by any class in any package. If you do not specify that your interface is public, then your interface will only be accessible to classes that are defined in the same package as the interface.

OOP : Interface

The extends clause is similar to the extends clause in a class declaration. However an interface can extend multiple interface (a class can only extend one), and an interface cannot extend classes.

OOP : Interface Example

interface Collection{

int MAXIMUM = 500;

void add (Object obj);

void delete (Object obj);

int currentCount( );

}

Example: Recursionclass Factorial {// This is a recursive function int fact (int n) {int result,if (n==1) return 1; elseresult = n * fact(n- 1);return result;}}

AN OVERVIEW OF JAVA (CONTD...)

class Recursion {public static void main(String args [ ] {Factorial f = new Factorial( );System.out.println ("factorial of 3 is" +f.fact(3));}}

AN OVERVIEW OF JAVA (CONTD...)

Recommended