Creating Your Own Classes

Report
Creating
Custom
Classes
CSCI 142
What is a Class?
• A template or blueprint for creating objects
• A “cookie cutter”
• Classes are defined by:
•
•
•
•
The Standard API
The Graphics API
Other APIs
You!
• Classes contain:
• Data
• Constructors
• Methods
A Class Has Data
• Data represents the properties of an object
• Sometimes called state
• Examples:
•
•
•
•
A GPen has x, y, color, and visibility
A Dog has gender, breed, and weight
A Car has…?
A Book has…?
Class Data
gender: M
breed: unknown
weight: 20.5
gender: F
breed: beagle
weight: 15.0
gender: M
breed: schnauzer
weight: 8.9
Representing Class Data
• Data is represented as instance variables
• Instance variables have class scope
• Instance variables are private
public class Dog
{
private char gender;
private String breed;
private double weight;
}
Encapsulation: Class
data is not visible
outside its class.
class header
instance variables
are private and
have class scope
A Class has Constructors
• A constructor is used to instantiate the class, e.g. create a
cookie from the cookie cutter
• Constructors initialize instance variables
• Defining a constructor
• A constructor is always public
• The constructor always has exactly the same name as the class
• A constructor has no return type, not even void
public Dog()
{
…
}
A Class has Constructors
• Every class has at least one constructor
• If you don’t create one, Java will create one for you!
• Default constructors don’t have any parameters
• Initialize instance variables to default values
• Parameterized constructors accept one or more parameters
• Initialize instance variables to values passed to the constructor
public class Dog
{
private char gender;
private String breed;
private double weight;
public Dog()
{
gender = ‘N’;
breed = “unknown”;
weight = 0.0;
}
Writing
Constructors
default
constructor
(no parameters)
public Dog(char dogGender, String dogBreed, double dogWeight)
{
gender = dogGender;
breed = dogBreed;
weight = dogWeight;
}
}
parameterized
constructor
Using a Custom Class
• One class (a “client”) can use another class
• Breakout uses GRect
• No import statement needed if the classes are in the same
folder
• The client uses the constructor to instantiate the class
• The client invokes methods on the object
Using Your Class
This is called a driver
class, because it can
be executed.
import acm.program.ConsoleProgram;
public class PetStore extends ConsoleProgram
{
public void run()
default
{
constructor
Dog d1 = new Dog();
Dog d2 = new Dog(‘M’, “boxer”, 10.2);
}
}
parameterized
constructor
A Class has Methods
• Methods represent the functionality or behavior of the class
• Examples:
• GPen has setColor(), getX(), and move()
• Dog has setName(), getBreed(), and bark()
• Car has …?
• Methods can be public or private
• Public methods are visible in the API and available to other
classes
• Public methods are used to interact with private data
• Private methods are only available within their own class –
sometimes called utility methods
Common Class Methods
• toString
• Returns a String representation of an object
• Setters
• Used to change the value of a private instance variable
• Getters
• Used to return the value of a private instance variable
All of these are optional.
The toString() Method
• Inherited from Object class
• Should be overridden
• Otherwise it prints the
object’s memory address!
• Returns a String
representation of an object
• Is called automatically when
an object is passed to the
println method
• println(bucket);
is equivalent to
println(bucket.toString());
Writing
toString()
public class Dog
{
private char gender;
private String breed;
private double weight;
…
public String toString()
{
String out = “”;
out += gender + “ ”;
out += breed + “ ”;
out += weight;
return out;
}
Using
toString()
public class PetStore extends
ConsoleProgram
{
public void run()
{
Dog d1 = new Dog();
Dog d2 = new
Dog(‘M’, “boxer”, 10.2);
println(d1.toString());
println(d2);
}
Two ways to print
}
an object.
Set Methods
Dog
• Return void
• Accept one parameter,
the same type as what they
are setting
• May be used to validate
data
• Also called mutators,
because they change the
value of instance variables
- char gender
- String breed
- double weight
return
type
parameter
+ Dog()
+ void setGender(char dogGender)
+ void setBreed(String dogBreed)
What would the set
method for weight
look like?
Get Methods
Dog
• Return whatever data type
they are getting
• No parameters
return
• Also called accessors,
type
because they access
instance variables
- char gender
- String breed
- double weight
parameter
+ Dog()
+ char getGender()
+ String getBreed()
What would the get
method for weight
look like?
Writing Set and Get Methods
public class Dog
{
private char gender;
private String breed;
private double weight;
public char getGender()
{
return gender;
}
get methods return a value
and accept no parameters
set methods return void
and accept a parameter
public void setGender(char dogGender)
{
gender = dogGender;
Write get and set methods
}
for breed and weight
…
}
The “this” Reference
public class Dog
{
private char gender;
private String breed;
private double weight;
The “this” reference refers
to the object that invoked
the method.
…
public void setGender(char gender)
{
this.gender = gender;
}
public void setBreed(String breed)
{
this.breed = breed;
}
Assigns the parameter
gender to the instance
variable gender.
Using Set Methods for
Data Validation
public class Dog
{
private char gender;
private String breed;
private double weight;
…
public void setWeight(double weight)
{
if(weight > 0.0)
{
this.weight = weight;
}
}
How would you modify
}
setGender to make sure that
gender is N, M, or F?
Using Setters and Getters
public class PetStore extends ConsoleProgram
{
public void run()
{
Dog d1 = new Dog();
Dog d2 = new Dog(‘M’, “boxer”, 10.2);
d1.setGender(‘F’);
d1.setBreed(“poodle”);
d1.setWeight(-5.4);
}
of each dog.
setters
println(“Weight of d1: ” + d1.getWeight());
println(“Gender of d2: ” + d2.getGender());
}
Print the breed
getters
Other methods
• A Dog might bark, sit, fetch, etc.
public class Dog
{
…
public String bark()
{
if(breed.equals(“poodle”))
{
return “Yip!”;
}
else
{
return “Woof!”;
}
}
}
public class PetStore extends ConsoleProgram
{
public void run()
{
Dog d1 = new Dog();
d1.setBreed(“poodle”);
println(d1.bark());
Dog d2 = new Dog(‘M’, “boxer”, 10.2);
println(d2.bark());
}
}
Public vs. Private
Class2
Class1
Class Data
public var
private var
Public Method
Private Method
Public vs. Private
Class1
public class Class1
{
public int publicVar;
private int privateVar;
public void m1()
{
println(“hello”);
m2();
}
Class2
public class Class2 extends ConsoleProgram
{
public void run()
{
Class1 c = new Class1();
c.publicVar = 5;
c.privateVar = 10;
c.m1();
c.m2();
private void m2()
{
println(“hi”);
}
}
}
}
Putting it All Together
UML Static
Class Diagram
Dog
- char gender
Data
- String breed
- double weight
+ Dog()
Constructors
+ Dog(char gender, String breed, double weight)
+ void setGender(char gender)
Class
Members
+ char getGender()
+ void setBreed(String breed)
Methods
+ String getBreed()
+ void setWeight(double weight)
+ double getWeight()
+ String toString()
The Anatomy of a Class
Class
Data
Instance
Variables
Static
Constants
Methods
Private
Constructors
Default
Parameterized
Public
Setters
Getters
toString

similar documents