+ All Categories
Home > Documents > OOP in Java

OOP in Java

Date post: 14-Nov-2014
Category:
Upload: api-3731415
View: 429 times
Download: 5 times
Share this document with a friend
Popular Tags:
35
Object-Oriented Programming
Transcript
Page 1: OOP in Java

Object-Oriented

Programming

Page 2: OOP in Java

What is Object-Oriented Programming?

•A set of implementation techniques that:–can be done in any programming language–may be very difficult to do in some

programming languages•A strong reflection of software engineering

–abstract data types–information hiding (encapsulation)

Page 3: OOP in Java

What is Object-Oriented Programming?

•A way of encouraging code reuse–produces more malleable systems

•A way of keeping the programmer in touch with the problem

–real world objects and actions match program objects and actions

Page 4: OOP in Java

Terms normally associated with OOP

• abstraction

• encapsulation

• information hiding

• inheritance

• polymorphism

Page 5: OOP in Java

Abstraction

• Functions – Write an algorithm once to be used in many situations

• Objects – Group a related set of attributes and behaviors into a class

• Frameworks and APIs – Large groups of objects that support a complex activity.

Frameworks can be used “as is” or be modified to extend the basic behavior.

Page 6: OOP in Java

OO in Java•Language elements:

> Class-based object-oriented programming language with inheritance> A class is a template that defines how an object will look and behave once instantiated

•Java supports both instance and class (static) variables and methods

•Nearly everything is an object•Objects are accessed via references•Object behavior can be exposed via public

methods•Objects are instantiated using the new construct

Page 7: OOP in Java

Classes Classes•A class defines the characteristicsof similar objects

– a specification•Objects of the same class aresimilar with respect to:

– Interface– Behavior– State space (set of

possiblestates, and state

transitions)•Classes are used to instantiatespecific objects (each with possiblydifferent state values)

Page 8: OOP in Java

Class

• most fundamental aspect of object-oriented programming

• template or prototype that defines a type of object

• a blueprint from which an object is actually made

• describes the state or the data that each object contains

• describes the behavior that each object exhibits

• classes in Java support three key features of OOP:

Encapsulation

Inheritance

Polymorphism

Page 9: OOP in Java

public class MyPoint { // attributes private int x; private int y; // methods public void setX(int n) { x = n; } public void setY(int n) { y = n; } public int getX() { return x; } public int getY() { return y; } public void display() { System.out.println("(" + x + "," + y + ")"); }}

Page 10: OOP in Java

• In the MyPoint class, x and y are called data members, instance variables or attributes

• setX(int n), setY(int n), getX(), geY() and display() are called methods

Page 11: OOP in Java

Object

• instance of a class

• in order to create an instance from a class definition, use the new keyword

MyPoint p = new MyPoint();

p is a reference variable

pPoint Object

x:0

y:0

Page 12: OOP in Java

Objects•An object possesses:– Identity a means of distinguishing it from other objects– State what the object remembers – Interface what messages the object responds to– Behavior what the object can do

•Objects are: – Building blocks for systems – Identifiable abstractions of real world objects

Page 13: OOP in Java

Instance variables or attributes

• define the state of an object in a class.

• can also be objects.

Methods

• functions that provide processing to the object’s data.

• determine the behavior of an object.

• The collection of all publicly available methods is called the class

interface.

Page 14: OOP in Java

Message and Object Communication•Objects communicate via messages•Interfaces define the set of valid messages that an object can receive•Messages, in Java, correspond to method calls (invocations)•Senders need a reference to the target object to send amessage

Page 15: OOP in Java

Accessing State•State information can be accessed directly or by usingmessages•Using messages:

–eliminates the dependence on implementation–allows the developer to hide the details of the

underlying implementation•“Accessor” messages are usually used instead of accessing state directly

–example: getSpeed() may simply access a state value called “speed” – or it could hide (or later be replaced by) a calculation to obtain the same value

Page 16: OOP in Java

Encapsulation

• Hides the implementation details of a class

• Forces the user to use an interface to access data

• Makes the code more maintainable

Page 17: OOP in Java

Accessing Object Members

• The dot notation: <object>.<member>

• to access the members of the class, use the dot operator

p.setX(20);

p.display();

• the dot operator is used to access object members including attributes and methods

• Examples:obj1.setNum (47);

obj1.num = 47; //only allowed if x is public

Page 18: OOP in Java

Example of bad class design:

class MyTime { public int seconds; public int minutes; public int hour;}

Client code can access data members directly:

MyTime time1 = new MyTime();

time1.seconds = 70; //no checking

time1.minutes = 70; // no checking

Page 19: OOP in Java

Client code can access data members directly:

MyTime time1 = new MyTime();

time1.setSeconds(70); //error will be handled in the// method

A better design:

class MyTime { private int seconds; private int minutes; private int hour;public void setSeconds(int

sec) { if ((sec >= 0) && (sec

<=59)) seconds = sec; else // error handling code}

Page 20: OOP in Java

Constructors

• A constructor is a method that is automatically invoked when an object is created. It is normally used to initialize data members.

• It has the same name as the name of the class. It can receive parameters but it has no return value

• Examplepublic class MyPoint {private int x;private int y;// constructorpublic MyPoint (int a,int b) {

x = a; y = b;}

Page 21: OOP in Java

Default Constructor

• If the programmer did not provide any constructor, a default no-argument constructor is automatically provided.

The default constructor takes no arguments

The default constructor has no body

• Enables the user to create object instances with new Xxx() without having to write a constructor

• If the programmer writes a constructor, the default constructor is not anymore provided.

Page 22: OOP in Java

Constructing and initializing objects

Calling new ...() causes the following events to occur:

• memory is allocated for the new object and instance variables are initialized to their default values

• explicit attribute initialization is performed

• the appropriate constructor is executed

Page 23: OOP in Java

Declaring

MyPoint p;

allocates space only for the reference. No object is created unless the new operator is invoked.

MyPoint p = new MyPoint(10,20);MyPoint q =p;q.setX(50);p.display(); // displays (50,20)

Page 24: OOP in Java

• In the MyPoint class, in the method display(), which x and y values are displayed? They are the x and y values of the object which invoked display.

Example:MyPoint p = new MyPoint(20,20);p.display();

--> the x and y values of the object referenced by p is displayed.

Page 25: OOP in Java

The this reference

• How does display know that it is the x and y values of the object referenced by p that is supposed to be displayed?

• When a method is invoked by an object, the object reference is implicitly transmitted as a hidden first argument to the method. Inside the method, the reference has a name and it is called this.

Page 26: OOP in Java

public class MyPoint {

private int x;

private int y;

public MyPoint(int x,int y) {

this.x = x;

this.y = y;

}

}

Page 27: OOP in Java

Method Overloading

• Java allows the definition of two or more methods with the same name within the same class provided that the order and type of parameters are different.

Example:

class Dummy {public void display() {} public void display(int x) {}public void display(int x,char ch) {}

}

Page 28: OOP in Java

Overloading Constructors

public class MyPoint {private int x;private int y;

public MyPoint(int x,int y) {this.x = x;this.y = y;

}public MyPoint() {

this(0,0);}

}

Page 29: OOP in Java

Package Statement

• allows for the grouping of classes• should be placed before any class or any import

statement.• corresponds to a directory structure

package mypackage;

public class MyPoint {}

Page 30: OOP in Java

import Statement

• in order to specify the specific package/directory where the classes to be used in the class are located, use the import statement

• should be placed after the package statement but before any class definition

import mypackage;

public class UsePoint {}

Page 31: OOP in Java

Inheritance - is used to : a. factor common attributes and methods in superclass b. extend existing classes to support new abstractions c. represent problem domain abstractions more accurately.

- Defining an inheritance hierarchy has several useful advantages : a. organizes classes b. eliminates redundancy of definitions c. simplifies specialization d. facilitates code reuse

Page 32: OOP in Java

Inheritance (continued) Inheritance Example :

BankAccount

SavingsAccountCheckingAccount

Generalization

Specialization

- Superclass contains attributes and methods applicable to all subclass instance.

Page 33: OOP in Java

Inheritance

Student

Person

Employee

DoctorTeacher

Page 34: OOP in Java

Method Overriding

• The method name that is used in the parent class can also be used in the child class.

• If the method has different number and type of parameters, it is still overloading, but if the method has exactly the same signature, it is called overriding.

• Overriding provides a way to redefine a method in the parent class.

Page 35: OOP in Java

The Object Class

- the root of all classes in Java

- any class that is created automatically “extends” the Object class.

- the Object class includes certain useful methods which can be

overridden by any class. Some of the useful methods are:

public boolean equals(Object obj);

- returns true if obj is equal to this object

public String toString();

- returns a string representation of the object


Recommended