Object Oriented Programming Concepts using Java

Post on 18-Jul-2015

177 views 4 download

Tags:

Transcript of Object Oriented Programming Concepts using Java

Object Oriented Programming

Old Programming Technique: Structures

struct queue{int a[5];int head;int tail;

};

struct stack{int a[5];int top;

}

void main(){

struct queue Q;struct stack S;

print( Q.a[2] );print( S.a[2] );

add(S, 3);add(Q, 2);

}

void add(queue Z, int x){ <codes for

adding queueelements here>

}

void remove(queue Z, int x){ <codes for

removing queueelements here>

}

void add(stack Z, int x){ <codes for

adding stackelements here>

}

void remove(stack Z, int x){ <codes for

removing stackelements here>

}

?

New Programming Technique: Object-Oriented

void main(){

queue Q;stack S;

print( Q.a[2] );print( S.a[2] );

S.add(3);Q.add(2);

}

class queue{int a[5];int head;int tail;

void add(int x){ <codes here>}

void remove(int x){ <codes here>}

};

class stack{int a[5];int top;

void add(int x){ <codes here>}

void remove(int x){ <codes here>}

}

Chapter 3 - Object-Orientation

What is OO Programming

A type of programming in which programmers define not only the data type of a data structure, but also the types of operations (functions) that can be applied to the data structure.

In this way, the data structure becomes an object that includes both data and functions.

In addition, programmers can create relationships between one object and another.

For example, objects can inherit characteristics from other objects.

Stack

int top;push();pop();add();

Linked List

int content;initialize();

Queue

int end;enqueue();dequeue();

add();

inherits inherits

Object-orientation is a new technology based on objects and classes. It presently represents the best methodological framework for software designers to develop complex large scale systems.

One of the principal advantages of object-oriented programming techniques over procedural programming techniques is that they enable programmers to create modules that do not need to be changed when a new type of object is added.

A programmer can simply create a new object that inherits many of its features from existing objects. This makes object-oriented programs easier to modify.

Chapter 3 - Object-Orientation

What is OOP?

Stack

int top;push();pop();add();

Linked List

int x;initialize();

Queue

int end;enqueue();dequeue();

add();

inherits inherits

Old class is not modified

New classes can be created based on an old class.

Classes, Objects, and Packages

What is a Class?

In manufacturing, a blueprint is a description of a device from which many physical devices are constructed

In software, a class is a description of an object

A class describes the data that each object includes

A class describes the behaviour that each object exhibit

In Java, classes support three key features of OOP

encapsulation

inheritance

polymorphism

Chapter 3 - Object-Orientation

What is an Object?

An object is an instance of the class. Objects store data and provides method for accessing and modifying this data

Chapter 3 - Object-Orientation

data/properties/fields – are the attributes of the object

methods – are functions that manipulate the data

Class: Vehicle Blue Print

Object: Actual Auto

Object: Actual Bus

Object: Actual Jeep

Class Objects

Data

Behaviour

Properties

Methods

Just a description. The concrete working thing.

Chapter 3 - Object-Orientation

Declaring Java Classes

<modifier> class <classname> {

<attribute_declaration>

<method_declaration>}

where: <modifier> = public, private, protected

Example:public class Test{ public static int x,y,z; public static void main(String args[]){

System.out.println(“Hello”); }}

Chapter 3 - Object-Orientation

Chapter 3 - Object-OrientationChapter 3 - Object-Orientation

Declaring Attributes:

<modifier> <type> <name> [= default value]

where: modifier = public, private, protectedtype = int, float, double, long, short, byte, boolean, char

Example:

public int number = 30;

Chapter 3 - Object-OrientationChapter 3 - Object-Orientation

Declaring Methods:

<modifier> <returnType> <name>(parameters){

<statements>

}

where: modifier = public, private, protected

returnType = int, float, double, long, short, byte,

boolean, char

Example:

public static void main(String args[]){

statements here.....

}

Chapter 3 - Object-Orientation

Constructors •Constructors are useful for initializing objects before they are being used.•Parameters can be passed to the constructor in the same way as for a method.

•Constructors are special purpose methods; •a constructor is only used during instantiation to initialize the object and is never used again.

•A constructor must follow the following rules:

1. A constructor's name must be the name of the class.2. A constructor does not have any return type.

Chapter 3 - Object-Orientation

Constructors

Syntax:<modifier> <classname>(parameters){

<statements>

}

Example:

String school = new String(“JAVA University”);

String school = new String( );

Instantiating a Class

• Creating Objects:

<class name> <object name> = new <constructor call>;

String school = new String(“JAVA University”);

Chapter 3 - Object-Orientation

Accessing Object Members:

The “dot” notation <object>.<member>

This is used to access object members including attributes and methods

Examples:

thing1.setX(47);

thing1.x=47; // valid only if x is public

Continue Here

Chapter 3 - Object-Orientation

Packages

Class:Faculty

Class:Student

Package: DMPCS

Object:BSCS

Object:BSAM

Object:BSCS

Object:BSAM

JAVA PACKAGES The standard Java classes are organized into packages.

Packages are a way of grouping related classes to avoid potential naming conflicts.

The standard Java packages are java.lang java.awt java.applet java.awt.image java.awt.peer java.io java.net java.util

Chapter 3 - Object-Orientation

Package

Class1 Class 2 Class 3 Class n

Attributes

Methods

Attributes

Methods

Attributes

Methods

Attributes

Methods

class1 class2

class3 class4

class1 class2

class3 class4

package1 package2

Wildcard usage:

import <packagename>.*;

Example:

import package1.*;

Specific usage:

<packagename>.<classname>;

Examples:

package1.class1;

package2.class1;

Chapter 3 - Object-Orientation

java.lang package--- contains the various classes that are essential to the definition of the Java language or that, by their nature, need to access the internals of Java in a way that most classes cannot do.

Java.lang classes: Boolean, Byte, Character, Character.Subset, Character.UnicodeBlock, Class, ClassLoader Compiler, Double, Float, InheritableThreadLocal Integer, Long, Math, Number, Object, Package, Process Runtime, RuntimePermission, SecurityManager, Short String, StringBuffer, System, Thread, ThreadGroup ThreadLocal, Throwable and Void

Chapter 3 - Object-OrientationJava.lang package

Objectclone,

finalize, getClass,

notify, notifyAll,

wait, wait, wait

Boolean•booleanValue()•equals(Object obj)•getBoolean(String name)•hashCode()•toString()•toString(boolean b)•valueOf(boolean b)•valueOf(String s)

Number

Byte

String

Double Float

Chapter 3 - Object-OrientationJava.lang package

Class String

charAt(int index) int compareTo(Object o) int compareTo(String anotherString) int compareToIgnoreCase(String str) String concat(String str) static String copyValueOf(char[] data) static String copyValueOf(char[] data, int offset, int count) boolean endsWith(String suffix) boolean equals(Object anObject) booleanequalsIgnoreCase(String anotherString) byte[] getBytes() void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin)

Chapter 3 - Object-Orientation

Methods of Class String of the java.lang package

• public int length()

• public char charAt(int index)

• public String substring(int beginIndex, int endIndex)

To create an instance of String:

String proglang = “JAVA”;

To use method length:

x = proglang.length();

ENCAPSULATION

Chapter 3 - Object-Orientation

Encapsulation•Is the process of compartmentalizing the elements of an abstraction that constitute its structure and behavior

•It is achieved through information hiding, which is the process of hiding all the secrets of an object that do not contribute to its essential characteristics; typically the structure of an object is hidden, as well as the implementation of the methods.

•Forces the user to use an interface to access data

•Makes the code more maintainable

Chapter 3 - Object-Orientation

Information Hiding

- is the process of hiding details of an object/function.

-is designing a method so that it can be used without any need to understand the fine detail of the code.

- An object is composed of a public interface and a private section that can be a combination of internal data and methods. The internal data and methods are the sections of the object hidden.

-The primary benefit is that these sections can change without affecting other parts of the program

ABSTRACTION & ENCAPSULATION

BENEFITS OF ENCAPSULATION

Chapter 3 - Object-Orientation

ABSTRACTION & ENCAPSULATION

• Modularity. This means that an object can be maintained independently of other objects. Because the source code for the internal sections of an object is maintained separately from the interface, you are free to make modifications with confidence that your object won't cause problems to other areas. This makes it easier to distribute objects throughout a system.

BENEFITS OF ENCAPSULATION

Chapter 3 - Object-Orientation

Method and Member VisibilityEncapsulation hides a class internal details for the outside world; if we were to provide getter and setter methods but leave Account class member declaration as public

This is because public allows virtually any one to access the member. By using private, we have effectively closed all members to the outside world.

By doing this, we are enforcing encapsulation.

ABSTRACTION & ENCAPSULATION

Chapter 3 - Object-Orientation

Java provides the following visibility keywords which can be used on members or methods:

public A method or member that is declared public is accessible from any class.

protected A method or member that is declared protected is accessible only to its subclass and the class itself.

private A private method or member of a class is only accessible from within that class. Other classes including subclass cannot access this member or method.

Keyword Self Subclass Others

Public yes yes yes

Protected yes yes no

Private yes no no

ABSTRACTION & ENCAPSULATION

Declaring Java Classes:

public class Thing{

public int x;

Thing (); //we dnt nd }

public class TestThing{

public static void main(String args[]{

Thing thing1 = new Thing();

thing1.x = 47;

System.out.println(“Thing1 = “+ thing1.x);

}

}

Instantiating a Class:

Declaring Java Classes:

public class Thing{

private int x; public int getter(){ return x; } public void setter(int newx){ x = newx; }}

Public class TestThing{

public static void main(String args[]{

Thing thing1 = new Thing();

thing1.x = 47; // invalid

thing1.setter(47);

System.out.println(“Thing1 = “

+ thing1.getter();

}

}

Instantiating a Class:

ABSTRACTION

Chapter 3 - Object-Orientation

Abstraction denotes the essential characteristics of an object that distinguish it from all other kinds of objects focuses on the outside view of the object

Kinds of AbstractionEntity abstraction – an object that represents a useful model of a problem-domain or solution domain.

Action Abstraction – an object that provides a generalized set of operations, all of which perform the same kind of functions.

More examples

ex1

Declaring Java Classes:

public class Thing{

public int x;

}

public class TestThing{

public static void main(String args[]{

Thing thing1 = new Thing();

thing1.x = 47;

System.out.println(“Thing1 = “+ thing1.x);

}

}

Declaring Java Classes:

public class Thing{

private int x; public int getX(){ return x; } public void setX(int newx){ x = newx; }}

Public class TestThing{

public static void main(String args[]{

Thing thing1 = new Thing();

thing1.setX(47);

System.out.println(“Thing1 = “

+ thing1.getX();

}

}

Instantiating a Class:

Chapter 3 - Object-Orientation

Accessing Object Members:

The “dot” notation <object>.<member>

This is used to access object members including attributes and methods

Examples:

thing1.setX(47)

thing1.x=47; // valid only if x is public

ex2

Chapter 3 - Object-Orientation

public class Account3 {

private String name;

private int acctNo;

private float balance;

private boolean overdraft;

public Account3(String n, int no) {

name = n;

acctNo = no;

balance = 4000F;

overdraft = false;

}

public void deposit(float amt) { ---- }

public void withdrawal(float amt) { ---- }

public void transfer(Account from, float amt) { ---- }

Information Hiding

ABSTRACTION & ENCAPSULATION

Chapter 3 - Object-Orientation

public void setName(String n){ name = n; } public String getName(){ return name; } public float getBalance(){ return balance; } public void setAccountNo(int ac){ acctNo = ac; } public int getAccountNo(){ return acctNo; }

public void setOverdraft(boolean x)

{ overdraft = x; } public boolean getOverdraft(){ return overdraft; }}

ABSTRACTION & ENCAPSULATION

Chapter 3 - Object-Orientation

public class TestAccount3{

public static void main(String args[]){

Account3 myAccount = new Account3(“Bin", 007);

// System.out.println("This account belongs to: " + myAccount.name);

System.out.println("Account of " + myAccount.getName());

// System.out.println("Current Balance is = "+ myAccount.balance);

System.out.println("Current Balance is ="+myAccount.getBalance());

System.out.println("After withdrawing P2000......");

myAccount.withdrawal(2000);

System.out.println("After withdrawing P100 ......");

myAccount.withdrawal(100);

// System.out.println("The new balance is = " + myAccount.balance);

System.out.println("The new balance is = " + myAccount.getBalance()); }}

ABSTRACTION & ENCAPSULATION

Chapter 3 - Object-OrientationABSTRACTION & ENCAPSULATION

Open Account3.java and TestAccount3.java

Since TestAccount3.java has an object of type Account, compile TestAccount3.java to compile the two files

EXERCISE: Exploring Classes and Objects

More Classes and Objects Examples

Ex 0

Sample Class

public class Account{ public String name; public int acctNo; public float balance; public boolean overdraft;

public void deposit(float amt) { if (amt >= 0) balance += amt; } public void withdrawal(float amt) { if ((amt <= balance) && (amt >= 0)) balance = balance - amt; } public void transfer(Account from, float amt) { if (amt < 0) return; from.withdrawal(amt); deposit(amt); }}

Chapter 3 - Object-Orientation

Attributes/Fields

Methods

Chapter 3 - Object-Orientation

To instantiate an Account object we use new.

public class TestAccount{ public static void main(String args[]){ Account myAccount = new Account(); myAccount.name = “Bin"; myAccount.acctNo = 007; myAccount.balance = 4000; myAccount.overdraft = false;

System.out.println("Current Balance is = “ + myAccount.balance); System.out.println("After withdrawing P2000......"); myAccount.withdrawal(2000); System.out.println("After withdrawing P100 ......"); myAccount.withdrawal(100); System.out.println("The new balance is = “ + myAccount.balance); }}

ex1

Chapter 3 - Object-Orientation

class Student {String fname;String lname;int age;String course;public Student(){ } public Student(String f, String l, String c, int a){

fname = f;lname = l;course = c;age = a; }

public Student(String f, String l){fname = f;lname = l;course = "BSCS";age = 20;

}

}

class TestStudent1 {

public static void main(String args[]){

Student s1 = new Student();

}

}

class Student {String fname; String lname; int age; String course;public Student(){ }

}

class TestStudent2 {

public static void main(String args[]){

Student s2 =new Student("Vic", "Calag", "BSCS", 37);

System.out.println("First Name = "+ s2.fname);

System.out.println("Last Name = "+ s2.lname);

System.out.println("Course = "+ s2.course);

System.out.println("Age = "+ s2.age);

}

}

class Student {String fname; String lname; int age; String course;public Student(String f, String l, String c, int a){

fname = f;lname = l;course = c;age = a; }

}

class TestStudent3 {

public static void main(String args[]){

Student s3 = new Student("Fernando", "Poe");

System.out.println("First Name = "+ s3.fname);

System.out.println("Last Name = "+ s3.lname);

System.out.println("Course = "+ s3.course);

System.out.println("Age = "+ s3.age);

} }

class Student {String fname; String lname; int age; String course;public Student(String f, String l){

fname = f;lname = l;course = "BSCS";age = 20;

}}

ex2

Chapter 3 - Object-Orientation

public class Account2 { public String name; public int acctNo; public float balance; public boolean overdraft; public Account2(String n, int no) { name = n;

acctNo = no; balance = 4000F; overdraft = false; } public void deposit(float amt) public void withdrawal(float amt) public void transfer(Account from, float amt)

}

Chapter 3 - Object-Orientation

public class TestAccount2 {

public static void main(String args[]){

Account2 myAccount = new Account2("Bin", 007);

// myAccount.name = "Bin"; myAccount.acctNo = 007;

// myAccount.balance = 4000; myAccount.overdraft = false;

System.out.println("This account belongs to: "+ myAccount.name);

System.out.println("Current Balance is = "+ myAccount.balance);

System.out.println("After withdrawing P2000......");

myAccount.withdrawal(2000);

System.out.println("After withdrawing P100 ......");

myAccount.withdrawal(100);

System.out.println("The new balance is = " + myAccount.balance);

}

}

Chapter 3 - Object-Orientation

public class Account3 { public String name; public int acctNo; public float balance; public boolean overdraft; public Account3(String n, int no, float bal, boolean od) { name = n;

acctNo = no; balance = bal; overdraft = od; } public void deposit(float amt) public void withdrawal(float amt) public void transfer(Account from, float amt)

}

Chapter 3 - Object-Orientation

public class TestAccount3 {

public static void main(String args[]){

Account3 myAccount = new Account3("Bin", 007, 5000,true);

// myAccount.name = "Bin"; myAccount.acctNo = 007;

// myAccount.balance = 5000; myAccount.overdraft = true;

System.out.println("This account belongs to: "+ myAccount.name);

System.out.println("Current Balance is = "+ myAccount.balance);

System.out.println("After withdrawing P2000......");

myAccount.withdrawal(2000);

System.out.println("After withdrawing P100 ......");

myAccount.withdrawal(100);

System.out.println("The new balance is = " + myAccount.balance);

}

}