0% found this document useful (0 votes)
10 views44 pages

Understanding Classes and Objects in Java

Chapter 5

Uploaded by

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

Understanding Classes and Objects in Java

Chapter 5

Uploaded by

layaungphyo079
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CLASS & OBJECT

Class

public class MyHelloWorld{


public static void main(String[] args){
Scanner sc = new Scanner([Link]);
int x = [Link]();
[Link](x);
}
}
Class Types
• Driver class – often just the class that contains a main
• Boundary class (service class or utility class) – a class
that collects the related static methods and no data such
as the Math class.
• Entity class – a class that represent any object in the
real world such as Student, Employee, BankAccount,
Circle, there are both data and methods.
Class & Object
• A class is a template or blueprint for creating an object.
• A class defines what types of data are included in the
object and specifies the operations the object performs.
• Object is created from a class.
• Creating an object from a class is known as instantiating
an object.
Class & Object
Class Object
Class & Object
Objects
obj1
Class
data
class

attributes obj2

data
methods
obj3

data
Class

BankAccount somsriAccount;
somsriAccount = new BankAccount();

Objects/Instances

BankAccount somchaiAccount= new BankAccount();


public class BankAccount{
private int accId; Attributes
private double balance;

public void setAccId(int id){


accId=id;
}
public void setBalance(double bal){
balance=bal;
}
public int getAccId(){
return accId;
}
public double getBalance(){
return balance;
}
public void deposit(double amount){ Methods
balance=balance+amount;
}
public void withdraw(double amount){
if(amount<=balance)
balance=balance-amount;
else
[Link](“cannot withdraw please check your balance”);
}
public String toString(){
return "Account Id = "+ accId +"\nBalance = " +balance;
}

}
Creating Objects
• A variable holds either a primitive type or a reference to an
object
• A class name can be used as a type to declare an object
reference variable
BankAccount somsakAccount ;

• No object is created with this declaration

• An object reference variable holds the address of an object

• The object itself must be created separately


Creating Objects
• Generally, we use the new operator to create an object

somsakAccount = new BankAccount();

Creating an object is called instantiation

An object is an instance of a particular class


Creating Object
• Object Declaration 1
BankAccount somsakAccount;
1
somsakAccount

• Object construction (Instantiation)


3 2
somsakAccount =new BankAccount();
2 3
accId=0 accId=0
balance=0.0 somsakAccount balance=0.0

setAccId(int id) setAccId(int id)


getAccId() getAccId()
setBalance(double bal) setBalance(double bal)
getBalance() getBalance()
deposite(double amt) deposite(double amt)
withdraw(double amt) withdraw(double amt)
toString() toString()
Driver Programs
• A driver program drives the use of other, more interesting
parts of a program
• Driver programs are often used to test other parts of the
software
[Link]
public class TestBankAccount{
public static void main(String args[]){
BankAccount somchaiAccount=new BankAccount();
[Link](123456);
[Link](500);
[Link](100);
[Link]([Link]());
[Link](somchaiAccount);
}
}
Primitive and Object Variables
• A primitive variable
• boolean, char, byte short, int, long, float and double
E.g. int num=59; num
59
• A reference variable
E.g. BankAccount somsakAccount= new BankAccount();

Address: F029
accId=123456
somsakAccount balance=500.00
F029 setAccId(int id)
getAccId()
setBalance(double bal)
getBalance()
deposite(double amt)
withdraw(double amt)
toString()
Primitive & Reference Variables
• Each variable has its own L-value and R-value
1. The L-value is its address
2. The R-value is its value
Primitive Assignment
1. int num1, int num2;
2. num1=59;
3. num2=num1; (R-value Copy)
1. 2. 3.
B001 num1 B001 num1 B001 num1
B002 0 L-value: B001 B002 59 L-value: B001 B002 59 L-value: B001
B003 R-value: 0 B003 R-value: 59 B003 R-value: 59
B004 B004 B004
| | |
| | |
F02A num2 num2
F02A F02A
F02B 0 L-value: F02A
F02B F02B 59 L-value: F02A
R-value: 0 R-value: 59
F02C F02C F02C
F02D F02D F02D
F02E F02E F02E
Reference Assignment
1. String msg1=new String(“str1”);
2. String msg2=new String(“str2”);
3. String msg2=msg1; (R-value Copy)
1. 2. 3.

B001 F0 msg1 FA01 FF msg2 FA01 F0


B002 FA02 0A L-value: FA01 FA02 2A
2A L-value: B001
R-value: FF0A FA03
B003 R-value: F02A FA03
B004 FA04 FA04
| | | msg1
| | | L-value: B001
FF0A R-value: F02A
F02A FF0A
F02B FF0B FF0B
F02C FF0C FF0C msg2
F02D FF0D FF0D
L-value: FA01
F02E FF0E FF0E R-value:F02A
Object without Reference
• We can use an object only if we have a reference to it
• The object without reference is called “Garbage”

3.

FA01 F0 msg1
FA02 2A L-value: B001
FA03 R-value: F02A
FA04
|
|
FF0A msg2
FF0B L-value: FA01
R-value:F02A
FF0C
FF0D
FF0E
Garbage
METHOD
public class BankAccount{
private int accId; Attributes
private double balance;

public void setAccId(int id){


accId=id;
}
public void setBalance(double bal){
balance=bal;
}
public int getAccId(){
return accId;
}
public double getBalance(){
return balance;
}
public void deposit(double amount){ Methods
balance=balance+amount;
}
public void withdraw(double amount){
if(amount<=balance)
balance=balance-amount;
else
[Link](“cannot withdraw please check your balance”);
}
public String toString(){
return "Account Id = "+ accId +"\nBalance = " +balance;
}

}
Method Header
• A method declaration begins with a method
header
public char calc (int num1, int num2, String message)

method
parameter list
name

return The parameter list specifies the type


type and name of each parameter

visibility The name of a parameter in the method


modifier declaration is called a formal parameter
Method Body
• The method header is followed by the method body

public char calc (int num1, int num2, String message)


{
int sum = num1 + num2;
char result = [Link] (sum);

return result; sum and result


} are local data

They are created


The return expression each time the
must be consistent with method is called, and
the return type are destroyed when
it finishes executing
Local Data
• As we’ve seen, local variables can be declared inside a
method
• The formal parameters of a method create automatic local
variables when the method is invoked
• When the method finishes, all local variables are
destroyed (including the formal parameters)
• Keep in mind that instance variables, declared at the
class level, exists as long as the object exists
The return Statement
• The return type of a method indicates the type of value
that the method sends back to the calling location
• A method that does not return a value has a void return
type
• A return statement specifies the value that will be returned
return expression;
• Its expression must conform to the return type
Parameters
• When a method is called, the actual parameters in the
invocation are copied into the formal parameters in the
method header
ch = [Link] (25, count, "Hello");

char calc (int num1, int num2, String message)


{
int sum = num1 + num2;
char result = [Link] (sum);

return result;
}
Method patterns (1):
method
return value
name

double
pow double
double

static double pow (double a, double b)


Returns the value of the first argument raised to the second argument.
Method patterns (2):
method return value
name

nextInt int

public int nextInt()


Scans the next token of the input as an int.
public static double random()

Returns a double value with a positive sign, greater than or equal to


0.0 and less than 1.0. Returned values are chosen pseudorandomly
with (approximately) uniform distribution from that range.
Method patterns (3):
method
name

println
String

public void println (String x)

Prints a String and then terminate the line. This method


behaves as though it invokes print(String) and then
println().
Method patterns (4):
method
name

gc

public static void gc ()


Runs the garbage collector.
Method Control Flow
• When a method is invoked, the flow of control jumps to the
method and executes its code

• When complete, the flow returns to the place where the


method was called and continues

• The invocation may or may not return a value, depending on


how the method is defined
Method Control Flow
• If the called method is in the same class, only the method
name is needed

compute myMethod

myMethod();
Method Control Flow
• The called method is often part of another class or object

main doIt helpMe

[Link](); helpMe();
Visibility Modifier
Modifier Explanation
(default) A class, constructor, method, or data field is visible in
this package
public A class, constructor, methods, or data field is visible to
all the programs in any package
private A constructor, method, or data fields is only visible in
this class
protected A constructor, method, or data field is visible in this
package and in subclasses of this class in any package
Visibility Modifiers

public private

Violate Enforce
Variables encapsulation encapsulation

Support other
Provide services methods in the
Methods to clients class
Static Class Members
• Recall that a static method is one that can be invoked
through its class name
• For example, the methods of the Math class are static:

result = [Link](25)

• Variables can be static as well

• Determining if a method or variable should be static is an


important design decision
The static Modifier
• We declare static methods and variables using the static
modifier
• It associates the method or variable with the class rather
than with an object of that class
• Static methods are sometimes called class methods and
static variables are sometimes called class variables
• Let's carefully consider the implications of each
Static Variables
• Normally, each object has its own data space, but if a
variable is declared as static, only one copy of the variable
exists

private static float price;

• Memory space for a static variable is created when the


class is first referenced
• All objects instantiated from the class share its static
variables
• Changing the value of a static variable in one object
changes it for all others
Static Methods
• The methods that a class definition has are called static
methods.
• A static method is a characteristic of a class, not of the
objects it has created.
• Important:

• A program can execute a static method without first creating


an object!
• All other methods (those that are not static) must be part of an
object. An object must exist before they can be executed.
Static Methods
class Helper{
public static int cube (int num){
return num * num * num;
}
}

Because it is declared as static, the method


can be invoked as
value = [Link](5);
Static Class Members
• The order of the modifiers can be interchanged, but by
convention visibility modifiers come first
• Recall that the main method is static – it is invoked by the
Java interpreter without creating an object
• Static methods cannot reference instance variables
because instance variables don't exist until an object exists
• However, a static method can reference static variables
or local variables
Student Class Example
Class: Student
int id
String name
static int numOfStudent

getId():int
setId(int id):void
getName:String
setName(String s):void
toString():String
static int getNumStudent()
Class Variables Vs. Instance Variables
Instance student1

id=52100701
name=“A”

Class: Student
student2 static int numOfStudent

id=52100702 getId():int
name=“B” setId(int id):void
getName:String
setName(String s):void
student3 toString():String
static int getNumStudent()
id=52100703
name=“C”
Class Methods Vs. Non-Static Methods
Instance student1

id=52100701
name=“A”
Class: Student

student2 static int numOfStudent


static method
id=52100702 static int getNumStudent()
name=“B”
getId():int
setId(int id):void non-static
method
student3 getName:String
setName(String s):void
id=52100703 toString():String
name=“C”
Static Class Members
• Static methods and static variables often work together

• The following example keeps track of how many Slogan


objects have been created using a static variable, and
makes that information available using a static method

You might also like