Top Banner
1 User Defined Class
32

Class & Object - User Defined Method

May 20, 2015

Download

Education

PRN USM

Chapter 6-2
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Class & Object - User Defined Method

1

User Defined ClassUser Defined Class

Page 2: Class & Object - User Defined Method

Syntax: Defining Class General syntax for defining a class is:

modifieropt class ClassIdentifier{

classMembers: data declarations

methods definitions}

Wheremodifier(s) are used to alter the behavior of the

classclassMembers consist of data declarations and/or

methods definitions.

2

Page 3: Class & Object - User Defined Method

Class Definition A class can contain data declarations and method

declarations

3

int size, weight;char category;

Data declarations

Method declarations

Page 4: Class & Object - User Defined Method

UML Design Specification

4

UML Class Diagram

Class Name

What data does it need?

What behaviors will it perform?

Publicmethods

Hiddeninformation

Instance variables -- memory locations used for storing the information needed.

Methods -- blocks of code used to perform a specific task.

Page 5: Class & Object - User Defined Method

Class Definition: An Example public class Rectangle {

// data declarations private double length; private double width;

//methods definitions public Rectangle(double l, double w) // Constructor method { length = l; width = w; } // Rectangle constructor

public double calculateArea() { return length * width; } // calculateArea

} // Rectangle class

5

Page 6: Class & Object - User Defined Method

Method Definition Example

6

The Method Header modifieropt ResultType MethodName (Formal ParameterList )

public static void main (String argv[ ] )

public void deposit (double amount)

public double calculateArea ( )

public void MethodName() // Method Header{ // Start of method body } // End of method body

Page 7: Class & Object - User Defined Method

Method Header A method declaration begins with a method header

7

int add (int num1, int num2)

methodname

returntype

Formal parameter list

The parameter list specifies the typeand name of each parameter

The name of a parameter in the methoddeclaration is called a formal parameter

Page 8: Class & Object - User Defined Method

Method Body The method header is followed by the method body

8

int add (int num1, int num2)

{ int sum = num1 + num2;

return sum;}

The return expressionmust be consistent withthe return type

sum is local data

Local data are created each time the method is called, and are destroyed when it finishes executing

Page 9: Class & Object - User Defined Method

User-Defined Methods

Methods can return zero or one valueValue-returning methods

○ Methods that have a return typeVoid methods

○ Methods that do not have a return type

9

Page 10: Class & Object - User Defined Method

calculateArea Method.

public double calculateArea(){ double area; area = length * width;

return area;

}

10

Page 11: Class & Object - User Defined Method

Return statement

Value-returning method uses a return statement to return its value; it passes a value outside the method.

Syntax:return statementreturn expr;

Where expr can be:Variable, constant value or expression

11

Page 12: Class & Object - User Defined Method

User-Defined Methods

Methods can have zero or >= 1 parametersNo parameters

○ Nothing inside bracket in method header1 or more parameters

○ List the paramater/s inside bracket

12

Page 13: Class & Object - User Defined Method

Method Parameters- as input/s to a method

public class Rectangle{

. . . public void setWidth(double w) { width = w; }

public void setLength(double l) { length = l; } . . .

}

13

Page 14: Class & Object - User Defined Method

Syntax: Formal Parameter List

(dataType identifier, dataType identifier....)

14

Note: it can be one or more dataType

Eg.

setWidth( double w )

int add (int num1, int num2)

Page 15: Class & Object - User Defined Method

Creating Rectangle Instances Create, or instantiate, two instances of the Rectangle

class:

15

The objects (instances) store actual values.

Rectangle rectangle1 = new Rectangle(30,10);

Rectangle rectangle2 = new Rectangle(25, 20);

Page 16: Class & Object - User Defined Method

Using Rectangle Instances We use a method call to ask each object to

tell us its area:

16

rectangle1 area 300rectangle2 area 500Printed output:

System.out.println("rectangle1 area " + rectangle1.calculateArea());

System.out.println("rectangle2 area " + rectangle2.calculateArea());

References to objects

Method calls

Page 17: Class & Object - User Defined Method

Syntax : Object Construction new ClassName(parameters);

Example: new Rectangle(30, 20); new Car("BMW 540ti", 2004);

Purpose: To construct a new object, initialize it with

the construction parameters, and return a reference to the constructed object.

17

Page 18: Class & Object - User Defined Method

The RectangleUser Class Definition

public class RectangleUser{ public static void main(String argv[]) { Rectangle rectangle1 = new Rectangle(30,10); Rectangle rectangle2 = new Rectangle(25,20); System.out.println("rectangle1 area " + rectangle1.calculateArea()); System.out.println("rectangle2 area " + rectangle2.calculateArea()); } // main()} // RectangleUser

18

An application must have a main() method

Object Use

ObjectCreation

ClassDefinition

Page 19: Class & Object - User Defined Method

Method Call

Syntax to call a method

methodName(actual parameter list);

Eg.

segi4.setWidth(20.5); obj.add (25, count);

19

Page 20: Class & Object - User Defined Method

Formal vs Actual Parameters When a method is called, the actual parameters in the

invocation are copied into the formal parameters in the method header

20

int add (int num1, int num2)

{ int sum = num1 + num2;

return sum;}

total = obj.add(25, count);

Page 21: Class & Object - User Defined Method

public class RectangleUser { public static void main(String argv[]) { Rectangle rectangle1 = new Rectangle(30.0,10.0); System.out.println("rectangle1 area " + rectangle1.calculateArea());

rectangle1.setWidth(20.0); System.out.println("rectangle1 area " + rectangle1.calculateArea()); } }

21

Formal vs Actual Parameters

Page 22: Class & Object - User Defined Method

Method Overloading In Java, within a class, several methods can

have the same name. We called method overloading

Two methods are said to have different formal parameter lists:If both methods have a different number of formal parameters

If the number of formal parameters is the same in both methods, the data type of the formal parameters in the order we list must differ in at least one position

22

Page 23: Class & Object - User Defined Method

Method Overloading

Example:public void methodABC()

public void methodABC(int x)

public void methodABC(int x, double y)

public void methodABC(double x, int y)

public void methodABC(char x, double y)

public void methodABC(String x,int y)

23

Page 24: Class & Object - User Defined Method

Java code for overloading public class Exam { public static void main (String [] args) { int test1=75, test2=68, total_test1, total_test2; Exam midsem=new Exam(); total_test1 = midsem.result(test1); System.out.println("Total test 1 : "+ total_test1); total_test2 = midsem.result(test1,test2); System.out.println("Total test 2 : "+ total_test2); } int result (int i) { return i++; } int result (int i, int j) { return ++i + j; } }

24

Page 25: Class & Object - User Defined Method

Output

Total test 1 : 75

Total test 2 : 144

25

Page 26: Class & Object - User Defined Method

Constructors Revisited Properties of constructors:

Name of constructor same as the name of classA constructor,even though it is a method, it has no

typeConstructors are automatically executed when a

class object is instantiated A class can have more than one constructors –

“constructor overloading”○ which constructor executes depends on the type of

value passed to the constructor when the object is instantiated

26

Page 27: Class & Object - User Defined Method

Java code (constructor overloading)public class Student{ String name; int age;

Student(String n, int a){ name = n; age = a;

System.out.println ("Name1 :" + name);System.out.println ("Age1 :" + age);

}Student(String n){

name = n; age = 18;System.out.println ("Name2 :" + name);System.out.println ("Age2 :" + age);

}public static void main (String args[]){

Student myStudent1=new Student("Adam",22);Student myStudent2=new Student("Adlin");

}} 27

Page 28: Class & Object - User Defined Method

28

Output:

Name1 :Adam

Age1 :22

Name2 :Adlin

Age2 :18

Page 29: Class & Object - User Defined Method

Object Methods & Class Methods Object/Instance methods belong to

objects and can only be applied after the objects are created.

They called by the following :objectName.methodName();

Class can have its own methods known as class methods or static methods

29

Page 30: Class & Object - User Defined Method

Static Methods Java supports static methods as well as static variables. Static Method:-

Belongs to class (NOT to objects created from the class) Can be called without creating an object/instance of the

class To define a static method, put the modifier static in the

method declaration: Static methods are called by :

ClassName.methodName();

30

Page 31: Class & Object - User Defined Method

Java Code (static method)

public class Fish

{

public static void main (String args[])

{

System.out.println ("Flower Horn");

Fish.colour();}

static void colour (){

System.out.println ("Beautiful Colour");

}

}

31

Page 32: Class & Object - User Defined Method

32

Output:

Flower Horn

Beautiful Colour