08IntroClasses
08IntroClasses
Programming Techniques
Introduction to Classes and Objects
Agenda & Reading
Topics:
Introduction
Built-In Classes in Java
Creating Classes
Class Variables & Methods
Reading
Java how to program Late objects version (D & D)
Chapter 7
The Java Tutorial
Classes:
http://docs.oracle.com/javase/tutorial/java/javaOO/classes.html
Objects
http://docs.oracle.com/javase/tutorial/java/javaOO/objects.html
2 02
1.Introduction
Class
A set of objects with shared behaviour and individual state
Individual state:
Data is stored with each instance, as an instance variable.
Shared behaviour:
Code is stored with the class object, as a method.
Shared state may be stored with the class object, as a class variable.
Object
Objects are created from classes at runtime by instantiation
usually with the “new” operator.
There may be zero, one, or many objects (instances) of a class.
Instantiated objects are garbage-collected if no other
user-defined object can reference them.
Each instance, or object, has its
own property values that may differ
from those of other objects of the
same kind
3 02
1.Introduction
What is an Object?
A building block for OO development
Like objects in the world around us
Objects have state and behaviour
Examples:
Dog
State/field/attribute: name, colour, isHungry, …
Behaviour: bark(), fetch(), eat(), …
Car
State: make, model, speed, number of doors, …
Behaviour/operation: accelerate, decelerate, open bonnet …
VCR
State: brand, colour, isOn …
Behaviour: play(), stop(), rewind(), turnOn(), …
4 02
2. Built-In Classes in Java
Java provide some useful classes in the java.awt package.
These classes provide us with some methods and fields that help us
save time and effort in writing code and repeating it more and
more…
Example:
Point class : A point representing a location in (x,y) coordinate space,
specified in integer precision.
Fields: x-coordinate, y-coordinate
Rectangle class: A rectangle specifies an area in a coordinate space that is
defined by the rectangle's top-left point (x, y) in the coordinate space, its
width, and its height. Point Rectangle
Fields: top-left point (x,y), width and height x =23 x =0
Creating Objects from Java built-in classes y = 94 y=0
width=50
Declaration
height=100
Instantiation
Initialization
5 02
2. Built-In Classes in Java
Creating Objects No object has been
Declaration: Point p; created with this
declaration.
Declaring a Variable to Refer to an Object
Note: a variable either holds a primitive type, or it holds a
reference to an object. p
2
Point p2 = new Point(23, 94); x 23
Instantiation & Initialization: y 94
The new keyword is a Java operator that creates the object.
This is known as instantiating a class.
The new operator allocates memory for the new object
The new operator returns a reference to the object it created
The new operator is followed by a call to a constructor.
For example, Point(23, 94) is a call to Point's only constructor.
The constructor initializes the new object with x is 23 and y
is 94
6 02
L08Code.ja
2. Built-In Classes in Java va
Examples:
Objects: originOne, rectOne, rectTwo originOne:
Point
Remember to add x =23
import java.awt.Point; the import y = 94
import java.awt.Rectangle; statements
rectOne:
public class L08Code { Rectangle
public static void main(String[] args){
x =10
Point originOne = new Point(23, 94);
Rectangle rectOne = new Rectangle(10, 20, 100, 200); y = 20
Rectangle rectTwo = new Rectangle(50, 100); width=100
System.out.println(rectOne.getWidth());
height=200
System.out.println(rectTwo.getLocation());
System.out.println(originOne.toString());
} rectTwo:
} Rectangle
x =0
100.0 y=0
java.awt.Point[x=0,y=0]
width=50
java.awt.Point[x=23,y=94]
height=100
7 02
3.Creating Classes
We can write our own classes that define specific objects that we
need.
Each class you create becomes a new type that can be used to declare
variables and create objects.
A class definition has two parts: a class declaration and a class body.
Class declaration
contains keyword “class” followed immediately by the class’s name.
Class body class MyClass {
contains //field and method declarations
}
constructors for initializing new objects,
declarations for the variables that provide the state, and
methods to implement the behavior of the class and its objects.
Note: Each class declaration that begins with the access modifier public
must be stored in a file that has the same name and ends with the .java
extension.
Class, method and variable names are identifiers. (i.e. all use camel case
names.)
8 02
3.Creating Classes
Instance Variables
Instance variables are dynamically allocated,
So they may have different values in each instance
of an object.
A class declares the type of the data, but it does not
reserve any memory space for it
When an object is instantiated, the runtime system b1: Ball
allocates some memory to this instance – so that it xPos=10
can “remember” the values it stores in instance b2: Ball
yPos = 20
variables carried with it throughout its lifetime. xPos =10
Color = Red
Instance variables exist before methods are called yPos = 10
on an object. Color =
Blue
A class normally contains one or more methods that b3: Ball
manipulate the instance variables that belong to
xPos = 5
particular objects of the class.
yPos = 5
Instance variables are declared inside a class Color =
declaration but outside the bodies of the class’s Green
9 method declarations. 02
3.Creating Classes
Visibility Modifiers
Java provides a number of access modifiers to set
access levels for classes, variables, methods and
constructors. There are four levels but we look at two
levels first.
Members of a class that are declared with public visibility can
be accessed from anywhere
Members of a class that are declared with private visibility can
only be access from inside the class
As a general rule
No object's data should be declared as public.
Methods are usually declared as public so that they can be
invoked by the clients
A method created simply to assist a service method is called a
support method and should not be declared as public
10 02
Car.jav public class Car {
3.Creating Classes a private String make;
private String model;
Instances of Car private int year;
private int speed;
Car c1 = new Car("Nissan", "Leaf", 2010, 4); private int doors;
Car c2 = new Car("Bentley", "Hunaudieres", 1999, 2); private boolean openBonnet;
Car c3 = new Car("Ford", "Mustang", 2008, 2);
...
Pictures: }
Objects in memory:
11 02
3.Creating Classes
Constructors
Constructors are invoked to create objects from the class
blueprint and initialize instance variables.
It looks like method declarations — except that they use the
name of the class, can specify parameters but no return
type.
It automatically called when an object is created using
the new operator
Note: Java requires a constructor call for every object that’s
created.
It could have more than one constructors (i.e. overloading)
Each constructor has a different signature (a public
different number
Point() { of
sequence of argument types) x=0;
public Point() { ... y=0;
public Point(Point p) { ... }
public Point(int x, int y) { ...
12 02
3.Creating Classes
Constructors (con’t)
Default Constructor
If a class definition doesn’t include a constructor method,
the Java compiler inserts a default constructor with no
parameters, and the class’s instance variables are
initialized to their default values.
int:0, String: null, boolean: false
Recall that local variables are not initialized by default.
Note: There’s No Default Constructor in a Class That
Declares a Constructor
If you declare a constructor for a class, the compiler will NOT
create a default constructor forclass
public thatMyMessage
class. { m:
int x; MyMessage
String y; x=0
} must be
careful when y = null
doing this
13 02
3.Creating Classes
Instance Methods
Instance methods operate on this object's instance variables.
15 02
3.Creating Classes
Object Instantiation
When a constructor method is called, a new instance
isBall
created.
b = new Ball( 10, 20, Color.Red ); b: Ball
Ball c = new Ball( 0, 10, Color.Blue ); 60
xPos = 10
c: Ball yPos = 20 120
xPos = 0 Color = Red
yPos = 10
Color =
Blue
Message Passing
In a method call, a message is passed to a receiver object.
The receiver’s
b.move(50, 100); response to the message is determined by
public class Ball {
its class. ...
public void move(int deltaX, int deltaY) {
message xPos += deltaX;
receiver yPos += deltaY;
arguments }
}
16 02
3.Creating Classes
Instance Method: setXXX & getXXX
Method getX() returns a particular Ball object’s x-position to the
caller.
This method has an empty parameter list, so it does not require
additional information to perform its task and just return the value
Get methods are also commonly called accessor methods
Method setX() assigns the value of the parameter (an int) to the
class’s xPos instance variable, thus storing the x-position in the
object.
Note: If a method contains a local variable with the same name as an
instance variable, that method’s body will refer to the local variable rather
than the instance variable.
The local variable is said to shadow the instance variable in the method’s body.
You use the keyword this to refer to the shadowed instance variable explicitly
Set methods
public are also
int getX() { commonly called mutator methods
return xPos; public void setX(int xPos) {
} this.xPos = xPos;
}
17 02
Point b = new Point( 10, 20); b: Point
3.Creating Classes x=
18 02
Exercise 1
What is the output?
public class Puppy{
int puppyAge;
public Puppy(String name){
System.out.println("Name chosen is :" + name );
}
public void setAge( int age ){
puppyAge = age;
}
public int getAge( ){
System.out.println("Puppy's age is :" + puppyAge );
return puppyAge;
}
public static void main(String []args){
Puppy myPuppy = new Puppy( "tommy" );
myPuppy.setAge( 2 );
myPuppy.getAge( );
System.out.println("Variable Value :" + myPuppy.puppyAge );
}
}
19 02
Stuff.jav
4.Class Variables & Class Methods a
Class Variables
You specify a class member variable or a class
method by using the static keyword in the member's
declaration.
A static variable represents classwide information—all
objects of the class share the same piece of data.
Class variables are statically allocated, so they
are shared by an entire Class of objects
The runtime system allocates class variables once per
class, regardless of the number of instances created Stuff of that
class. (i.e. only one copy) X: 10
Static
public storage
class Stuff { is allocated when the class isa1: loaded.
Stuff a2 : Stuff
public static int x = 10; Stuff a1 = new Stuff();
} All instances share the same
Stuff a2copy
= new of the class variables
Stuff();
System.out.println(Stuff.x);
20 02
4.Class Variables & Class Methods
Class Methods
Some methods do work but don’t need an object.
Use the class name instead of an object name to
invoke Math.round(2.3);
Integer.parseInt("123");
21 02
4.Class Variables & Class Methods
Additional Notes
A static method can call other static methods of the same
class directly (i.e., using the method name by itself) and
can manipulate static variables in the same class directly.
Java does not allow a static method to directly access instance
variables and instance methods of the same class
It is because a static method can be called even when no objects of the
class have been instantiated. (i.e. this reference cannot be used in a
static method)
Instance methods can access all fields (static variables
and instance variables) and methods of the class.
Many objects of a class, each with its own copies of the instance
variables, may exist at the same time.
Declaring instance variables private is known as data
hiding or information hiding.
22 02
SharedCounter.ja
va
23 02
Exercise 2 Employee bob = new Employee("Bob", "Blue");
Employee susan = new Employee("Susan", "Baker");
System.out.println(Employee.getCount());
Exercise: 2
}
}
25 02
Exercise 4
Consider the MyPoint class again, what will happen if
the two constructors are declared as private?
class MyPoint {
private int x;
private int y;
private MyPoint() {
...
}
private MyPoint(int x, int y) {
...
}