Classes - Paul Bui

Download Report

Transcript Classes - Paul Bui

Introduction to
Objects & Classes
Paul Bui
Introduction



Group related information and methods
(functions) together
Design classes with attributes and behaviors in
mind
Circle Example

Attributes?

Behaviors?
Building a Class - Attributes




Name the java file the same name as the class (e.g. Circle.java)
Capitalize the class name
Put the attributes at the top of the class and make them private
It’s nice to give them default values too (e.g. radius = 0.0)
public class Circle
{
private double radius = 0.0;
...
}
Building a Class - Constructors

Constructors







Used when the object is instantiated
String str = new String();
No return type
Always has the same name as the class
Can have 0 or more parameters
Two types:“default constructor” and “specific constructors”
Example:
public Circle()
{
}
// “default constructor” has 0 parameters
Building a Class - Constructors


“specific constructor” takes parameters that
set the attributes
Example:
public Circle(double newRadius)
{
radius = newRadius;
}
Building a Class - Methods

Methods are defined and declared using the following template:
public RETURNTYPE METHODNAME(PARAMETERS)
{
//METHOD CODE
}

Example:
public double getArea()
{
return 3.1415*radius*radius;
}
Naming Methods

Naming Methods

Capitalize every word in the method name EXCEPT
for the first



Example: thisIsAGoodMethodName()
No spaces in the method name
Parts of a method
All methods except for the constructors have the
same form
RETURNTYPE METHODNAME ( PARAMETERS )

Methods – Getters & Setters

Accessors (Getters)



Used to access attributes
0 parameters
Example
public double getRadius()
{
return radius;
}
Methods – Getters & Setters

Mutators (Setters)



Used to change attributes
Most of the time has a return type of void
Example
public void setRadius(double newRadius)
{
radius = newRadius;
}
Access Levels



Controls whether or not the attribute or
method can be seen/used outside of the
class
public, private, protected
Put in front of class name, attributes, and
methods