0% found this document useful (0 votes)
3 views41 pages

lecture08 writing classes

The document provides a comprehensive overview of writing instantiable classes in programming, focusing on class declarations, instance variables, and methods. It explains the structure of instantiable classes using examples like Circle and Coin, detailing how to define constructors, set and get instance variables, and implement methods. Additionally, it includes practical exercises to reinforce the concepts learned, such as creating a Counter class and its driver program.

Uploaded by

maureen kakoma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views41 pages

lecture08 writing classes

The document provides a comprehensive overview of writing instantiable classes in programming, focusing on class declarations, instance variables, and methods. It explains the structure of instantiable classes using examples like Circle and Coin, detailing how to define constructors, set and get instance variables, and implement methods. Additionally, it includes practical exercises to reinforce the concepts learned, such as creating a Counter class and its driver program.

Uploaded by

maureen kakoma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 41

Writing instantiable classes

Classes struggle, some classes triumph, others are


eliminated
(Mao Zedong)

31/05/2022 / Slide
1
Lecture
• objectives
We've been using predefined classes. Now we will learn to
write our own classes to define new objects

• You should be able to understand


– class declarations
– instance variables and instance methods
– driver programs

31/05/2022 / Slide
2
Two types of
• Class
Those that contain a main method
– Called Driver programs
– Not used to define objects

• Those used for defining objects


– instantiable classes
– ie we can create instances of these classes (objects) and
use methods on them

31/05/2022 / Slide
3
Objects and
• methods
Eg String class: create an object then use methods on it

• The String class is used to define String objects

String str = new String(“a meaningless string)”;


//full syntax
String str = “a meaningless string”;// optional syntax
for Strings only

• Each String object can perform pre-defined methods


that are defined in the String class
31/05/2022 / Slide
4
Instantiable
• An instantiable classes
class is a blueprint used to create
objects
– many things or objects are made from a pattern or template
• It is a generalised case that defines what data we need to
define a specific case (an object )
– eg a car
• What generalised data might we use to define cars?
• What data would define a specific car object eg my car?
– What about a circle, a student, a rectangle…

• A class also defines methods to allow us to change


31/05/2022 / Slide
objects 5
So what is an
object?
• One or many variables that define something of interest
– These are called data fields or instance variables because an
instance of them is created in memory every time an object
is created

– A student object
• name, studentNumber, course, address etc
– A rectangle object
• width, length

• On which defined methods can be used


31/05/2022 / Slide
6
Defining an instantiable
class
• Define the instance variables
– These data fields uniquely define each instance of the class
ie object

• Define a constructor
– This initialises the instance variables

• Define the methods required to manipulate and access the


instance variables

31/05/2022 / Slide
7
Circle
• class
What if we wanted to create an application to work with
circles eg. calculate area, circumference ..
• What data fields might we require for a circle?
– radius
• Define the constructor
• What methods might we need to write?
– calculateArea etc
– Method to provide a value for radius ie setRadius
– Methods to enquire as to the value of radius eg getRadius

31/05/2022 / Slide
8
Building a Circle
• A Circle class
object will have the following field:
– radius. That will hold the circle’s radius.

public class Circle


{
private double radius;
}

• public and private are access specifiers that we will deal


with next week
31/05/2022 / Slide
9
Writing the
• A constructorconstructor
is a type of method that is called when an
object is created
– It has the same name as the class
• Constructors typically initialize instance variables

public
Circle()
{
radius
= 0;
}
31/05/2022 / Slide
10
public class Circle
{
private double
radius;

public Circle()
{
radius = 0;
}

}
Setting the
• variables
So when we create a Circle object the variable radius is set
to 0
• To make the class useful we need to provide a method to
set it to other values

public void setRadius(double rad)


{
radius = rad;
}

31/05/2022 / Slide
12
Header for the setRadius
Method
Return Notice the word static
Type does not appear in the
Access Method method header designed to
specifier Name work on an instance of a
class (instance method).

public void setRadius (double rad)

Parameter variable declaration

31/05/2022 / Slide
13
public class Circle
{
private double radius;

public Circle()
{
radius = 0;
}

public void
setRadius(double rad)
{
radius = rad;
}
}
Getting the
• variables
To retrieve the value of the data field we need to provide a
method

public double getRadius()


{
return radius;
}

31/05/2022 / Slide
15
public class Circle
{
private double radius;

public Circle()
{
radius = 0;
}

public void
setRadius(double rad)
{
radius = rad;
}
public double
getRadius()
{
return radius;
}
}
Other useful
• methods
We can provide any number of useful methods that apply
to circles eg calculate area

public double calculateArea()


{
return Math.PI * Math.pow(radius, 2);
}

31/05/2022 / Slide
17
public class Circle
{
private double radius;

public Circle()
{
radius = 0;
}

public void setRadius(double


rad)
{
radius = rad;
}
public double getRadius()
{
return radius;
}
public double calculateArea()
{
return Math.PI *
Math.pow(radius, 2);
}
}
Using an instantiable
class
• An instantiable class such as Circle has no main method
• It does nothing on its own
• It sits until a driver program interacts with it
– To create an object or objects
– Then to use its methods to manipulate the objects

31/05/2022 / Slide
19
// Driver class
public class TestCircle Circle class
{
public static void main Call the constructor Circle()
(String[] args) to create an object of the
{ Circle class called circ
Circle circ = new Circle();
circ.setRadius(2.
0); Invokes the setRadius
method of the Circle
double area = class on the object
circ.calculateArea();
System.out.println (“Area of Invokes the
circle radius “ + calculateArea
circ.getRadius() + “ = “ + method on the object
} area);
} Invokes the getRadius
method of the Circle
class on the object
public class Circle
{
public class private double
TestCircle radius;
{ public
public static void main Circle()
(String [ ] args) {
{ radius
Circle circ = new Circle(); = 0;
circ.setRadius(2. }
public void setRadius(double
0); rad)
double area = {
circ.calculateArea(); radius = rad;
System.out.println (“Area of }
circle radius + public double getRadius()
circ.getRadius() + “ = “ + {
} area); return radius;
} }
public double
calculateArea()
{
} return Math.PI *
Math.pow(radius, 2);
Practic
• e
Write an instantiable class called Counter that has
– An integer instance variable called numClicks
– A constructor that sets numClicks to 0
– A method called click() that adds 1 to numClicks
– A method called getClicks() that returns numClicks

• Write a driver program called TestCounter that


– Creates a counter object
– Calls the click method 2 times
– Calls the getClicks() method and prints its value

31/05/2022 / Slide
22
public class TestCounter public class Counter
{ {
public static void main (String private int numClicks;
[] args)
{
public Counter()
//create Counter object
Counter count = new {
Counter(); numClicks = 0;
}
// call click
method twice public void click()
count.click(); {
count.click(); numClicks = numClicks + 1;
}
//get number of
clicks
public int getClicks()
int num =
count.getClicks(); {
return numClicks;
// print number }
of clicks }
System.out.print(nu
Constructo
• rs kind of method that contains
A constructor is a special
instructions to set up a newly created object
• When writing a constructor, remember that:
– it has the same name as the class
– it is syntactically similar to a method
– it has no return type, not even void
– it often sets the initial values of instance variables
– it is invoked by the keyword new

31/05/2022 / Slide
24
Another instantiable
• Class
Suppose we wanted to write a program that simulates the
flipping of a coin
• Think of a coin object as an actual coin
• We could write a Coin class to define coin objects

• What variables would we need to define a coin?


– If you are just flipping a coin, what variables would you
need ?
• What methods (or behaviour) could you apply to the coin?
31/05/2022 / Slide
25
Object
• s
We need a variable for the face of the coin (heads or tails).
– How would you represent the face of a coin?

• We need to create an object (with a constructor) and


initialise the face variable

• We need to be able to change the face variable


– How would you represent flipping a coin?

• We need to be able to enquire as to the current value


face
of thevariable 31/05/2022 / Slide
26
// Coin.java Represents a coin
with two sides

public class Coin


{
Define the variables
private int face;
public //
Coin () Constructor:
Create the object and { //
initialise the face = initialise
1;
variables public
} void flip () // Flips the
coin
Change the variables {
} face = (int)
(Math.random() * 2);
public int
getFace()
Enquire as to the value {
of the variables return face;
}
}
// Driver
program public public class Coin
class CoinFlip
{
public static
Call the constructor Coin()
void main
(String[] to create an object of the
args) Coin class called myCoin
myCoin.flip
{ ();
Coin Invokes the flip
myCoin =
int result = method of the Coin class
new Coin();
myCoin.getFace(); and applies it to the
object
// 0 = heads, 1
= tails if (result Invokes the getFace
== 0) method to access the
System.out.p
instance variable face
rintln (“It’s a
head!”);
}
else
System.out.p
// CoinFlip.java Driver // Coin.java Represents a coin
program public class with two sides
CoinFlip
public class Coin
{ {
public static void private int face;
main (String[] args) public Coin //
{ () Constructor:
Coin myCoin = new {
myCoin.flip face = 1;
Coin();
(); }
// Flips the
int result = public void coin
myCoin.getFace(); face
flip () = (int)
}
{ (Math.random() * 2);
// 0 = heads, 1
= tails if (result public int
== 0) getFace()
System.out.p {
rintln (“It’s a return
face;
} head!”); } }
} else
System.out.
println
Reus
• e
Once we have created an instantiable class it can be reused
for other applications
– This is good programming as the class has already been used
and tested
• We can write other driver programs that use the Coin class
• Eg create 2 coin objects
– Flip them both 10 times
– See how many times each comes up “heads”

31/05/2022 / Slide
30
// CountFlips.java Driver // Coin.java Represents a coin
public
program class
counts heads with two sides
CountFlips
{ public static void main public class Coin
(String[] args) {
{ private int face;
int result, myScore = 0, public //
yourScore = 0; Coin () Constructor:
Coin myCoin = new Coin(); {
Coin yourCoin
for (int i = 1; i =
<=new
10;Coin();
i face =
++) 1;
{ public
} void flip () // Flips the
myCoin.flip(); coin
result = {
myCoin.getFace(); } face = (int) (Math.random()
if (result == 0) * 2);
yourCoin.flip();
myScore = public int
result
myScore
= + 1; getFace()
yourCoin.getFace(); {
if (result == 0) return
} yourScore = face;
yourScore + 1;
System.out.print(“me “ + myScore } }
+ “you “ +
} yourScore
Instance
CountFlips.java
Variables
class Coin myCoin

int face; face 0

yourCoin

face 1

31/05/2022 / Slide
32
Exercis
• e
Change the driver program to
– Create a second counter object
– Click it once
– Get and display its value

31/05/2022 / Slide
34
public class TestCounter public class Counter
{ {
public static void main (String private int numClicks;
[] args)
{ public Counter()
Counter count = new {
Counter(); numClicks = 0;
count.click(); }
count.click();
public void click()
int num = {
count.getClicks(); numClicks = numClicks + 1;
System.out.print(num); }

Counter count2 = new public int getClicks()


Counter(); count2.click(); {
System.out.print(count2.getCli return numClicks;
cks()); }
} }
}
Setter
• s
We can change the values of variables that define an object
– When we construct it (initialisation)
– When we call a method eg flip()
– When we call a setter method

• By convention their name starts with the word “set”


– These do nothing more than accept a value or values as
parameters and update instance variables with that value

31/05/2022 / Slide
36
Adding a setter to
• Say we haveCounter
a requirement to be able to re-set out
numClicks variable
– Eg back to zero
– Or to any number
• We need to write a setter in the Counter class

public void setNumClicks(int num)


{
numClicks = num;
}

• We need to pass the parameter to it from the


program
Driver 31/05/2022 / Slide
37
public class TestCounter public class Counter
{ {
public static void main private int
(String [] args) numClicks;
{
public Counter()
Counter count = new
Counter(); count.click(); {
count.click(); numClicks =
int num = 0;
count.getClicks(); }
System.out.print(num); public void
Counter count2 = new click()
Counter(); count2.click(); {
System.out.print(count2.getCli numClicks =
cks()); numClicks +
count.setNumClicks 1;
} (0); }
} public void
setNumClicks(int
num)
{
Pseudocode for driver
• programs
In Object Oriented (OO) programming the design is very
similar to the java code

• Creating objects
create circ as new Circle()
create coin1 as new Coin()

• Using methods
area  circ.calculateArea()
circ.setRadius(num)
31/05/2022 / Slide
39
Pseudocod
• e
For instantiable classes we do not use pseudocode for
design
• We use UML – covered next week

31/05/2022 / Slide
40
Lecture
Outcomes
Today we have covered:
– writing your own instantiable classes
– creating objects from them
– we have moved into true object-oriented
programming

• Questions?

31/05/2022 / Slide
41

You might also like