Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming...

52
BBS514 Structured Programming (with Java) 1 Objects and Classes

Transcript of Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming...

Page 1: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

BBS514 Structured Programming (with Java) 1

Objects and Classes

Page 2: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• Object-oriented programming (OOP) involves programming using objects.

• An object represents an entity in the real world that can be distinctly identified.

– For example, a student, a desk, a circle, a button, and even a loan can all be viewed as

objects.

• Objects have two general capabilities:

– Objects can store data. The pieces of data stored in an object are known as fields.

– Objects can perform operations. The operations that an object can perform are

known as methods.

OO Programming Concepts

BBS514 Structured Programming (with Java) 2

Page 3: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• A class is code that describes a particular type of object.

• A class specifies

– the data that an object can hold (the object's fields), and

– the actions that an object can perform (the object's methods).

• A class is a blueprint of its objects.

• We can create many objects from a single class.

• Creating an object from a class is called instantiation, and an object is an instance of

a particular class.

• Additionally, a class provides a special type of methods, known as constructors,

which are invoked to construct objects from the class.

Classes

BBS514 Structured Programming (with Java) 3

Page 4: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• Normally, an object is created from a class using the new operator.

new ClassName( parameters )

Objects

BBS514 Structured Programming (with Java) 4

keyboard

variable

Scanner

object

Scanner keyboard = new Scanner(System.in);

This expression creates a Scanner object in memory.

The object's memory address is assigned to the keyboard variable.

Example:

Page 5: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• When a new operator is executed the constructor method of the class is activated to

create an instance of that class, and that instance is initialized by the constructor

method.

• The constructor method has same name as the class and does not have any return type. (not even void)

• There are some short cuts to create objects of certain pre-defined classes in Java.

– String class: “abc” creates an object of String class

– array classes: int[] x = {5,2,1}; creates an int array object with size 3 and

initializes that array.

Objects

BBS514 Structured Programming (with Java) 5

Page 6: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• A class can be defined as follows

[ClassAccesibilityModifiers] [OtherClassModifiers] class ClassName

[extends SuperClass] [implements Interface1,...,Interfacen] {

ClassMemberDeclarations

}

• Note: Here, [] means that those parts are optional.

• OtherClassModifiers, SuperClass and Interface concepts are inheritance related

subjects, we will not cover them here.

Class Declaration

BBS514 Structured Programming (with Java) 6

Page 7: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• There are three class accessibility modifiers:

public -- A public class is accessible by any class.

private -- A private class is accessible only the classes within the same file.

• When no modifier is present, (by default) the class is accessible by all the classes

within the same package.

– This accessibility modifier (no modifier) is known as package accessibility

modifier.

Class Accessibility Modifiers

BBS514 Structured Programming (with Java) 7

Page 8: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• Inside of a class, we may declare the following class members:

– Fields – data-variables declared in the class.

– Methods – methods declared in the class.

– Constructors – special methods to create objects of the class, and to initialize

fields.

• The order of the declarations is not important, but it is nice to use the following order.

class ClassName {

Fields

Constructors

Methods

}

Class Member Declarations

BBS514 Structured Programming (with Java) 8

Page 9: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

There are four accessibility modifiers for class members:

public -- A public member is accessible by any class.

private – A private member is accessible only the class itself.

protected – A protected member is accessible by the class itself, all its sub-classes,

and all the classes within the same package.

– When no modifier is present, (by default) the member is accessible by all the

classes within the same package. This accessibility modifier (no modifier) is

known as package accessibility modifier.

Accessibility Modifiers for Class Members

BBS514 Structured Programming (with Java) 9

Page 10: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• Fields are also known as attributes.

• Fields are the data-variables declared in that class.

• A data-variable can be:

– an instance variable (declared without using keyword static), or

– a class variable (declared using keyword static, it is also known as a static

variable).

• An instance variable lives in an object of that class, and each object of that class has

its own copy of that variable.

• A static variable is a class-variable and there is only one copy for it. All instances of

that class share that single copy.

• A field is declared with a final modifier, it is a constant and its value cannot be

changed after its declaration.

Fields

BBS514 Structured Programming (with Java) 10

Page 11: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• A field declaration can be in the following form:

[FieldModifiers] Type FieldName1 [ = Initializer1], ... ,

FieldNamen [ = Initializern] ;

Examples:

public int a;

int b=1, c=2;

private double x;

private static int x;

public static int y;

public final int CONST1 = 5;

private static final int CONST2 = 6;

Declarations of Fields

BBS514 Structured Programming (with Java) 11

Page 12: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• A method can be:

– an instance method (declared without using keyword static), or

– a class method (declared using keyword static, it is also known as a static method).

• An instance method is associated with an object.

• If an instance method accesses an instance variable, it accesses of the copy of that instance variable in the current object.

• It looks like that there are multiple copies of an instance methods (one for each instance of that class).

• A static method is a class-method and there is only one copy for it.

• All instances of that class share that single copy.

• A static method cannot access an instance variable or an instance method.

Methods

BBS514 Structured Programming (with Java) 12

Page 13: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• A method declaration can be in the following form:

MethodModifiers ReturnType MethodName( FormalParameterList )

{

Statements}

Examples:

public int m1(int x) { ... }

public void m2(double x) { ... }

private void m3(int x, double y) { ... }

int m4() { ... }

public static int m5() { ... }

private static int m6(int x) { ... }

Method Declaration

BBS514 Structured Programming (with Java) 13

Page 14: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• Instance fields and methods are fields and methods that are NOT declared with a special keyword, static.

• Objects created from a class each have their own copy of instance fields.

• Instance fields and instance methods require an object to be created in order to be

used.

Instance Fields and Methods

BBS514 Structured Programming (with Java) 14

Page 15: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• Classes can have special methods called constructors.

• A constructor is a method that is automatically called when an object is created.

• Constructors are used to perform operations at the time an object is created.

• Constructors typically initialize instance fields and perform other object initialization

tasks.

• Constructors have a few special properties that set them apart from normal methods.

– Constructors have the same name as the class.

– Constructors have no return type (not even void).

– Constructors may not return any values.

– Constructors are typically public.

Constructors

BBS514 Structured Programming (with Java) 15

Page 16: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

class C {

// fields

private int x;

private double y;

// constructors

public C() { x=1; y=2.2; }

// methods

public void m1 (int val) { x=val; }

public void m2 (double val) { y=val; }

}

• The constructor method must have the same name as the class, and it does not have

any return type (not even void).

• Variables x and y are instance-variables, and they can be seen only by the methods of

this class.

Creating Objects

BBS514 Structured Programming (with Java) 16

Page 17: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• In some other class, we may create the objects of the class C.

– If we want, we can also create the objects of C in C too.

public class C2 {

.... main (...) {

C obj1, obj2;

obj1 = new C();

obj2 = new C();

}

.

.

}

Creating Objects (cont.)

BBS514 Structured Programming (with Java) 17

x

x

y

y

obj1

obj2

1

2.2

1

2.2

Page 18: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• Once an object of a class is created, its instance methods can be invoked using the

dot operator.

• Of course, the method which will be invoked must be accessible from that class.

• To invoke a method:

object.methodname( actual-parameters )

Example: (in the main method of C2)

obj1.m1(4);

obj2.m1(3);

obj1.m2(3.3);

Dot Operator

BBS514 Structured Programming (with Java) 18

Page 19: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• Using dot operator, we may also access fields.

• To access a field: object.field

Example: (in a method of C2)

obj1.x = 4; it will not work, because x was private

if C is declared as follows, the above assignment will be okay.

class C {

public int x;

.

}

Dot Operator (cont.)

BBS514 Structured Programming (with Java) 19

Page 20: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• A Rectangle object will have the following fields:

– length. The length field will hold the rectangle’s length.

– width. The width field will hold the rectangle’s width.

• The Rectangle class will also have the following methods:

– setLength. The setLength method will store a value in an object’s length field.

– setWidth. The setWidth method will store a value in an object’s width field.

– getLength. The getLength method will return the value in an object’s length field.

– getWidth. The getWidth method will return the value in an object’s width field.

– getArea. The getArea method will return the area of the rectangle, which is the result

of the object’s length multiplied by its width.

Rectangle - Example

BBS514 Structured Programming (with Java) 20

Page 21: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

public class Rectangle {

// Data Fields

private double length;

private double width;

// Constructor

public Rectangle(double len, double w) {

length = len;

width = w;

}

Rectangle - Example

BBS514 Structured Programming (with Java) 21

Page 22: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

// setLength method stores a value in thelength field.

public void setLength(double len) {

length = len;

}

// setWidth method stores a value in the width field.

public void setWidth(double w) {

width = w;

}

// getLength method returns a Rectangle object's length.

public double getLength() {

return length;

}

// getWidth method returns a Rectangle object's width.

public double getWidth() {

return width;

}

// getArea method returns a Rectangle object's area.

public double getArea() {

return length * width;

}

}

Rectangle - Example

BBS514 Structured Programming (with Java) 22

Page 23: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

public class RectangleDemo {

public static void main(String[] args) {

// create a Rectangle object

Rectangle box1 = new Rectangle(5.0, 10.0);

// Display the length.

System.out.println("The box's length is " + box1.getLength());

// Display the width.

System.out.println("The box's width is " + box1.getWidth());

// Display the area.

System.out.println("The box's area is " + box1.getArea());

// Change its length

box1.setLength(20.0);

// Display the area again.

System.out.println("The box's area is " + box1.getArea());

// create another Rectangle object

Rectangle box2 = new Rectangle(30.0, 40.0);

// Display the area of box2.

System.out.println("The box's area is " + box2.getArea());

}

}

Rectangle - Example

BBS514 Structured Programming (with Java) 23

Page 24: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

public class RectangleDemo {

public static void main(String[] args) {

// create a Rectangle object

Rectangle box1 = new Rectangle(5.0, 10.0);

// Display the length.

System.out.println("The box's length is " + box1.getLength());

// Display the width.

System.out.println("The box's width is " + box1.getWidth());

// Display the area.

System.out.println("The box's area is " + box1.getArea());

// Change its length

box1.setLength(20.0);

// Display the area again.

System.out.println("The box's area is " + box1.getArea());

// create another Rectangle object

Rectangle box2 = new Rectangle(30.0, 40.0);

// Display the area of box2.

System.out.println("The box's area is " + box2.getArea());

}

}

Rectangle - Example

BBS514 Structured Programming (with Java) 24

The box's length is 5.0

The box's width is 10.0

The box's area is 50.0

The box's area is 200.0

The box's area is 1200.0

Page 25: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• Because of the concept of data hiding, fields in a class are private.

• The methods that retrieve the data of fields are called accessors.

• The methods that modify the data of fields are called mutators.

• Each field that programmer wishes to be viewed by other classes needs an accessor.

• Each field that programmer wishes to be modified by other classes needs a mutator.

• For the Rectangle example, the accessors and mutators are:– setLength : Sets the value of the length field.

public void setLength(double len) …

– setWidth : Sets the value of the width field.

public void setLength(double w) …

– getLength : Returns the value of the length field.

public double getLength() …

– getWidth : Returns the value of the width field.

public double getWidth() …

• Other names for these methods are getters and setters.

Accessor and Mutator Methods

BBS514 Structured Programming (with Java) 25

Page 26: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• An object hides its internal, private fields from code that is outside the class that the

object is an instance of.

• Only the class's methods may directly access and make changes to the object’s internal

data.

• Code outside the class must use the class's public methods to operate on an object's

private fields.

• Data hiding is important because classes are typically used as components in large

software systems, involving a team of programmers.

• Data hiding helps enforce the integrity of an object's internal data.

Data Hiding

BBS514 Structured Programming (with Java) 26

Page 27: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• When an object is created, its constructor is always called.

• If you do not write a constructor, Java provides one when the class is compiled. The

constructor that Java provides is known as the default constructor.

– It sets all of the object’s numeric fields to 0.

– It sets all of the object’s boolean fields to false.

– It sets all of the object’s reference variables to the special value null.

• The default constructor is a constructor with no parameters, used to initialize an

object in a default configuration.

• The only time that Java provides a default constructor is when you do not write any

constructor for a class.

• A default constructor is not provided by Java if a constructor is already written.

Default Constructor

BBS514 Structured Programming (with Java) 27

Page 28: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• Variables and methods that are declared using keyword static, they are known as a

static (class) variables and methods).

• For static fields and methods, we can use the dot operator to access static fields and

methods as follows (normally from other classes):

ClassName.FieldName

ClassName.MethodName ( ActualParameters )

• To access static members, we do not need to create an object of that class.

• We may also access static members using objects as follows (although we do NOT

prefer this way to access static member).

Object.FieldName

Object.MethodName (ActualParameters )

• All the objects will access the single copy of a static member.

Static Fields and Methods

BBS514 Structured Programming (with Java) 28

Page 29: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

public class C1 {

public int x;

public static int y;

public C1() { x=1; y=5;}

public void setX(int val) { x=val; }

public static void printY() { System.out.println(“y: “ + y); }

}

// in a method of some other class

C1 o1,o2; o1.x = 2;

C1.y = 10; o2.x = 3;

C1.x = 10; ILLEGAL o1.y = 4;

C1.printY(); o2.y = 5;

C1.setX(10); ILLEGAL C1.y = 6;

o1 = new C1(); o1.setX(7);

o2 = new C1(); o2.setX(8);

o1.printY();

o2.printY();

Static Fields and Methods

BBS514 Structured Programming (with Java) 29

Page 30: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

public class C {

private static int count = 0;

private int objIndex;

public C() { count=count+1; objIndex=count; }

public static int numOfObjs() { return count; }

public int objID() { return objIndex; }

}

// in a method of some other class

C o1,o2,o3;

o1 = new C();

o2 = new C();

o3 = new C();

System.out.println(o1.objID());

System.out.println(o2.objID());

System.out.println(o3.objID());

System.out.println(C.numOfObjs());

Another Example with Static Fields

BBS514 Structured Programming (with Java) 30

Page 31: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• The act of assignment takes a copy of a value and stores in a variable.

int x,y; x 5 x 5

x=5; y=6; y=x; y 6 y 5

before assignment after assignment

public C {

public int x,y;

public C() {x=1;y=2;}

}

// in a method of another class

C c1,c2;

c1=new C();

c2=c1;

// c1 and c2 will point to the same object

Reference Assignment

BBS514 Structured Programming (with Java) 31

1

2

x

yc1

c2

Page 32: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• Two or more references may refer to the same object.

– They are called aliases of each other.

• Aliases can be useful, but they should be managed carefully.

• Affecting the object through one reference affects its all aliases, because they refer to

the same object.

• Example:

c1.x = 5;

• c2 is affected too.

Reference Assignment - Aliases

BBS514 Structured Programming (with Java) 32

Page 33: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• In a Java program, we can access three kinds of variables in the methods.

– instance variables -- declared in the class (without using static keyword)

– class variables (static variables) - declared in the class (with using static

keyword)

– local variables – declared in a method or as its formal parameters.

• An instance method of a class can refer (just using their names) to all instance

variables, all static variables declared in the class, and all its local variables.

• A static method of a class CANNOT refer to any instance variable declared in that

class. It can only refer to static variables and its local variables.

Variables

BBS514 Structured Programming (with Java) 33

Page 34: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

public class C {

int x;

static int y;

public void printX() { System.out.println(“x: “+x); }

public static void printY() { System.out.println(“y: “+y); }

public void m1(int a, int b) {

int c=a+b;

x=a; y=b;

printX(); printY();

}

public static void m2(int a, int b) {

x=a; ILLEGAL

y=b;

printX(); ILLEGAL

printY();

}

}

Variables (cont.)

BBS514 Structured Programming (with Java) 34

Page 35: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• The keyword this can be used inside instance methods to refer to the receiving

object of the method.

• The receiving object is the object through which the method is invoked.

• The object reference this cannot occur inside static methods.

• Two common usage of this:

– to pass the receiving object as a parameter

– to access fields shadowed by local variables.

• Each instance method runs under an object, and this object can be accessible using this keyword.

Object Reference this

BBS514 Structured Programming (with Java) 35

Page 36: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

public class MyInt {

private int ival;

public MyInt(int val) { ival=val; }

public boolean isGreaterThan(MyInt o2) {

return (ival > o2.ival);

}

public boolean isLessThan(MyInt o2) {

return (o2.isGreaterThan(this));

}

}

in some other placeMyInt x1=new MyInt(5), x2=new MyInt(6);

x1.isGreaterThan(x2);

x1.isLessThan(x2);

Passing this as a Parameter

BBS514 Structured Programming (with Java) 36

Page 37: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• A field declared in a class can be shadowed (hidden) in a method by a parameter or a

local variable of the same name.

public class T {

int x; // an instance variable

void m1(int x) { ... } // x is shadowed by a parameter

void m2() { int x; ... } // x is shadowed by a local variable

• To access a shadowed instance variable, we may use this keyword.

public class T {

int x; // an instance variable

void changeX(int x) { this.x = x; }

}

Accessing Shadowed Fields

BBS514 Structured Programming (with Java) 37

Page 38: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

public class Time {

private int hour, minute;

public Time (int h, int m) { hour = h; minute = m; }

public void printTime () {

if ((hour == 0) && (minute == 0))

System.out.print("midnight");

else if ((hour == 12) && (minute == 0))

System.out.print("noon");

else {

if (hour == 0) System.out.print(12);

else if (hour > 12) System.out.print(hour-12);

else System.out.print(hour);

if (minute < 10) System.out.print(":0" + minute);

else System.out.print(":" + minute);

if (hour < 12) System.out.print("AM");

else System.out.print("PM");

}

}

Time – Example

BBS514 Structured Programming (with Java) 38

Page 39: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

public Time addMinutes (int m) {

int totalMinutes = (60*hour + minute + m) % (24*60);

if (totalMinutes < 0)

totalMinutes = totalMinutes + 24*60;

return new Time(totalMinutes/60, totalMinutes%60);

}

public Time subtractMinutes (int m) { return addMinutes(-m); }

public boolean priorTo (Time t) {

return ((hour < t.hour) ||

((hour == t.hour) && (minute < t.minute)));

}

public boolean after (Time t2) { return t2.priorTo(this); }

Time – Example

BBS514 Structured Programming (with Java) 39

Page 40: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

public class TimeDemo {

public static void main (String[] args) {

Time t1 = new Time(0,0),

t2 = new Time(12,0),

t3 = new Time(8,45),

t4 = new Time(14,14);

System.out.print("midnight - "); t1.printTime(); System.out.println();

System.out.print("noon - "); t2.printTime(); System.out.println();

System.out.print("8:45AM - "); t3.printTime(); System.out.println();

System.out.print("2:14PM - "); t4.printTime(); System.out.println();

t1 = t1.addMinutes(4*60);

System.out.print("4:00AM - "); t1.printTime(); System.out.println();

t1 = t1.addMinutes(-2*60);

System.out.print("2:00AM - "); t1.printTime(); System.out.println();

t1 = t1.addMinutes(-6);

System.out.print("1:54AM - "); t1.printTime(); System.out.println();

t1 = t1.addMinutes(-2*60);

System.out.print("11:54PM - "); t1.printTime(); System.out.println();

Time – Example

BBS514 Structured Programming (with Java) 40

Page 41: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

t1 = t1.subtractMinutes(8);

System.out.print("11:46PM - "); t1.printTime(); System.out.println();

t1 = t1.subtractMinutes(24*60);

System.out.print("11:46PM - "); t1.printTime(); System.out.println();

System.out.println("true - " + t1.priorTo(new Time(23, 47)));

System.out.println("false - " + t1.priorTo(new Time(3, 47)));

System.out.println("true - " + (new Time(23, 47)).after(t1));

System.out.println("false - " + (new Time(3, 47)).after(t1));

}

Time – Example

BBS514 Structured Programming (with Java) 41

Page 42: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• Method overloading is the process of using the same method name for multiple

purposes.

• The signature of each overloaded method must be unique.

– The signature of a method is based on the number, types and the order of the

parameters (not return type).

• The compiler must be able to determine which version of the method is invoked by

analyzing the parameters of a method call.

• println is an overloaded method

println(String s) System.out.println(“abcd”);

println(int i) System.out.println(5);

Method Overloading

BBS514 Structured Programming (with Java) 42

Page 43: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

• The constructors of the classes are often overloaded to provide multiple ways to set

up a new object.

class T {

private int x,y;

public T() { x=0; y=0; }

public T(int v1, int v2) { x=v1; y=v2; }

}

in somewhere else

T o1 = new T();

T o2 = new T(5,6);

Method Overloading

BBS514 Structured Programming (with Java) 43

Page 44: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

public class OverloadedMethodsDemo {

static void m() { System.out.println("m-noarg"); }

static void m(int x, int y) { System.out.println("m-i-i"); }

static void m(double x, double y) { System.out.println("m-d-d"); }

static void m(int x, double y) { System.out.println("m-i-d"); }

static void m(double x, int y) { System.out.println("m-d-i"); }

static void m(int x) { System.out.println("m-i"); }

static void m(short x) { System.out.println("m-s"); }

static void m(byte x) { System.out.println("m-b"); }

public static void main(String args[]){

System.out.print("m(1,2) -- "); m(1,2);

System.out.print("m() -- "); m();

System.out.print("m(1.1,2.2) -- "); m(1.1,2.2);

System.out.print("m(1,2.2) -- "); m(1,2.2);

System.out.print("m(1.1,2) -- "); m(1.1,2);

System.out.print("m(1) -- "); m(1);

System.out.print("m((byte)1) -- "); m((byte)1);

System.out.print("m((short)1) -- "); m((short)1);

System.out.print("m((int)1) -- "); m((int)1);

}

}

Overloaded Methods

BBS514 Structured Programming (with Java) 44

Page 45: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

public class RationalNum {

// Fields: a rational number is numerator/denominator

private int numerator, denominator;

// Constructors – Assume that parameters are positive

public RationalNum(int n, int d) {

int gcd = gcdivisor(n,d);

numerator = n/gcd;

denominator = d/gcd;

}

public RationalNum(int n) {

numerator = n;

denominator = 1;

}

public RationalNum() {

numerator = 0;

denominator = 1;

}

RationalNum – Constructors

BBS514 Structured Programming (with Java) 45

Page 46: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

// gcdivisor -- finds the greatest common divisor

// of the given two integers

private static int gcdivisor(int n1, int n2) {

if (n1==0 && n2==0) return 1;

else if (n1==0) return n2;

else if (n2==0) return n1;

else {

// they are not zero, Apply Euclid's algorithm

// for these positive numbers

while (n1 != n2) {

if (n1>n2) n1=n1-n2;

else n2=n2-n1;

}

return n1;

}

}

RationalNum – gcdivisor

BBS514 Structured Programming (with Java) 46

Page 47: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

// add method -- add the current rational number with

// another rational number or an integer.

public RationalNum add(RationalNum r2) {

return(

new RationalNum(

numerator*r2.denominator+r2.numerator*denominator,

denominator*r2.denominator));

}

public RationalNum add(int n2) {

return(new RationalNum(numerator+n2*denominator,denominator));

}

RationalNum – add

BBS514 Structured Programming (with Java) 47

Page 48: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

// subtract method -- subtract another rational number or

// an integer fromthe current rational number.

public RationalNum subtract(RationalNum r2) {

return(

new RationalNum(

numerator*r2.denominator-r2.numerator*denominator,

denominator*r2.denominator));

}

public RationalNum subtract(int n2) {

return(new RationalNum(numerator-n2*denominator,denominator));

}

RationalNum –subtract

BBS514 Structured Programming (with Java) 48

Page 49: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

// compareTo -- compare the current rational number with

// another rational number or an integer.

// returns 0 if they are equal;

// returns –1 if current rational number is less than given parameter;

// returns 1 otherwise

public int compareTo(RationalNum r2) {

if (numerator*r2.denominator < r2.numerator*denominator) return -1;

else if (numerator*r2.denominator == r2.numerator*denominator) return 0;

else return 1;

}

public int compareTo(int n2) {

if (numerator < n2*denominator) return -1;

else if (numerator == n2*denominator) return 0;

else return 1;

}

// toString method -- the string representation of

// a rational number is numerator/denominator.

public String toString() {

return(numerator+"/"+denominator);

}

RationalNum – compareTo and toString

BBS514 Structured Programming (with Java) 49

Page 50: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

import java.util.Scanner;

public class RationalNumDemo {

public static void main( String args[] ) {

RationalNum r1,r2;

int n1,n2,d1,d2;

Scanner keyboard = new Scanner(System.in);

System.out.println("The value of new RationalNum(): " +

(new RationalNum()));

System.out.println("The value of new RationalNum(3): " +

(new RationalNum(3)));

System.out.println("The value of new RationalNum(4,6): " +

(new RationalNum(4,6)));

RationalNumDemo

BBS514 Structured Programming (with Java) 50

Page 51: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

System.out.print("Enter the first numerator: ");

n1 = keyboard.nextInt();

System.out.print("Enter the first denominator: ");

d1 = keyboard.nextInt();

System.out.print("Enter the second numerator: ");

n2 = keyboard.nextInt();

System.out.print("Enter the second denominator: ");

d2 = keyboard.nextInt();

r1 = new RationalNum(n1,d1);

r2 = new RationalNum(n2,d2);

RationalNumDemo

BBS514 Structured Programming (with Java) 51

Page 52: Objects and Classes - Hacettepe ÜniversitesiObjects and Classes • Object-oriented programming (OOP) involves programming using objects. • An object represents an entity in the

System.out.println("r1: " + r1);

System.out.println("r2: " + r2);

System.out.println("r1.add(r2): " + r1.add(r2));

System.out.println("r1.add(3): " + r1.add(3));

System.out.println("r1.subtract(r2): " + r1.subtract(r2));

System.out.println("r1.subtract(3): " + r1.subtract(3));

System.out.println("r1.compareTo(r2): " + r1.compareTo(r2));

System.out.println("r1.compareTo(3): " + r1.compareTo(3));

}

RationalNumDemo

BBS514 Structured Programming (with Java) 52