Custom classes and objects

What are classes and objects?

Class

  • A class is a template for creating an object, including the initial values of any variablesas well as method definitions.
  • Any number of objects can be created (i.e. instantiated) from a class.
  • Classes can inherit variables and methods from a parent class.

Object

  • An object is a data structure that includes values (i.e. variables) and ways to manipulate data (i.e. methods).
  • An object is an instance of a class.

We have worked with objects throughout this course, including String, Button, TextField, Color, Font, Graphics, and many more!

For example, ifmyString is a String object, the data stored in myString will be a text string, such as “Hello World!”. It also has a variety of methods for either manipulating or determining information about the text string, such asmyString.toLowerCase() and myString.length().

How to create an object

When you want to use an object, you must…

  • Declare the object by stating its class and giving it aname. By convention, class names begin with a capital letter, and object names begin with lower case.
  • Instantiate(and initialise) the object by calling one of the constructor methods for the object with the newoperator. Classes will often have a number of different constructors that take different parameters. Constructor methods always have the same name as the class, but there may be any number of parameters.

For example, to create a myButton object from the Button class, we first declare it…

Button myButton;

And then instantiate it… (in this case we’re also initialising it with the value “Hello”)

myButton = new Button(“Hello”);

Creating your own class

To create your own class you need to consider what variables and methods you will require.

For example, to create a class to represent a circle we might want to be able to store the size and location of the circle. We might also have methods to increase the size of the circle, as well as move and display it.

It is useful to write a list of all the variables and methods that will be in the class.

Variables

int radiusStores the radius of the circle

intxCoordStores the x-coordinate

intyCoordStores the y-coordinate

Methods

circle()Constructor method to create a new circle object with default values

circle(int x, int y, int radius)Constructor method to create a new circle object with specified values

void setCoords(int x, int y)Sets new coordinates

int getX()Returns the current x-coordinate

int getY()Returns the current y-coordinate

intsetRadius()Sets the size of the circle

intgetRadius()Returns the radius

intgetDiameter()Returns the diameter

voidincreaseSize(int size)Increases the radius by the given size

voiddrawCircle(Graphics g)Draws the circle in the applet window

Here is a partial implementation of the Circle class…

class Circle

{

privateintradius;

privateintxCoord, yCoord;

publicCircle(int initialX, int initialY, int initialRadius)

{

radius = initialRadius;

xCoord = initialX;

yCoord = initialY;

publicvoidincreaseSize(int size)

{

radius = radius + size;

}

publicintgetRadius()

{

return radius;

}

publicintgetDiameter()

{

return radius*2;

}

publicvoid drawCircle(Graphics g)

{

g.drawOval(xCoord, yCoord, radius*2, radius*2);

}

}

The following program demonstrates how to use the Circle class to create, modify, and draw Circle objects.

import java.awt.*;

import java.applet.*;

publicclassCircleDemoextends Applet

{

Circle c1, c2;

publicvoid init()

{

c1 = new Circle(100,100,50);

c2 = new Circle(200,200,30);

}

publicvoid paint(Graphics g)

{

g.drawString("Showing circle outputs", 20, 20);

c1.drawCircle(g);

c2.drawCircle(g);

c1.increaseSize(25);

c1.drawCircle(g);

}

}

Principles of object-oriented programming (OOP)

Encapsulation

  • Encapsulation means that related data and methods are grouped together in an object in such a way that a programmer can use the object without having to worry about its details, or running the risk of destroying it.
  • Data and methods that the user does not need to worry about are “hidden” (declared as private).
  • “Public” data and methods are available in a way that is simple and safe.
  • Objects should not be able to change (or even look directly at) the instance variables of other objects. Instead they should use the object’s methods.

Inheritance

  • A “parent” class can be extended to “child” classes that include more data and methods. In this way the programmer can set up a hierarchy of classes, without necessarily needing to know the internal details of parent classes. For example, when you create an applet class, you are extending the Java class Applet, and you do not need to know any details of how the Applet class was originally set up.

Polymorphism

  • Polymorphism is the ability of an object to take on many forms. For example, if similar classes have the same method name, whenever that method is called for a particular object Java “knows” to get the version of the method defined in the appropriate class.
    For example s = Integer.toString(n) (where s is a String and n is an integer) or
    s = Double.toString(d) (where s is a String and d is an double).

Class structure

Class definitions must have the following structure…

public class <name of Class>

{

variable declarations

constructor method(s)

method declarations>

}

Variable declarations

  • Variables provide a way of keeping track of the state of an object.
  • The variables declared in a class are generally defined as private and can’tbe used outside the class.

For example…

class Car
{
private int maxSpeed;
private int weight;
private String make;
}

Every car created within the program must have a maxSpeed, weight and make.

Constructor method(s)

  • Constructormethods are used to instantiate (create) and initialise an object.
  • They never return a value, so they don’t specify a return type (not even void).
  • Constructor methods must have the same name as the class.
  • It is recommended to have a constructor method that sets the instance variables to default values.
  • Multiple constructor methods can be defined, but they still must all have the same name as the class, and differ in the number and type of the parameters.

For example…

Car()
{
maxSpeed = 0;
weight = 0;
make= null;
}

public Car(int carMaxSpeed, int carWeight, String carMake)

{

maxSpeed = carMaxSpeed;

weight = carWeight;

make = carMake;

}

To create a new Car object in another class, we could use either version of the constructor method. For example…

fredsCar = new Car(160, 1000, “Honda”);

eddiesCar = new Car();

Method declarations

  • The method declarations are the methods that can be used on objects of this class.
  • They are blocks of code that can be called from outside the object and can take arguments and optionally return a value.

For example…

public int getMaxSpeed()

{

return maxSpeed;

}

The access modifiers (public, private, protected) allow you to say how visible the method will be to other classes. If it is public, any class can access the method.

An example: Fred’s Car and Mary’s Car

Here is thedefinition of a class to represent an object of type Car.

import java.awt.*;

import java.applet.*;

public class Car extends Applet

{

private int maxSpeed;
private int weight;
private String make;

public Car()

{

maxSpeed = 0;

weight = 0;

make = null;

}

public Car(int carMaxSpeed, int carWeight, String carMake)

{

maxSpeed = carMaxSpeed;

weight = carWeight;

make = carMake;

}

public void setMaxSpeed(int carMaxSpeed)

{

maxSpeed = carMaxSpeed;

}

public int getSpeed()
{
return maxSpeed;

}

public void setWeight(int carWeight)

{

weight = carWeight;

}

public int getWeight()
{
return weight;

}

public void setMake(String carMake)

{

make = carMake;

}

public String getMake()

{

returnmake;

}

}

This applet demonstrates how the Car class can be used to create two different car objects from the same class, and display their values.

public class CarSample extends Applet

{

Car fredsCar, marysCar;

int speed, weight;

String make;

public void init()

{

setBackground(Color.white;

fredsCar = new Car( );

fredsCar.maxSpeed(500);

fredsCar.setweight(1000);

fredsCar.setMake(“Honda”);

marysCar = new Car(600, 900, “Porsche”)

public void paint(Graphics g)

{

speed = fredsCar.getSpeed();

weight = fredsCar.getWeight();

make = fredsCar.getMake();

g.drawString(“Fred’s car speed “ + speed + “weight” + weight + “ and make”

+ make, 10, 20);

g.drawString(“Mary’s car speed “ + marysCar.getSpeed + “ weight ” +

marysCar.getWeight + “ and make ” + marysCar.getMake, 10, 40);

}

}

A summary of the structure of Car class ...

Class Car

Variables

intmaxSpeed;
int weight;
String make;

Methods

Car()
Car(int carMaxSpeed, int carWeight, String carMake)
voidsetMaxSpeed(int carMaxSpeed)
intgetSpeed()
voidsetWeight(int carWeight)
intgetWeight()
voidsetMake(String carMake)
String getMake()

Inheritance added to the Car class

Inheritance enables new classes to be built on existing classes but with extra variables and/or methods.

For example, we could define a VintageCar class that has all the features of the Car class, but adds a variable to record the age of the car, as well as methods for setting and getting the age.

class VintageCar extends Car( )

{

int age;

public void setAge(int years)

{

age = years;

}

public void getAge( )

{

return age;

}

}

We could make use of this new child class in our applet like this:

VintageCar = tModel;

tModel = new VintageCar();

tModel.maxSpeed(500);

tModel.setweight(1000);

tModel.setMake(“Ford”);

tModel.setAge(70);

A summary of the structure of the VintageCarclass ….

Class VintageCar extends Car

Variables

intage

Methods

VintageCar()
voidsetAge()
intgetAge()

Claremont College 2015, based on ????Page 1 of 8