object- oriented programming (cs243) dr walid m. aly lec4 1 dr walid m. aly 1 lecture 4 object-...

25
Object- Oriented Programming (CS243) Dr Walid M. Aly lec 4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page: http://groups.yahoo.com/group/JAVA-CS243/ Defining your own classes

Upload: lambert-jacobs

Post on 29-Jan-2016

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:

Object- Oriented Programming (CS243)

Dr Walid M. Alylec41 1

Dr Walid M. Aly

Lecture 4

Object- Oriented Programming (CS243)

Group home page:

http://groups.yahoo.com/group/JAVA-CS243/

Defining your own classes

Page 2: Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:

Object- Oriented Programming (CS243)

Dr Walid M. Alylec42

Why Programmer-Defined Classes?

• Using just standard API classes will not meet all of our needs. We need to be able to define our own classes customized for our applications.

• Learning how to define our own classes is the first step toward mastering the skills necessary in building large programs.

• Classes we define ourselves are called programmer-defined classes.

Page 3: Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:

Object- Oriented Programming (CS243)

Dr Walid M. Alylec43 3

Banking SystemClass EmployeeClass Manager

Class BankAccount

Class CreditCard

Student Registration SystemClass StudentClass Lecturer

Class Course

Class ClassRoom

Voting SystemClass VotingClass Citizen

Class vote

Class Candidate

Library SystemClass BookClass LibraryMember

Class Employee

Example : classes in different systems

Page 4: Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:

Object- Oriented Programming (CS243)

Dr Walid M. Alylec44

4

class className{

}

Variables describing state

Methods describing behavior

class Student{String name;double GPA;Int regidterationNumber;…………………..void registerUnit(){…………………}void payFees(){……}

}

Student object 1

name =Ahmed Alyregistration number=245245GPA=3.2

register a unit

Student object 2

name =Mohamed Fathiregistration number=34345GPA=2.2

payFees

Page 5: Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:

Object- Oriented Programming (CS243)

Dr Walid M. Alylec45 5

• Real-world objects share two characteristics: they all have state and behavior.

• in your program, you will have software objects which are objects that you want to manipulate.

• The state of an object is represented by variables with their current values.• The behavior of an object is defined by a set of methods• The terms object and instance are interchangeable.• Objects of the same type are defined using a common class. • The class defines the type of variables the object can have and the type of

method the object can execute.

Objects & classes

Radio might have states (on, off, current volume, current station) and behavior (turn on, turn off, increase volume, decrease volume, seek, scan, and tune).

Radio

Page 6: Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:

Object- Oriented Programming (CS243)

Dr Walid M. Alylec46 6

Example :Class Radiopublic class Radio{int volume;String station;boolean powerStatus;

public void increaseVolume(){volume++;}public void decreaseVolume(){volume--;}public void changeStation(String newStation){station=newStation;}public void turnOn(){ volume=3;

powerStatus=true;}public void turnOff(){ volume=0;

powerStatus=false;}}

volume =4station=“Negoom FM”Powerstatus=true

Radio object1

volume =7station=“Quran”Powerstatus=true

Radio object2

volume =0station=“FM”Powerstatus=false

Radio object3

volume =3station=“FM”Powerstatus=true

Turn On

Page 7: Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:

Object- Oriented Programming (CS243)

Dr Walid M. Alylec47

class {

}

Template for Class DefinitionImport StatementsImport Statements

Class CommentClass Comment

Class NameClass Name

Data MembersData Members

Methods(incl. Constructor)

Methods(incl. Constructor)

A class will have variables , constructors and methods. All these are known as class members

Page 8: Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:

Object- Oriented Programming (CS243)

Dr Walid M. Alylec48

The Definition of the Bicycle Classclass Bicycle {

// Data Member private String ownerName;

//Constructor: Initialzes the data memberpublic Bicycle( ) {

ownerName = "Unknown";}

//Returns the name of this bicycle's owner public String getOwnerName( ) { return ownerName; }

//Assigns the name of this bicycle's owner public void setOwnerName(String name) { ownerName = name; } }

Page 9: Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:

Object- Oriented Programming (CS243)

Dr Walid M. Alylec49 Chapter 4 - 9

Data Member Declaration

<modifiers> <data type> <name> ;

private String ownerName ;

ModifiersModifiers Data TypeData Type NameName

Note: There’s only one modifier in this example.

Note: There’s only one modifier in this example.

Class members can be declared with access modifier as public or protected or private. the default access modifier is “ package”

Page 10: Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:

Object- Oriented Programming (CS243)

Dr Walid M. Alylec410 Chapter 4 - 10

Method Declaration<modifier> <return type> <method name> ( <parameters> ){

<statements>

}

public void setOwnerName ( String name ) {

ownerName = name;

}

StatementsStatements

ModifierModifier Return TypeReturn Type Method NameMethod Name ParameterParameter

Class members can be declared with access modifier as public or protected or private. the default access modifier is “ package”

Page 11: Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:

Object- Oriented Programming (CS243)

Dr Walid M. Alylec411

Constructor• A constructor is a special method that is executed when a new instance of the

class is created.

public <class name> ( <parameters> ){ <statements> }

public Bicycle ( ) {

ownerName = "Unassigned";

}

StatementsStatements

ModifierModifier Class NameClass Name ParameterParameter

Page 12: Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:

Object- Oriented Programming (CS243)

Dr Walid M. Alylec412 12

Constructors…..Constructor must have the same name as the class name.Constructors do not have a return type—not even void, can not be static.default blank constructor, is provided automatically only if no constructors are explicitly declared in the class.A constructor is generally used to do initial setup for an object

class Circle { double radius=0 ;public Circle() { }public Circle (double r){radius=r;}public double findArea(){ // }}

multiple constructors with the same name but different signatures can exist.(overloading)

Page 13: Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:

Object- Oriented Programming (CS243)

Dr Walid M. Alylec413 13

class Circle { double radius=0 ; public Circle() { } public Circle (double r) { radius=r; } public double findArea() { return radius * radius * 3.14; }}

class Test{public static void main (String [] arg){Circle c1;c1=new Circle();Circle c2= new Circle();Circle c3= new Circle(5.1);}}

How to create an object from class?

To construct an object from a class, invoke a constructor of the class using the new operator, as follows: new ClassName(arguments);constructor can contain any type of code that a normal method could contain. When constructor is invoked an object is created and also code in constructor is executed.

radius=0 radius=0 radius=5.1c1 c2 c3

c1,c2,c3 are reference data types

Page 14: Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:

Object- Oriented Programming (CS243)

Dr Walid M. Alylec414

Revisiting the Bicycle Classclass Bicycle {

// Data Member private String ownerName;

//Constructor: Initialzes the data memberpublic Bicycle( ) {

ownerName = "Unknown";}

//Returns the name of this bicycle's owner public String getOwnerName( ) { return ownerName; }

//Assigns the name of this bicycle's owner public void setOwnerName(String name) { ownerName = name; } }

Page 15: Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:

Object- Oriented Programming (CS243)

Dr Walid M. Alylec415

Using the Bicycle Classclass BicycleRegistration {

public static void main(String[] args) {

Bicycle bike1, bike2;

String owner1, owner2;

bike1 = new Bicycle( ); //Create and assign values to bike1

bike1.setOwnerName("Adam Smith");

bike2 = new Bicycle( ); //Create and assign values to bike2

bike2.setOwnerName("Ben Jones");

owner1 = bike1.getOwnerName( ); //Output the information

owner2 = bike2.getOwnerName( );

System.out.println(owner1 + " owns a bicycle.");

System.out.println(owner2 + " also owns a bicycle.");

}

}

Page 16: Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:

Object- Oriented Programming (CS243)

Dr Walid M. Alylec416 Chapter 4 - 16

Multiple Instances• Once the Bicycle class is defined, we can create multiple instances.

Bicycle bike1, bike2;

bike1 bike2

: Bicycle

ownerName

: Bicycle

ownerName

“Adam Smith” “Ben Jones”

bike1 = new Bicycle( );

bike1.setOwnerName("Adam Smith");

bike2 = new Bicycle( );

bike2.setOwnerName("Ben Jones");

Sample Code

Page 17: Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:

Object- Oriented Programming (CS243)

Dr Walid M. Alylec417 17

Example :Adding constructors to class Radiopublic class Radio{int volume;String station;boolean powerStatus;public Radio(){volume=3;}public Radio(int startVolume){volume= startVolume;}public void increaseVolume(){volume++;}public void decreaseVolume(){volume--;}public void changeStation(String newStation){station=newStation;}

public void turnOn(){powerStatus=true;

}public void turnOff(){ volume=0;

powerStatus=false;}}

class Test{public static void main (String [] args){Radio radio1=new Radio();radio1.turnOn();radio1.increaseVolume();Radio radio2=new Radio(5);}}

Page 18: Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:

Object- Oriented Programming (CS243)

Dr Walid M. Alylec418 18

public class Box{double width;double height;double depth;double volume;public Box(double w,double h,double d){width=w;height=h;depth=d;}}

public class Test {public static void main(String args[]) {Box mybox1 = new Box( );}

1-compile error2-Runtime error3-Compile and run without error

What will be the output ?

1-compile errorDefault constructor should be written

Page 19: Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:

Object- Oriented Programming (CS243)

Dr Walid M. Alylec419

Example :The Account Classclass Account {

private String ownerName; private double balance; public Account( ) {

ownerName = "Unassigned"; balance = 0.0;

}

public void add(double amt) { balance = balance + amt; } public void deduct(double amt) { balance = balance - amt; } public double getCurrentBalance( ) { return balance; } public String getOwnerName( ) { return ownerName; }

public void setInitialBalance (double bal) { balance = bal; } public void setOwnerName (String name) { ownerName = name; } }

Page 1 Page 2

Page 20: Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:

Object- Oriented Programming (CS243)

Dr Walid M. Alylec420

Arguments and Parameters

• An argument is a value we pass to a method

class Account {

. . .

public void add(double amt) {

balance = balance + amt; }

. . . }

class Sample {

public static void main(String[] arg) { Account acct = new Account(); . . . acct.add(400); . . . }

. . . }

argument

parameter

• A parameter is a placeholder in the called method to hold the value of the passed argument.

Page 21: Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:

Object- Oriented Programming (CS243)

Dr Walid M. Alylec421 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 4 - 21

Matching Arguments and Parameters• The number or

arguments and the parameters must be the same

class Demo {

public void compute(int i, int j, double x) { . . . } }

Demo demo = new Demo( );

int i = 5; int k = 14;

demo.compute(i, k, 20);3 arguments

3 parameters

• The matched pair must be assignment-compatible (e.g. you cannot pass a double argument to a int parameter)

• Arguments and parameters are paired left to right

Passing Side

Receiving Side

Page 22: Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:

Object- Oriented Programming (CS243)

Dr Walid M. Alylec422 22

Calling a constructor from another constructor

this is used to call a constructor from another constructor.call to this must be first statement in constructor otherwise compile error

class Box{double width;double height;double depth;Box(double w, double h, double d){width = w;height = h;depth = d;}Box(){width = 1;height = 1;depth = 1;}Box(double y){this(y,y,y);}}

Page 23: Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:

Object- Oriented Programming (CS243)

Dr Walid M. Alylec423

Information Hiding and Visibility Modifiers

• The modifiers public and private designate the accessibility of data members and methods.

• If a class component (data member or method) is declared private, client classes cannot access it.

• If a class component is declared public, client classes can access it.

• Internal details of a class are declared private and hidden from the clients. This is information hiding.

Page 24: Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:

Object- Oriented Programming (CS243)

Dr Walid M. Alylec424 Chapter 4 - 24

Accessibility Example

class Service { public int memberOne; private int memberTwo;

public void doOne() {

} private void doTwo() {

}

}

Service obj = new Service();

obj.memberOne = 10;

obj.memberTwo = 20;

obj.doOne();

obj.doTwo();

Client Service

Page 25: Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:

Object- Oriented Programming (CS243)

Dr Walid M. Alylec425

Data Members Should Be private

• Data members are the implementation details of the class, so they should be invisible to the clients. Declare them private .

• Exception: Constants can (should) be declared public if they are meant to be used directly by the outside methods.