Você está na página 1de 30

1 | P a g e

Lecture 1 - INTRODUCTION
Introduction to OOP and objects
object-oriented programming: a programming method that uses "objects" and their interactions to design applications
and computer programs. It involves classes and objects.
o Object-oriented programs consist of interacting objects. >> uses objects

An object is a thing, both tangible and intangible. For example account1, vehicle2, employee7, etc.
o For example, a bank program may consist of Account, Customer, Transaction, and ATM objects.

Objects:
o behave in a certain way operations
o Contain certain types of information - class

Classes
A class is:
o an abstract definition of an object
o a template for producing objects of a certain type.
o is a plan from which one or more objects can be created
Example: Account, Employee, Student, Car, etc.
Naming convention: Class name starts with a capital letter and may include more than one word.

Objects
Objects are:
o a runtime instance of the corresponding class.
o an occurrence of a corresponding class at a given moment of time (instance).
o One to many objects can be created from one class. (grouped into classes
INSTANCE = OBJECT = OCCURANCE

o Examples of classes and
their objects: >>>>>

o Naming convention:
Object name starts with a lowercase letter and first letter of the next word is a capital letter.


2 | P a g e

Classes and Objects
An object/class is comprised of data (fields/attributes) and operations (methods) that manipulate these data.
Read-world objects share two characteristics: They all have state (fields) and behavior (methods).
o Data values=fields=attributes -> state
o Operations=methods ->behaviour
Real life : Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail).

Notation of a class >>>>>>>>>>>>>>>>>


o Fields/attributes (data): Fields/attributes describe the characteristics or are a description of a class/object.
Fields are also called as data members.

o Operations/methods: Operations/methods describe behavior of a class/object. They are actions that can be
carried out by, or on, a class/object.

A Java program must have one class designated as the main class. The designated main class must have the main
method.

Data Values (fields)
An object is comprised of data values and methods.
An object stores its state in data values (fields)
Examples: studentId, name, dob (Student object)
radius (Circle object)
position, currentSpeed (Car Object)

Messages and Methods
Objects do not carry information but are entities capable of carrying out tasks.
o E.g. moving, withdrawing

To instruct a class or an object to perform a task, we send a message to it.
You can send a message only to the classes and objects that understand the message you sent to them. A matching
method must have been defined in that class/object. Once a method is defined, then we can send a matching message
o the message = methods name

Argument : A value we pass to an object when sending a message. E.g. 200.00.
Examples of methods:
o myCar.drive(); >>>> myCar = object, Drive = method
o sv1001.deposit(200.00);


3 | P a g e

Template for Class Definition
Import Statements: Include a sequence of
import statements.

Comment: Use a comment to describe the
program

Class Name: Give a descriptive name to the
main class.

Fields:

Method Body: Include a sequence of
instructions.


Declare, create, use
To write an object-oriented program in Java, you must:
1. Declare an object name - a name we use to refer to an object
2. Create an object - the actual object which the declared name will refer to
3. Use an object - by sending messages to it

Example:
Car herbie;
herbie = new Car(red);
herbie.accelerate(0.5);

Object Declaration
object declaration: designates the name of an object and the class to
which the object belongs to.
declaring the name herbie, we will use to refer to a Car object.
More examples.
o Object of a BankAccount - BankAccount sv125;
o Object of a Student Student john,jim,marie;

Identifiers
Valid identifiers: Any identifier that is not reserved for other uses can be used as an object name
o Identifier: is a sequence of letters, digits, underscores (_), and the dollar sign, with the first one being a letter
o No spaces are allowed in an identifier.
o Java is case sensitive and hence upper- and lowercase letters are distinguished in Java.

Identifiers >>>> name a class, object, method, and others (variables and constants).
o Valid identifier Examples: x123, velocity

Conventions:
o Class names = start with uppercase
o Object names = start with lower case

4 | P a g e

Object Creation
To create the actual object, we need
to invoke the new operation.
More examples:
o customer = new Customer( );
o jon = new Student(John
Java);


Declare/create in one line
Normally, declaring and creating an object is two lines of code:
BankAccount myAccount;
myAccount = new BankAccount();

(Declare and create merged)
BankAccount myAccount = new BankAccount();

Sending a Message /Invoking a method
Format: object name.method name(argument);
o account.deposit(200.0);
o student.setName(john);
o car1.startEngine( );

There is always () after a call to a method. When there is no argument to be passed to the method, there is nothing
inside the ().

calling an objects method = sending a message to an object


Program 3










Date
The Date class from the java.util package is used to represent a date.
When a Date object is created, it is set to today (the current date set in the computer)
5 | P a g e

The class has toString method that converts the internal format to a string.
Date today;
today = new Date( );
today.toString( );
results in >>>>> Thu Dec 18 18:16:56 PST 2008
6 | P a g e

Lecture 2 numerical data
Manipulating Numbers
In Java, to add two numbers x and y, we write
o x + y

But addition of the two numbers , we must declare their data type. If x and y are integers, we write
int x, y; (int = data type, x = name used)
or
int x;
int y;

Variables
When the declaration is made, memory space is allocated to store the values of x and y.
x and y are called variables. A variable has three properties:
o A memory location to store the value,
o The type of data stored in the memory location, and
o The name used to refer to the memory location.
A variable only holds one value at a time
Sample variable declarations:
int x;
int v, w, y;

Numerical Data Types
There are six numerical data types: byte, short, int, long, float, and double.
Sample (example) variable declarations:
o int i, j, k;
o float numberOne;
o long bigInteger;
o double bigNumber;

At the time a variable is declared, it also can be initialized (GIVEN A VALUE).
o Example 1, we may initialize the integer variables count and height to 10 and 34 as
int count = 10, height = 34;

o Example 2, we may initialise the double variable of x as 10.345
double x = 10.345;

Data Type Precisions
The six data types differ in the
precision of values they can store
in memory (range of values that
can be represented).

USING INT + DOUBLE FOR
SUBJECT




7 | P a g e

Assignment Statements
We assign a value to a variable using an assignment statement. (END WITH
SEMICOLON)
The syntax is
<variable> = <expression> ;

A single variable appears to the left of equal symbol and an expression appears to the
right.
Examples:
sum = firstNumber + secondNumber;
average = (one + two + three) / 3.0;







Primitive Data Declaration and Assignments
CODE
int firstNumber, secondNumber; (variables are allocated in memory)
firstNumber = 234;
secondNumber = 87;
STATE OF MEMORY



Assigning Objects
CODE
Customer c1; (allocation to memory)
c1 = new Customer( ); (assigning of new reference to c1)
c1 = new Customer( ); (overwriting of reference to c1)
STATE OF MEMORY


Notice the content of the variable is not the value itself, as is the case with primitive data, but the address of, or
reference to, the memory location where the object data is stored. We use arrows to indicate this memory reference.

Having Two References to a Single Object
CODE
Customer clemens, twain; (allocation to memory)
clemens = new Customer( ); (assigning of new reference to clemens)
twain = clemens; (clemens = twain



Values are assigned to variables
8 | P a g e

Primitive vs. Reference
primitive data types = Numerical data
o Two non numerical primitive data types are boolean (true or false) and char (for character). char is used to
represent single character (letter, digit, punctuation marks, and others).

reference data types = Objects >> contents are addresses that refer to memory locations where the objects are
actually stored.

Qs

1. The first has two occurrences of variable a
The second and third both attempt to declare a
variable int, which is a reserved word.
The fourth has the variable name bigNumber and
the type double in the wrong order.

2. Both are illegal because they attempt to declare a
variable which has the same name as a variable in
the first line.
3. This is the question that is crossed out.
4. The second and third lines are invalid. They are
back to front.



Arithmetic Operators
The following table summarizes the arithmetic operators available in Java.
Integer vs double division
9/2 4 int
9%2 1 int
9.0/2.0 4.5 double
9.0%2.0 1.0 double


Arithmetic Expression
How does the expression
o x + 3 * y
get evaluated? Answer: x is added to 3*y.

We determine the order of evaluation by following the precedence rules.
A higher precedence operator is evaluated before the lower one. If two operators are the same precedence, then they
are evaluated left to right for most operators.
MODULO division + DIVISION = integer division.
MODULO - looks at the remainder
9 | P a g e


Precedence Rules
unary operator just means
negative numbers e.g. 4 + -3. it
operates on one operand only.

If you want to alter the precedence
rules, then use parentheses to
dictate the order of evaluation.




Type Casting
If x is a float and y is an int, what will be the data type of the following expression?
o x * y
The above expression is called a mixed expression.
The data types of the operands in mixed expressions are converted based on the promotion rules. The promotion rules
ensure that the data type of the expression will be the same as the data type of an operand whose type has the highest
precision.
A casting conversion, or type casting, is a process that converts a value of one data type to another data type.
o Two types of casting conversions in Java are implicit and explicit.
o An implicit conversion called numeric promotion is applied to the operands of an arithmetic operator.

Explicit Type Casting
Instead of relying on the promotion rules, we can make an explicit type cast by prefixing the operand with the data type
using the following syntax:
( <data type> ) <expression>

Example
o (float) x / 3 (Type cast (changes) x to data type float float and then divide it by 3.)
o (int) (x / y * 3.0) (Type cast (changes) the result of the expression x / y * 3.0 to int.)

Implicit Type Casting
Consider the following expression:
o double x = 3 + 5;

The result of 3 + 5 is of type int. However, since the variable x is double, the value 8 (type int) is promoted to 8.0 (type
double) before being assigned to x
Notice that it is a promotion. Demotion is not allowed.
o If the two operands are of different types, the smaller type is promoted to the bigger type
9 + 4.0 promotes to 9.0 + 4.0
1.0/2 promotes to 1.0/2.0
hello + 10 promotes to hello + 10

Summary of a program
A program is a sequence of statements.
o statement 1;
10 | P a g e

o statement 2;
o statement 3;
o statement 4;
o statement 5;
o statement 6;
o statement 7;
There are only 3 kinds of statement:
int a; <- Variable declaration
int b;
a = 3; <- Variable assignment
b = 4;
int result;
result = a + b;
System.out.println(result); <- Method invocation



Constants
Constant - when the value of a variable stays the same
o Java convention uses all capitalized letters for constants
o receive value straight away after declaring + put them before methods
final double PI = 3.14159;
final int MONTH_IN_YEAR = 12;
final short FARADAY_CONSTANT = 23060;



Constants: Sample Code Fragment
final double PI = 3.14159; (CONSTANT DECLATARATION)
double radius, area, circumference;
area = PI * radius * radius; (PERFORM calculation)
circumference = 2.0 * PI * radius;
System.out.println("Given Radius: " + radius);
System.out.println("Area: " + area);
System.out.println(" Circumference: + circumference); (report the answer (via standard output)

The DecimalFormat Class
Use a DecimalFormat object to format the numerical output
o When you print out a double value, you may get eight or nine decimal places. To limit the number of decimal
places to display, you can use the DecimalFormat class.

double num = 123.45789345;
DecimalFormat df = new DecimalFormat(0.000);
System.out.print(num); 123.45789345
System.out.print(df.format(num)); 123.458
11 | P a g e



Overloaded Operator +
The plus operator + can mean two different operations, depending on the context.
<val1> + <val2> is an addition if both are numbers. If either one of them is a String, the it is a concatenation.
Evaluation goes from left to right.
output = test + 1 + 2;

output = 1 + 2 + test;



Import Statement
import statement - allows the program to use classes and
their instances defined in the designated package.

Import Statement Syntax and Semantics
<package name>.<class name>;
e.g. dorm.Resident;
If you need to import more than one class from the same package,
then instead of using an import statement for every class, you can
import them all using asterisk notation:
For example, when we write import java.util.*; then we are importing
all classes from the java.util package.

Standard classes
Learning how to use standard Java classes is the first step toward mastering OOP. Some include:
o Scanner (java.util.Scanner)
o String (java.lang.String) -STRING . uses double quotes + is sequence of characters. E.g. Marco
o Math (java.lang.Math)
o System (java.lang.System)


12 | P a g e

Standard Output
Using print of System.out (an instance of the PrintStream class) is a simple way to display a result of a computation to
the user.
standard output window - the console window which displays the result to the user of the program via System.out
o EXAMPLE 1
CODE: System.out.print(I love java);
OUTPUT: I love java


We use the print method to output a value:
The print method will continue printing from the end of the currently displayed output.
o EXAMPLE 2
CODE
System.out.print(How do you do? );
System.out.print(My name is );
System.out.print(Jon Java. );
OUTPUT: How do you do? My name is Jon Java.

Displaying Numerical Values
We use the print and println methods to output numerical data to the standard output.
CODE:
int num = 15;
System.out.print(num); //print a variable
System.out.print( ); //print a string
System.out.print(10); //print a constant
RESULT: 15 10

Standard Input
Using a Scanner object is a simple way to input data from the standard input System.in, which accepts input from the
keyboard.

First we need to associate a Scanner object to System.in as follows:
import java.util.Scanner;
Scanner keyboard;
keyboard = new Scanner(System.in);

System.in is an instance of the InputStream class that provides only a facility to input 1 byte at a time with its read
method.
o Analogous to System.out for output, we have System.in for input.
o System.in accepts input from the keyboard.

Reading from Standard Input
After the Scanner object is set up, we can read data.
The following inputs the first name (String):
System.out.print (Enter your first name: );
String firstName = keyboard.nextLine();
System.out.println(Nice to meet you, + firstName + .);

RESULT:
o Enter your first name: Suresh (PRESS ENTER)
o Nice to meet you, Suresh.
CODE
CODE
13 | P a g e


Getting Numerical Input
We can use the same Scanner class to input numerical values too by using its nextInt method.
To input strings, we use the nextLine method of the Scanner class. For instance, to input an int value, we use the
nextInt method. Below is an example of inputting a persons age.
Scanner keyboard = new Scanner(System.in);
int age;
System.out.print( Enter your age: );
age = keyboard.nextInt();

Scanner Methods
Method Example Explanation
nextByte( ) byte b = scanner.nextByte( );
nextDouble( ) double d = scanner.nextDouble( ); Reads a double
nextFloat( ) float f = scanner.nextFloat( ); Reads a float
nextInt( ) int i = scanner.nextInt( ); Reads a integar
nextLong( ) long l = scanner.nextLong( );
nextShort( ) short s = scanner.nextShort( );
nextLine( ) String str = scanner.nextLine(); Reads a string


Input/Output Example
import java.util.Scanner;
Scanner keyboard;
String name;

keyboard = new Scanner(System.in);

System.out.println("Hello");
System.out.print("What is your name? ");
name = keyboard.nextLine(); // reads a String

System.out.print("Hello ");
System.out.println(name);




14 | P a g e


Template for a method

Comment:
Use a comment to describe the program

Import Statements:
Include a sequence of import statements.

Class Name:
Give a descriptive name to the main class.

Method Body:
Include sequence of instructions.

Get data by reading it from input - Scanner



The Math class
The Math class in the java.lang package
contains class methods for commonly used
mathematical functions.

As with all standard classes, they need to be
inputted.


Some Math Class Methods (INITIALLY DOUBLE)
Method Description
max(a.b) The larger of a and b.
pow(a,b) The power of a to b
sqrt(a) The square root of a
log(a) Natural logarithm (base e) of a
floor(a) The largest whole number less than or equal to a.
sin(a) The sine of a. (Note: all trigonometric functions are computed in radians)




15 | P a g e

Lecture 3 defining your own class part 1
Template for Class Definition
This is the template we use when creating
programmer-defined classes.
o Import statement
Include a sequence of import
statements to import standard
classes from JDK (if required)

o Class comment
Use a comment to describe the
program

o Class name
Give a descriptive name to the
main class.

o Fields
describe what an object has

o Methods (including constructors)
Include a sequence of instructions.

Standard classes
Learning how to use standard Java classes is the first step toward mastering OOP. Some include:
o Scanner (java.util.Scanner)
o String (java.lang.String) -STRING . uses double quotes + is sequence of characters. E.g. Marco
o Math (java.lang.Math)
o System (java.lang.System)

Class Declaration and Comment
A comment - any sequence of text that begins with the marker /* and terminates with another marker */.
o NOT VITAL BUT , helps readers of the code understand what is going on

SYNTAX FOR CLASS DECLARATION .
class Classname
{
}

Comments :
o state the purpose of the program
o explain the meaning of code,

Follow the naming conventions while naming a class and give it a meaningful name.

Data Member (field) Declaration
FIELDS - describe what an object has
The syntax is:
o <data type> <name> ;

16 | P a g e

Method Declaration
methods - what an object can
do.
void <method name> () {
<statements>
}




Constructor (special method)
constructor - a special method that is executed when a new instance of the class is created.
o intialises the fields to a valid state. (DEFINES what happens at the moment a new object is created.)
o Name of constructor = name of class
o No return type

The syntax is
<class name> ()
{
<statements>
}
For example,
Car herbie = new Car();
When the above statement is executed, it executes the
constructor method shown below
Car ()
{
position = 0;
}
THE CONSTRUCTOR initialises position (of herbie object) to
0


17 | P a g e


Accessing members of a class
To use the members (fields and methods) of another class, we need to first create an instance/object of that class in
the client class.
o For example, Service obj = new Service();

Once we have created a Service object, we can now use its fields and methods through dot notation.
CLIENT SERVICE
class Client {
Service obj = new Service();
obj.fieldOne = 10;
obj.fieldTwo = 20;
obj.methodOne();
obj.methodTwo();
}

class Service {
int fieldOne;
int fieldTwo;
void methodOne(){

}
methodTwo(){

}
}

Using your class (in another class) - CircleProgram
CODE PROGRAM OUTPUT
public class CircleProgram
{
public static void main(String [] args)
{
Circle c1 = new Circle();
c1.radius = 10.0;
c1.showRadius();
c1.showDiameter();
c1.showCircumference();
c1.showArea();
.
}
}
Radius: 10.0
Diameter: 20.0
Circumference: 62.83185307179586
Area: 314.1592653589793
-----------
Showing all
Radius: 10.0
Diameter: 20.0
Circumference: 62.83185307179586
Area: 314.1592653589793

To use the members (fields and methods) of another class, we need to first create an instance/object of that class. For
example, Circle c1 = new Circle();

After creating an instance of that class, we can now invoke its methods through dot notation objectname.methodname


Calling Methods of the Same Class
It is possible to call method of a
class from another method of the
same class.
o in this case, we simply
refer to a method without
dot notation



18 | P a g e


Self- method calls
An object may invoke a method on another object (an object of another class):
otherObject.someMethod();
herbie.drive();

An object may also invoke a method on itself: (SAME CLASS)
this.someMethod();
// OR //
someMethod();

For example, the method calls within the showEverything() method of Circle class.
Approach 1 (CALL FROM DIFF CLASS) Approach 2 (CALL FROM SAME CLASS)
void showEverything() {
System.out.println(Showing all);
this.showRadius();
this.showDiameter();
this.showCircumference();
this.showArea();
}
void showEverything() {
System.out.println(Showing all);
showRadius();
showDiameter();
showCircumference();
showArea();
}

Approach 2 is most commonly used.

Local variables
An instance variable exists for
the lifetime of the
object/instance.

A local (temporary) variable
exists for the lifetime of the
method invocation and is used
for storing temporary results

For example,
public double convert(int num) {
double result;
result = Math.sqrt(num
* num)
return result;
}
FIELD DECLARATION = VARIABLE
DECLARATION = field
Instance value given within the constructor + declared in the class and not in the method


19 | P a g e

Static fields
A static field is a property of the
class,
o there is no need to
create an instance

It can be done by:
class name.field name
class name.method
name


Static example
1. (Top EXAMPLE) Each
BankAccount object
shares the same
interest rate.

2. (BOTTOM EXAMPLE)
Each BankAccount
has a different
current balance.



Sample Instance Data Value (non-static fields)
All two BankAccount objects possess the instance data
value current balance.

The actual dollar amounts are, of course, different.

Sample Class Data Value (static fields)
Here we see that a single class data
value named minimum balance is
shared by all instances.




20 | P a g e

Object Icon with Class Data Value
When the class icon is not shown, we include the class data value in the object icon
itself.

When we do not include the class icon in a diagram, we can use this notation.

Whether the data value name is underlined or not indicates the information is a class
or an instance data value.


Constants
Make a field constant using keyword final.
Use static also if the value is identical for all objects.
class Circle
{
static final double PI = 3.141592654;
double radius;
..METHOD HeRe.
}

Constants:
o make your code more readable/maintainable.
o are conventionally UPPERCASE with an underscore (_) separating each word

Math.PI is a static/final constant of class Math


Static methods
A static method belongs to the class, rather than an object. Math.pow(), Math.sqrt() etc. are all static methods
belonging to class Math.

A java program should have a static method called main:
public static void main(String[] args) {
System.out.println(Program starting...);
Car myCar = new Car();
myCar.start();
}

This is the method (main method) that will be invoked when the user double-clicks on your program.
o The main method should create all of your objects and kickstart your program.
o You can directly invoke the method on this class by using the syntax Class name.method name

21 | P a g e

Calling a Class Method (static methods)
The maximum speed of all MobileRobot
objects is the same. Since the result is the
same for all instances,

we define getMaximumSpeed as a class
method and access it as
MobileRobot.getMaximumSpeed();

General Idea: You define an instance method
for a task that relates uniquely to individual instances (like getCurrentSpeed and getObstacleDistance(), which is
different for individual mobile robots) and a class method for a task that relates to all instances of the class collectively
(like getMaximumSpeed(), which is the same for all


Calling an Instance Method (non-static methods)
The distance from an obstacle is different for
every MobileRobot object. Since the result is
different for all instances, we define
getObstacleDistance as an instance method.

General Idea: You define an instance method for
a task that relates uniquely to individual
instances (like getCurrentSpeed() and
getObstacleDistance(), which is different for
individual mobile robots) and a class method for
a task that relates to all instances of the class collectively (like getMaximumSpeed(), which is same for all mobile robots).

Changing Any Class to a Main Class
Any class can be set to be a main class.
o All you have to do is to include the main method.
o When we create a program, we must designate one class as the programs main class.

Any class can include the main method
o the one we designate as the main class includes the main method
class Motorbike {

//definition of the class as shown before comes here

//The main method that shows a sample
//use of the Motorbike class
public static void main(String[] args) {

Motorbike bike;
bike = new Motorbike();
bike.drive();
}
...
}

22 | P a g e

The main() method
The main method >> the VITAL entry point into your program
o . It should create the first object, and direct the other parts of your program to run in the order in which you
want to run them.

The main method is the first method, which the Java Virtual Machine executes. When you execute a class , the runtime
system starts by calling the class's main()method. The main()method then calls all the other methods required to run
your application.
public static void main(String[] args)
{

}


Three Types of Comments
Type of comment example
Multiline comment
(BEGINNING + END
MARKER)
/*
This is a comment with
three lines of
text.
*/
Single line comments
(//)
// This is a comment
// This is another comment
// This is a third comment
Javadoc comments
(/** marker and end with
the */ marker)
/**
* This class provides basic clock functions. In addition
* to reading the current time and todays date, you can
* use this class for stopwatch functions.
*/


Composition
A program usually consists of several classes.
For example, if a car consists of a fuel tank and 4 wheels, we have 6 objects and 3 classes:
o Car (1 object)
o FuelTank (1)
o Wheel (4)
Because the Car object contains all of the other objects, we say that the Car is composed of a fuel tank and 4
wheels.



23 | P a g e

Composition Car example

Drive method is updated to invoke the roll method on each of the four wheels. And that is how the car moves forward
and the position of each wheel is updated by 1.

the Car constructor initialises the position of four wheels and creates a fuel tank as soon as a new object is created.

FIELDS AND METHODS TASKS
QUestion Fields Methods
You have been contracted to develop software for a university to keep track of
student information, enrolments and grades.
o name,
o DOB,
o subjects,
o grades
o changeName
o enrol
o withdraw
o graduate

You are developing a diagram drawing tool. In the first release, the user will be
able to draw diagrams consisting only of rectangles, which may be arranged
within the diagram after they have been drawn.

This program might have a Diagram class and a Rectangle class.
o x
o y
o width
o height

o resize
o move
o changeColour
o

24 | P a g e

Lecture 4 defining your own class part 2
Method Parameters
void <method name> ( <parameters> ){
<statements>
}




Adding parameters to class Car EXAMPLE


Passing arguments to parameters
25 | P a g e

Parameters and Arguments
parameter - a placeholder in the called method to hold the value of the passed argument.
argument - a value we pass to a method


Matching Arguments and Parameters
no. of arguments (must equal) no. parameters
Arguments and parameters are paired left to right
The matched pair must be assignment-compatible (e.g. you cannot pass a double argument to a int parameter, but
you can pass a int argument to a double)
int i, k, m;
i = 12; k = 10; m = 14;
demo.compute(3, 4, 5.5);
demo.compute(i, k, m); // m = 14 will be promoted to 14.0



Memory Allocation
Separate memory space is allocated for the receiving method.
Values of arguments are passed into memory allocated for
parameters.




<<<<<<< VALID CALLS
26 | P a g e

Constructor parameters
Parameters - allow the caller of that method or constructor to pass in different values to control what they want the
method or constructor to do. If there are no parameters, you are giving the caller no choices. E.g..
o Car herbie = new Car(4.0); //Initial position of the car
o Account myAccount = new Account(1000.0); //Initial bank balance
o Rectangle r = new Rectangle(10.0, 5.0); // initial height and initial width

Declaring constructor parameters


Returning methods
the user of this function has complete control over what is to be done with the returned value

<return type> <method name> ( <parameters> ){
<statements>
<return statement>



Two kinds of method
Two types of methods:
procedure - method that performs some action but returns nothing
function - method that affects nothing, but returns a value
Procedure Function
void deposit(double amount)
{
balance = balance + amount;
}
double cube(double n)
{
return Math.pow(n,3);
}

27 | P a g e


Information Hiding and Visibility Modifiers
two types of modifiers that designate the accessibility (who can have direct access) of class components:
o private - only the methods defined in the class can access directly, and client classes cannot access it.
o public - client classes can access it.
E.g..Internal details of a class are declared private and hidden from the clients. (INFORMATION
HIDING)

Anything that is considered as internal details should be declared as private and hidden from the
clients.

EXAMPLE OF ACCESABILITY
Client
class Client {
Service obj = new Service();
obj.fieldOne = 10;
obj.fieldTwo = 20;
obj.methodOne();
obj.methodTwo();
}
Service
class Service {
public int fieldOne;
private int fieldTwo;
public void methodOne(){

}
private void methodTwo(){

}
}


Fields Should Be private
Fields are the implementation details of the class, so they should be invisible to the clients. Declare them private as:
o a client can make changes directly that can affect the internal operation adversely
o it maintains the integrity of the class

Exception: Constants can (should) be declared public if they are meant to be used directly by the outside methods.
o For example:
a bank FEE
public static final double FEE = 0.50;
FIELDS = private (UNLESSS CONSTANT), CLASS = public, METHOD = public

Guideline for Visibility Modifiers
Guidelines in determining the visibility of data members and methods:
o Declare the class and instance variables (fields) private.
o Declare the class and instance methods private if they are used only by the other methods in the same class.
o Declare the class constants public if you want to make their values directly readable by the client programs. If
the class constants are used for internal purposes only, then declare them private.

Diagram Notation for Visibility
public plus symbol (+)
private minus symbol (-)
o If we include both the private and public components, then we use the plus
symbol for public and the minus symbol for private.
28 | P a g e


Modifiers
<modifier> <return type> <method name> ( <parameters> ){
<statements>
}


Accessor and Mutator methods (SETTERS AND GETTERS)
Mutator (SET METHOD) - it changes/sets the property of an object. For example,
public void setOwnerName(String name) {
ownerName = name;
}

Accessor - a method that returns a property (information) of an object. For example,
public String getOwnerName( ) {
return ownerName;
}

get and set methods are used to retrieve and modify the values of private fields.



The Definition of the Bicycle Class Using the Bicycle Class
class Bicycle {

// field
private String ownerName;

//Constructor: Initialzes the field
public 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;
}
}
class 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.");
}
}

The BicycleRegistration class above creates two Bicycle objects, assigns
the owners names to them, and displays the information.


29 | P a g e

Multiple Instances
Multiple instances of an object can be created
EACH instance of a class has their own variable.

Class Diagram for Bicycle
CLASS DIAGRAM
Class

name and data type of an argument passed to the method.

Passing Objects to a Method
In a method, for its arguments, we can pass:
int values
double values
objects (reference name OR STRING)

Passing a Student Object
In the diagram
1. Argument is passed
2. Value is assigned to the data member



Local, Parameter & Field
An identifier appearing inside a method can be a local variable, a parameter, or a field.
The rules are
o If theres a matching local variable declaration or a parameter, then the identifier refers to the local variable or
the parameter.
o Otherwise, if theres a matching data member declaration, then the identifier refers to the data member.
o Otherwise, it is an error because theres no matching declaration.
30 | P a g e


Converting objects to strings part 1
Built-in types like int are automatically converted to String when using String concatenation:
int age = 21;
System.out.println(Your age is + age);
//Prints Your age is 21 after converting 21 to a String.

Programmer-defined types (reference types) require YOU to supply your own String conversion function.
Person john = new Person(John, Smith);
System.out.println(Hello + john);
//Prints Hello John Smith after converting john to a String.

Converting objects to strings part 2
For any object you wish to be convertible to a String, you must define a toString() function.

The toString() function is automatically called when needing to convert a Person to a String:
Person john = new Person(John, Smith);
System.out.println(Hello + john);
toString() method - called automatically to convert it to a string.
toString() returns a string representation of the object.

Você também pode gostar