Objects, Classes and Methods
Objects and Classes
An object:
An object is a run-time representation of a “thing”.
Is stamped out of the class mold
Is a single instance of a class
Retains the structure and behavior of a class
A class:
Models an abstraction of objects
Defines the attributes and behaviors of objects
Is the blueprint that defines an object
Objects and Classes
Classes reflect concepts, objects reflect instances that
embody those concepts.
object class girl
Jodie Daria Jane Brittany
Objects and Classes
An Object's Attribute Maintain Its State
Objects have knowledge about their current state
Each piece of knowledge is called an attribute
The values of attributes dictates the objects' state
Object: My blue pen Attribute: Ink amount
Object: Acme Bank ATM Attribute: Cash available
Objects and Classes
Objects Have Behavior
An object exists to provide (functionality) to the system
Each distinct behavior is called an operation
Object: My blue pen Operation: Write
Object: Acme Bank ATM Operation: Withdraw
Objects and Classes
Defining Object Composition
Objects can be composed of other objects
Objects can be part of other objects
This relationship between objects is known as aggregation
A PC may be an object
A PC may have a keyboard, mouse, and network card, all of
which may be objects.
A PC may have a CD drive, which may be an object
Objects and Classes cont’d
A class captures the common properties of the objects
instantiated from it
A class characterizes the common behavior of all the objects
that are its instances
Objects and Classes cont’d
Class BankAccount Operations
Balance MakeDesposit
InterestYTD Transfer
Owner WithDraw
Account_number GetBalance
Balance 500 Balance 10,000
InterestYTD InterestYTD
Owner Owner
Account_number Account_number
Objects as instances of Classes
The world conceptually consists of objects
Many objects can be said to be of the same type or class
◼ My bank account, your bank account, Bill Gates’ bank
account …
We call the object type a class
Instantiation
An Object is instantiated from a Class
BankAccount myAccount;
myAccount = new BankAccount();
Methods
Two (2) kinds of Methods
◼ Those that return a single value
◼ Those that perform some action
Methods - Examples
public String getFname()
{
return fname;
}
public void writeOutput()
{
System.out.println(“Name: = “ + name);
}
Defining Java Methods
Always define within a class
Specify:
◼ Access modifier
◼ Static keyword
◼ Arguments
◼ Return type
[access-modifiers] [static] “return-type”
“method-name” ([arguments]) {
“java code block” … }
return
static keyword (w/ methods)
class Math {
public static double sqrt(double x) {
// calculate
return result;
}
}
class MyApp {
public static void main(String [] s ) {
double dd;
dd = Math.sqrt(7.11);
}
}
14
Assignment:
Create a class Person with at least 10
properties. Provide corresponding
accessors (getters) and mutators
(setters) for each of the methods.
Files: Person.java and TestPerson.java