Professional Documents
Culture Documents
• 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
} ...
• 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