0% found this document useful (0 votes)
10 views

Chapter 3 Methods ObjectAzizah

Uploaded by

suranaishah
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Chapter 3 Methods ObjectAzizah

Uploaded by

suranaishah
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 43

Chapter 3

Methods, Class and Object


Objectives

• Create methods with no arguments, a single argument,


and multiple arguments
• Create methods that return values
• Learn about class concepts
• Create a class
• Create instance methods in a class
• Declare objects and use their methods
• Understand how to use constructors,mutator and
accessor
• This references
Introduction to a Method
 Method is a functionality to perform an operation.
 All methods, void or non-void methods can have parameter.
 Parameter is a variable or value that is received from the calling
statement.
 Argument is a variable or value that is passed to the method header
Introducing Methods

A method is a collection of statements that are


grouped together to perform an operation.
Define a method Invoke a method

modifier return value type method name formal parameters

method
public static int max(int num1, int num2) { int z = max(x, y);
header

int result;
method actual parameters
body parameter list (arguments)
if (num1 > num2)
result = num1;
else
result = num2;
return value
return result;
}
Placement of Methods within a
Class
PURPOSE FOR USING
METHOD
• Work on one method can focus the action until you feel it efficient
• Different person can use different method
• Reusable
• Can enhance the program readability because method reduces
complexity.
First Class with main() Calling
nameAndAddress()
Calling Methods
This program demonstrates calling a method max
to return the largest of the int values
pass the value of i
pass the value of j

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
Types of method
• Predefined method
– Math.h
– Character-toString()
– charAt(0)
• User defined method
– one class
– Multiple classes- must create object object instance.
Predefined Classes
• Methods already written and provided by Java
• Organized as a collection of classes (class libraries)
• To use: import package
• Method type: data type of value returned by method

10
Predefined Classes
(continued)

11
User-Defined Methods
• Value-returning methods
– Used in expressions
– Calculate and return a value
– Can save value for later calculation or print value
• modifiers: public, private, protected, static, abstract, final
• returnType: type of the value that the method calculates and returns (using
return statement)
• methodName: Java identifier; name of method

12
Creating Methods that Return
Values
• Return type can be any type used in Java
– Primitive types
– Class types
– void
• Returns nothing
• Method’s type
• return statement
– Causes value to be sent from called method back to calling method
User Defined Method
• There are two types of method
– Void Method
• Defined as non returnable method. It will not return anything to the
calling statement. It will have void keyword in the method header
• Eg: public void Calculate( )
{
}
– Non-Void Method
• Defined as returnable method. It will return a value to the calling
statement. Consist of one return statement. It will have the data
types keyword in the method header.
• Eg: public int Calculate ( )
{
return 23;
}
The predictRaise() Method
The predictRaise() Method
Returning a double
Programming Example:
Largest Number (in single
class)
• Input: set of 10 numbers
• Output: largest of 10 numbers
• Solution
– Get numbers one at a time
– Method largest number: returns the larger of 2 numbers
– For loop: calls method largest number on each number received and
compares to current largest number

Java Programming: From Problem Analysis to Program Design, 3e 17


Solution: Largest
Number.java
static Scanner console = new Scanner(System.in);

public static void main(String[] args)


{
double num;
double max;
int count;
System.out.println("Enter 10 numbers.");
num = console.nextDouble();
max = num;
for (count = 1; count < 10; count++)
{
num = console.nextDouble();
max = larger(max, num);
}
System.out.println("The largest number is " + max);
}
public static double larger(double x,double y)
{
if (x>=y)
return x;
else
return y;
}
}
18
Sample Run: Largest Number

• Sample Run:

Enter 10 numbers:
10.5 56.34 73.3 42 22 67 88.55 26 62 11
The largest number is 88.55

Java Programming: From Problem Analysis to Program Design, 3e 19


Learning About Class Concepts
• Every object is a member of more general class
• Is-a relationships
– Object “is a” member of class
• Instantiation
• Reusability
Learning About Class Concepts
(continued)
• Methods often called upon to return piece of information to source of
request
• Class client or class user
– Application or class that instantiates objects of another prewritten
class
Declaring Objects and Using
Their Methods
• Declaring class does not create any actual objects
• Create instance of class
– Supply type and identifier
– Allocate computer memory for object
– Use new operator
Employee someEmployee;
someEmployee = new Employee();
– Or
Employee someEmployee = new Employee();
Declaring Objects and Using
Their Methods (continued)
• After object instantiated
– Methods accessed using:
• Object’s identifier
• Dot
• Method call

• Example
– myEmployee .InfoDetail();
Class Diagram for Bicycle

Bicycle

Bicycle( )
Method
MethodListing
Listing
getOwnerName( ) We
We list the nameand
list the name andthe
the
data type of an argument
data type of an argument
passed
passedtotothe
themethod.
method.
setOwnerName(String)
Multiple Instances
• Once the Bicycle class is defined, we can create multiple instances.

Bicycle bike1, bike2;


bike1 = new Bicycle( );
bike1.setOwnerName("Adam Smith");

bike2 = new Bicycle( );


bike2.setOwnerName("Ben Jones");
The Definition of the Bicycle
Class
class Bicycle {
// Data Member
private String ownerName;
//Constructor: Initialzes the data member Bicycle
public void Bicycle( ) {
ownerName = "Unknown";
} -ownerName:String
+Bicycle( )
//Returns the name of this bicycle's owner
public String getOwnerName( ) {
+getOwnerName( ):String
return ownerName;
}
+setOwnerName(String):void
//Assigns the name of this bicycle's owner
public void setOwnerName(String name) {
ownerName = name;
}
}
First Example: Using the
Bicycle Class
class BicycleTest {
public static void main(String[] args) {
Bicycle bike1, bike2;// declare variable of type bicycle
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.");


}
}
The Program Structure and
Source Files
BicycleTest Bicycle

There
Thereare
aretwo
twosource
sourcefiles.
files.
Each class definition
Each class definition isis
stored
storedininaaseparate
separatefile.
file.
BicycleTest.java Bicycle.java

To run the program: 1. javac Bicycle.java (compile)


2. javac BicycleTest.java (compile)
3. java BicycleTest (run)

In jCreator: Compile Bicycle.java and BicycleTest.java, then run


BicycleTest.java only!
User Defined Method
• Multiple classes
• Ceate an object instance
• In single class • RoomTypeTest.java
• public class RoomTypeTest
• First.java • {
• public static void main (String [] args)
• {
• RoomType roomOne; // declare the class
• roomOne = new RoomType()//create object
• roomOne.Info();

• RoomType.java
• public class RoomType
• {
• // data declaration
• double length;
• double width;
• }
• public void info(){
• System.out.println(“ the hotel name is A++”);
• }
Method without parameter
:: Example ::

class Employee
{
public void CalSalary ( ) No parameter received
{
//…statements…
}
}

class EmployeeTest
{
public static void main (String[ ] args)
{

Employee myEmployee = new Employee( );


myEmployee.CalSalary ( ); No argument passed

}
}
Method with parameter
:: Example ::

class Employee
{
public void CalSalary (int basic) //…statements… 1 parameter received
{ as integer

}
}

class EmployeeTest
{
public static void main(String[ ] args)
{
Employee myEmployee = new Employee( );
myEmployee.CalSalary ( 4000); 1 integer argument passed
}
}
Method with parameter
:: Example ::

class Employee
{
public void CalSalary (int basic, double rate) 2 parameters received
{ integer and double
//…statements…
}
}

class EmployeeTest
{
public static void main (String[ ] args)
{
Employee myEmployee = new Employee( );
myEmployee.CalSalary( 4000, 1.7); 2 arguments passed
integer and double
}
}

• NOTE: Argument is passed by location and with correspondence data type to the receiving
parameter
Method with parameter
:: Example ::

class Employee
{
public void CalSalary (int Basic, double Rate) 2 parameters received
{ integer and double
//…statements…
}
}

class EmployeeTest
{
public static void main (String[ ] args)
{
Employee myEmployee = new Employee( );
int Pay = 4000;
double PayRate= 1.7;
myEmployee.CalSalary (Pay, PayRate); 2 arguments passed
integer and double
}
}
::Example::
Non-void method without parameter

import java.util.*;
class Number class NumberTest
{ {
public int output; public static void main (String[ ]args)
{
public int CheckNumber( ) Number myNum = new Number();
{
int num; int result = myNum.CheckNumber();
Scanner sc = new System.out.println(“ The answer
Scanner(System.in); is” + result);
System.out.println(“Enter an }
integer”); }
num = sc.nextInt();
if (num >0)
output=1;
else
if (num < 0)
output= -1;
return output;
}
::Example::
Non-void method with parameter

import java.util.*;
class Number
{ class NumberTest{
public int output; public static void main(String[ ] args)
{
public int CheckNumber(int Scanner s= new Scanner(System.in);
num) Number myNum=new Number();
{ int num;
if (num >0) System.out.println(“Enter an integer”);
output=1; num = s.nextInt();
else int result = myNum.CheckNumber( num);
if (num < 0) System.out.println(“ The answer
is”+result);
output= -1;
}
return output; }
}
}
Example of void Method
Method declaration:
class Vehicle
{
public void DisplayMessage( ) //void method header
{
System.out.println(“Hello, welcome to Vehicle class”);
}
}
Hello, welcome to
Invocation/Calling statement:
Vehicle class
class VehicleTest
{
public static void main(String[ ] args)
{
Vechicle myVehicle = new Vehicle( );// declare and
create object
myVehicle.DisplayMessage( ); //invocation or method call

}
}
Example of Non-void Method
Method declaration:

class Vehicle
{
public int DisplayMessage( ) //non-void method header
{
System.out.println(“Hello, welcome to Vehicle class”);
return 123;
}
}
Hello, welcome to
Invocation/Calling statement: Vehicle class
The output is 123
class VehicleTest
{
public static void main(String[ ] args)
{
Vechicle myVehicle = new Vehicle( );
int result = myVehicle.DisplayMessage( );/invocation
or method call
System.out.println(“ The output is ”+ result);
}
::Check point::
• Create a method header and an invocation statement for the following:
1. In Class Employee, create public method named CalSalary that will
not return anything to the calling statement.
2. In Class Transportation, create a public method named
AirTransport, that will return an integer data type value to the
calling statement.
3. In Class Festival, create a public method named EidFitri that will
return a string data type value to the calling statement.
4. In Class RectangleArea, create a public method named
CalculateArea with no parameter that will return double data type
of area to the calling statement.
5. Modify question 4. Two parameters received of double data type
and return double data type to the calling statement.
::Check point 1::
• Create a method header and an invocation statement for the following:
– In Class Employee, create public method named CalSalary that will not return
anything to the calling statement.

Answer:

class Employee
{
public void CalSalary( )
{
}
}

class EmployeeTest
{
public static void main ( String[ ] args)
{
Employee myEmployee = new Employee( );
//create a class
myEmployee.CalSalary( );
}
::Check point 2::
• Create a method header and an invocation statement for the following:
– In Class Transportation, create a public method named AirTransport, that will return an integer data type
value to the calling statement.
Answer:

class Transportation
{
public int AirTransport( )
{
return 947;
}
}
class TransportationTest
{
public static void main(String[ ] args)
{
Transportation myTransport = new
Transportation( );
int result = myTransport. AirTransport( );
System.out.println (“The output is” + result);
}
::Check point 3::
• Create a method header and an invocation statement for the following:
– In Festival class, create a public method named EidFitri that will return a string data type value to the
calling statement.

Answer:

class Festival
{
public String EidFitri( )
{
return “Rendang”;
}
}

class FestivalTest
{
public static void main (String[ ] args)
{
Festival myFest= new Festival ( );
String raya = myFest. EidFitri( );
System.out.println(“The message is” +raya);
}
Summary
• Method
– Series of statements that carry out a task
– Declaration includes argument type and local name for argument
– Can pass multiple arguments to methods
– Has return type
• Class objects
– Have attributes and methods associated with them
• Instantiate objects that are members of class
B a = new B();

You might also like