[go: up one dir, main page]

0% found this document useful (0 votes)
24 views47 pages

4 - Lec - Classes and Methods

Uploaded by

Malik Abdul Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views47 pages

4 - Lec - Classes and Methods

Uploaded by

Malik Abdul Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

Classes and Methods

Basic Terminology
• A class defines a kind of objects:
• specifies the kinds of attributes (data) an object of the class
can have.
• provides methods specifying the actions an object of the class
can take.

• An object is an instance of the class.


• Person is a class
• Alice and Bob are objects of the Person class.
What does a class have?
• Members of a class:
• Attributes (instance variables, data)
• For each instance of the class (object), values of attributes can vary,
hence instance variables
• Methods

• Person class
• Attributes: name, address, phone number
• Methods: change address, change phone number

• Alice object
• Name is Alice, address is …

• Bob object
• Name is Bob, address is …
A Class as
an Outline
Methods
• Class provides one or more methods
• Method represents task in a program
• Describes the mechanisms that actually perform its tasks
• Hides from its user the complex tasks that it performs
• Method call tells method to perform its task

• Calling a method
• Object name, then dot separator (.)
• Then method name and parentheses

5
Method Definitions
• Methods belong to a class
• Defined inside the class
• Heading
• Return type (e.g. int, float, void)
• Name (e.g. nextInt, println)
• Parameters (e.g. println(…) )
• More…
• Body
• enclosed in braces {}.
• Declarations and/or statements.
7

• GradeBook.java
1 // Fig. 3.1: GradeBook.java
2 // Class declaration with one method.
3
4 public class GradeBook
5 {
6 // display a welcome message to the GradeBook user Print line of text to output
7 public void displayMessage()
8 {
9 System.out.println( "Welcome to the Grade Book!" );
10 } // end method displayMessage
11
12 } // end class GradeBook
8

• GradeBookTest.java
1 // Fig. 3.2: GradeBookTest.java
2 // Create a GradeBook object and call its displayMessage method.
3
4 public class GradeBookTest
5 {
6 // main method begins program execution
7 public static void main( String args[] )
8 {
9 // create a GradeBook object and assign it to myGradeBook Use class instance creation
10 GradeBook myGradeBook = new GradeBook(); expression to create object of
11 class GradeBook
12 // call myGradeBook's displayMessage method
13 myGradeBook.displayMessage();
Call method
displayMessage using
14 } // end main
GradeBook object
15
16 } // end class GradeBookTest

Welcome to the Grade Book!


Java Sample Program
Ex-1
Ex-1 solution
Adding parameters to method and return values
Adding Multiple parameters to method and return values
Adding Multiple parameters to method and return values
Ex-2
Ex-2 –Solution
Storing and Accessing Instance Variables of an Object
Adding a Method to a Class
Returning a Value from a Class Method
Class Methods with Parameters
Class Files and Separate
Compilation
• One class definition per file
• File name and class name are the same
• File extension is .java
• After compilation
• byte code is stored in a file with extension .class
• Execution
• .class is run in the JVM
• Multiple .class files in the same directory
• No need to import them
Two Types of Methods

1. Return a value
• next = keyboard.nextInt();
• keyboard is the calling object.

2. Don’t return a value, called void method


• System.out.println(“Enter data:”);
• System.out is the calling object
void Method Definitions
• example
public void writeOuput() //heading
{ //body
System.out.println(“Name: “ + name);
System.out.println(“Age: “ + age);
}
Defining Methods That Return a
Value
• example
public float density(float area) // heading
{ // body
return population / area;
}
Defining Methods That Return a
Value (cont.)
• must contain return statement
return Expression;
• Expression must have a type that matches the return type

• multiple return statements are allowed


• a single return statement is better (one exit point for
the method).
Naming Methods
• Use a verb to name methods
• Actions
• getBalance, deposit, changeAddress
• Start a method name with a lowercase letter.
public Method Definitions
• syntax for a void method
public void methodName(parameters)
{
<statement(s)>
}
public Method Definitions
• syntax for methods that return a value
public returnType methodName(parameters)
{
<statement(s), including a
return statement>
}
Local Variables
• Declared within a method
• “local to” (confined to) the method definition
• can’t be accessed outside the method

• Not attributes (instance variables)


Local Variables, cont.
• class BankAccount
• class LocalVariablesDemoProgram
Scope of a local variable
• The region in the program where the local variable can be
accessed
• Start: declaration of the variable
• End: the closing } of the block in which the variable is declared
public void method1()
Example of { // begin of block
int x;
Scope if (…)
{ // begin of block
int y; // can’t have int x here, confusing
anyway

}
else
{ // begin of block
… // can y be used here?
}
… // can y be used here?
}

public int method2()


{ // begin of block
int x; // can I do this?


return x;
}
Example of Scope
public void method()
{
for (int i=0; i < 10; i++) // start of a block
{
int y=0;

}
// Are i and y accessible here?
}
Passing Values to a Method:
Parameters
• Input values for methods (within the program, not from user)
• passed values or parameters
• More flexibility for methods
• formal parameters
• Part of method definition
• After the method name, within parentheses
• type
• name
• arguments, or actual parameters
• Calling a method with an object within the parentheses
• matching data type
• in the same order
Formal vs Actual Parameters
public static void main(String[] args)
{
print(“George Bush”); //“George Bush” as argument
}

public static void print(String name) //name as parameter


{
System.out.print(“The name is: “ + name);
}
Parameter Passing Example
//Definition of method to square an integer
public int doubleValue(int numberIn)
{
return 2 * numberIn;
}

//Invocation of the method... somewhere in main...


...
int square = keyboard.nextInt();
System.out.println(someObj.doubleValue(square));
//calling
• What is the formal parameter in the method definition?
• numberIn
• What is the argument (actual parameter) in the method invocation?
• square
Arguments to Methods
• An argument in a method invocation can be
• a literal such as 2 or ‘A’
• a variable
• an expression that yields a value
[technically a literal or variable is also an “expression”]
Multiple Arguments to Methods
anObject.doStuff(42, 100, 9.99, ‘Z’);
public void doStuff(int n1, int n2, double d1,
char c1);

• arguments and formal parameters are matched by position


• Corresponding types need to match
public and private
public
• Attribute (instance variable)
• any class can directly access/change

• Method
• any class can invoke

private
• Attribute (instance variable)
• only the same class can access/change

• Method
• only the same class can invoke
private or public ?
• Attributes (instance variables)
• should be private, why?

• Methods
• usually public, why?
• sometimes private

• Default is package access in Java


• Convention is to explicitly state public or private
Accessors (get) and Mutators (set)
Methods
• Accessor / get methods—public methods that allow attributes (instance
variables) to be read
• Mutator / set methods—public methods that allow attributes (instance
variables) to be modified
• Check to make sure that changes are appropriate.
• Much better than making instance variables public

private attributes (instance variables) with public accessor and


mutator methods
• Use set methods to alter the value
• Use get methods to retrieve the value
Set Methods
• Fields in classes are usually private and therefore cannot be accessed from
outside the class.
• To assign values to such fields we need public methods that can be called by
application classes external to the class in which they are defined.
• The practice of assigning a value to a private field is so common that methods
which are specifically intended to do so are called “set methods”.
• For example, a set method in Circle class
public void setRadius(double cRad) {
radius = cRad;
}
Get Methods
• Another common requirement is for an application calls to access (get)
the value associated with a private field defined in another class.
• To do this it is common practice to define a public method for each field
which may need to be accessed that returns the value for each field.
• Such methods are generally referred to as "get methods".
• For example, a get method in Circle class
public double getRadius() {
return radius;
}
Account Class with an Instance Variable, and
set and get Methods
Circle Class Definition
CircleTest Class Definition
Class Task – Get and Set Methods
• Write a class called Person with the following attributes:
 title (Dr., Mr., Mrs., Ms.)
 first name
 last name
 age in years
 gender (boolean - true/false to indicated either male or female)

• The Person class should have a setter method with public access for each attribute.
• The Person class should have a getter method with public access for each attribute.
• For a Person with the following attributes:
title = "Mr."
first name = "William"
last name = "Gates"
age = 44
gender = true (true is male, false is female, or vice versa)
• The Person class should have the following public access methods that return Strings as follows:
standardName() formalName()
concatenation of the first and last names concatenation of the title, first name, and lastname
(i.e., "William Gates") (i.e., "Mr. William Gates")

You might also like