You are on page 1of 27

An object has behaviors

• In old style programming, you had:


• data, which was completely passive
• functions, which could manipulate any data

• An object contains both data and methods that


manipulate that data
• An object is active, not passive; it does things

• An object is responsible for its own data

• But: it can expose that data to other objects


An object has state
• An object contains both data and methods that
manipulate that data
• The data represent the state of the object

• Data can also describe the relationships

between this object and other objects


• Example: A CheckingAccount might have
• A balance (the internal state of the account)

• An owner (some object representing a person)


Example: A “Rabbit” object
• You could (in a game, for example)
create an object representing a rabbit
• It would have data:
• How hungry it is

• How frightened it is

• Where it is

• And methods:
• eat, hide, run, dig
Class
• A class consists of:
• a set of attributes (the data).
• a set of methods which can access or change

those attributes.
O Oblong belong
class Oblong {
length
The Attributes height
height
calculateArea
The Constructor calculatePerimeter

The methods
}
Classes describe objects
• Every object belongs to (is an instance of) a class
• An object may have fields, or variables
• The class describes those fields
• An object may have methods
• The class describes those methods
Example of a class
class Employee {
// fields
String name;
double salary;
// a method
void pay () {
System.out.println("Pay to the order of " +
name + " $" + salary);
}
}
Approximate Terminology
• instance = object
• field = instance variable
• method = function
• sending a message to an object = calling a
function
• These are all approximately true
Instance and Class Variables
• Usually a class describes fields (variables) and
methods for its objects (instances)
• These are called instance variables and instance

methods
• A class can have its own fields and methods
• These are called class variables and class

methods
• There is exactly one copy of a class variable, not
one per object
• Use the special keyword static to say that a field or
method belongs to the class instead of to objects
Static/Instance Variables
• A static field (a.k.a. class field or class variable) is
shared by all objects of the class.
• A static field can hold a constant shared by all
objects of the class:
public class RollingDie Reserved
{ words:
private static final double slowDown = 0.97; static
private static final double speedFactor = 0.04; final
} ...

• A non-static field (a.k.a. instance field or instance


variable) belongs to an individual object.
Access Modifiers
• Java provides four levels of access:
• public: available everywhere
• protected: available within the package (in the
same subdirectory) and to all subclasses
• [default]: available within the package
• private: only available within the class itself
Access modifiers: an example
class Person { class RecordCompanyPayroll {
public String firstname; public static void main(String [ ]
public String surname; args) {
} Person p = new Person( );
p.firstname = “Britney”;
p.surname = “Spears”;
public instance variables String fullname = p.firstname + “ ”
+
p.surname;
local variable
System.out.println(fullname);
}
}

The Payroll class has access to the variables of the


Person class
Access modifiers: an example
class Person { class RecordCompanyPayroll {
private String firstname; public static void main(String [ ] args) {
private String surname; Person p = new Person( );
} p.firstname = “Britney”;
p.surname = “Spears”;
System.out.println(p.firstname +
private instance variables “ ” + p.surname);
}
}

Will not compile: “Variable firstname/surname in


class Person not accessible from class Payroll”
(error message given by javac)
Access modifiers: an example
class Person {
class RecordCompanyPayroll {
private String firstname;
public static void main(String [ ] args)
private String surname;
{
Person p = new Person( );
public void setFirstname(String
p.setFirstname(“Britney”);
fn) {
p.setSurname(“Spears”);
firstname = fn;
System.out.println(p.getFirstname( )
}
+
public void setSurname(String
“ ” + p.getSurname( ));
sn) {
}
surname = sn;
}
}
public String getFirstname( ) { Information hiding
return firstname;
} Prevent direct access to
public String getSurname( ) { information (i.e. instance variables)
return surname; and provide appropriate methods
}
}
Constructors
• A constructor is like a method for creating objects
of the class.
• A constructor often initializes an object’s fields.
• Constructors do not have a return type (not even
void) and they do not return a value.
• All constructors in a class have the same name —
the name of the class.
• Constructors may take arguments.
Constructors Overloading
• If a class has more than one constructor, they are
“overloaded” and must have different numbers
and/or types of arguments.
• Programmers often provide a “no-args”
constructor that takes no arguments.
• If a programmer does not define any
constructors, Java provides one default no-
args constructor, which allocates memory and
sets fields to the default values.
The user-defined constructor
public Oblong(double lengthIn, double heightIn)
{
length = lengthIn;
height = heightIn;
}
• we are defining it so that when a new Oblong object
is created (with the keyword new) then not only do
we get some space reserved in memory, but we also
two assignment statements are executed.
• the variables in the brackets are called the formal
parameters of the method, and they are the
variables that receive the values that we send into the
method when we call it.
Calling the Constructor
myOblong = new Oblong(oblongLength,
oblongHeight);
• In the calling method, the variables oblongLength
and oblongHeight are referred to as the actual
parameters (also known as arguments) of the
calling method.
• their values are copied to the formal parameters
lengthIn and heightIn in that order:
myOblong = new Oblong(10.0, 20.0);
Methods
public [or private] returnType
methodName (type1 name1, ..., typeN nameN)
{
...
} Body Header

• To define a method:
• decide between public and private (usually public)
• give it a name
• specify the types of arguments (formal parameters)
and give them names
• specify the method’s return type or chose void
• write the method’s code
Types of Methods
• Class Methods
• invoked using class name
• public static int getCount( )

• answer = Math.sqrt(16.0);

• Instance Methods
• invoked by an object

• generally public
Static/Class Methods
• Static methods can access and manipulate a
class’s static fields.
• Static methods cannot access non-static fields or
call non-static methods of the class.
• Static methods are called using “dot notation”:
ClassName.StaticMethodName(...)
double x = Math.random();
double y = Math.sqrt (x);
System.exit();
Static/Class Methods
class Helper

public static int triple(int num) {


int result;
result = num * 3;
return result;
}

• Because it is static, the method can be invoked as:


value = Helper.triple(5);
22
Instance Methods
• Non-static methods are also called instance
methods.
• An instance method is called for a particular object
using “dot notation”:
ObjectName.InstanceMethodName(...);
• Instance methods can access ALL fields
and call ALL methods of their class —
both class and instance fields and
methods.
Static (Class) vs. Non-Static (Instance)
public class MyClass
{ 
public static final int statConst; public int instMethod(...)
private static int statVar; {
statVar = statConst;
private int instVar; inst Var = statConst;
... All OK instVar = statMethod(...);
... statVar = instMethod2(...);
...
public static int statMethod(...) }
{
statVar = statConst; public int instMethod2(...)
{
statMethod2(...); OK
...
instVar = ...; }
instMethod(...); Error! ...
} Continued  }
Static vs. Non-Static
• Note: main is static and therefore cannot access
non-static fields or call non-static methods of its
class:
public class Hello Error:
{ non-static
private String message = "Hello,World"; variable
public static void main (String[ ] args) message
{ is used in
System.out.println (message); static
} context
} (main)
Method Overloading
• In Java, it is possible for two or more methods to
have the same name, as long as they have
different number or types of parameters. This is
called method overloading.
• When an overloaded method is invoked, the
compiler compares the number and types of
parameters to find the method that best matches
the available signatures.
• The return type are not counted for overloading
of methods.
public void move (int x, int y) { ... }
public void move (double x, double y) { ... }
public void move (Point p) { ... }
Method Overloading
public class Example {
public void show() {
// does something;
}
public double show (double i) {
// does something else
return i/2.0;
}
}

You might also like