Download presentation
Presentation is loading. Please wait.
1
Java LESSON 7 Objects, Part 1
2
Before We Start Objects...
You now need a full understanding of: variables (types, declaration, initialisation) loops (while, for, do) conditionals (if, switch) methods (parameter lists, return types, scope) Otherwise you CAN’T understand Objects !
3
Why Objects ? History of Programming (abridged): In the beginning…….
BASIC: the "Goto crisis" PROCEDURES (’Methods’ in Java) A little later…... Pascal, C, et al.: the "Software crisis" OBJECTS
4
Important: Encapsulation
In Objects METHODS shield the DATA from other objects data method “talks to” another object… data method data method data method One object… Which in turn talks to others…
5
An Example: Re-Usability Consider a car:-
A car manufacturer may use a component across a range of models e.g. locks and ventilation controls; Different car manufacturers may use the same component supplied by a single manufacturer e.g. tyres and wiper-blades. Re-Usability
6
Similarities Real Objects - Program Objects
However the components must still be : Designed Once only Engineered / Built Repeatedly So too must software components and the programs which manipulate them.
7
Similarities Real Objects - Program Objects
Blueprint or Plan = java class Designed Once only Engineered / Built Repeatedly Manufacturing Line = java object instances
8
Object Orientated Basics
The state of an object is represented by the attributes of the object. The state of an object can be changed or interrogated via the methods.
9
Enough Theory Lets do it !
10
Object Orientated Example: “Car” Fundamentals (1 of 3)
Consider Cars: We start with a single underlying “blueprint“ for the Cars we want to use Lots of Cars will then be instances (i.e. copies) of the same blueprint;
11
A Blueprint (an early method of making photocopies)
12
Instances (produced from the blueprint)
13
“Car” Fundamentals (2 of 3)
Each Car instance (copy) can access methods such as (remember the lesson on methods ?): Setting the attribute changeSpeedBy getSpeed Interrogating the attribute In this example Car attributes (e.g. int speed, int direction ) store the state of the cars. attributes methods
14
“Car” Fundamentals (3 of 3)
To summarise: We start with a single “blueprint” for Cars From that we can later build multiple instances (i.e. copies) of Cars Each Car instance has methods (i.e. can do things) The methods act on the attributes of each Car (i.e. speed, direction, etc.)
15
“Car” Object Implementation
design once Car “Blueprint” - methods - attributes The ‘Car’ class Car.java Multiple builds Car 3 - methods - attributes Car 2 - methods - attributes Car 1 - methods - attributes The ‘UseCar’ class UseCar.java Car instances
16
General Structure of “Blueprints”
Attributes (variables, constants) Class attributes Attributes which are identical for all objects created from the blueprint. e.g. "FORWARDS" for Cars - same for all. ‘static’ keyword public class NameOfClass { // Class attribute(s) go here // Object attribute(s) go here // Constructor(s) go here // Other methods go here // Optional ‘main’ method here } // end of the ‘blueprint’ class Objects attributes Variables which are copied into individual objects created from the blueprint. e.g. “state” (speed), - different for each. NO 'static' keyword
17
General Structure of “Blueprints”
Methods (manipulate attributes) Constructor(s) Special method that creates a new object from the blueprint. Has same name as blueprint. public class NameOfClass { // Class attribute(s) go here // Object attribute(s) go here // Constructor(s) go here // Other methods go here // Optional ‘main’ method here } // end of the ‘blueprint’ class Other methods Usually so called ‘get’ and ‘set’ methods that manipulate the attributes. Possibly other ‘helper’ methods ’main’ method Not required, but may be used for testing and demonstration of usage
18
Car.java “Blueprint” Class attributes Objects attributes
public class Car { // Class attribute(s) go here // Object attribute(s) go here // Constructor(s) // 'Set' and 'Get' methods Car.java “Blueprint” public static final int FORWARDS=1; public static final int BACKWARDS=0; private int speed; private int direction; Class attributes Attributes which are identical for all objects created from the blueprint. e.g. the constant FORWARDS for Cars - same for all. ‘static’ keyword ‘public’ keyword ‘final’ keyword public Car () { speed=0; direction=FORWARDS; } Objects attributes Variables which are copied into individual objects created from the blueprint. e.g. “state” (speed), - different for each ‘private’ keyword no 'static' Constructor(s) Special method that creates a new object from the blueprint. Has same name as the blueprint class (i.e. 'Car'). ‘public’ keyword no 'static' public void changeSpeedBy(int amount) { speed = speed + amount; if ( speed > 70 ) { speed = 70; } if ( speed < 0 ) { speed = 0; } // end of method 'changeSpeedBy' Other methods Usually so called ‘get’ and ‘set methods that manipulate the attributes. Other ‘helper’ methods ‘public’ keyword no 'static' ’main’ method Not required, but may be used for testing and demonstration of usage public int getSpeed() { return speed; } // end of method 'getSpeed' public void changeDirection() { if ( direction == FORWARDS ) { direction = BACKWARDS; } else { direction = FORWARDS; } // end of method 'changeDirection'
19
Non-OO Car vs. 'Car' blueprint
public class Car { public static final int FORWARDS=1; public static final int BACKWARDS=0; private static int speed=0; private static int direction=FORWARDS; public static void changeSpeedBy(int amnt) { speed = speed + amnt; if ( speed > 70 ) { speed = 70; } if ( speed < 0 ) { speed = 0; } // end of method 'changeSpeedBy' public static int getSpeed() { return speed; } // end of method 'getSpeed' public class Car { // Class attribute(s) go here // Object attribute(s) go here // constructor(s) // 'Set' and 'Get' methods public static final int FORWARDS=1; public static final int BACKWARDS=0; private int speed; private int direction; public Car () { speed=0; direction=FORWARDS; } The Car class from Lesson 6 on Methods public void changeSpeedBy(int amnt) { speed = speed + amnt; if ( speed > 70 ) { speed = 70; } if ( speed < 0 ) { speed = 0; } // end of method 'changeSpeedBy' public int getSpeed() { return speed; } // end of method 'getSpeed' 11/12/2018
20
“UseCar” Implementation
design once Car “Blueprint” - methods - attributes Multiple builds Car 3 - methods - attributes Car 2 - methods - attributes Car 1 - methods - attributes The ‘UseCar’ class UseCar.java Car instances
21
Building Cars (Constructing) (UseCar.java)
public class UseCar { public static void main(String args[]) { Car car1 = new Car(); Car car2 = new Car(); System.out.print ( "Initial car speed : "); System.out.println ( car1.getSpeed()); System.out.println ( car2.getSpeed()); System.out.println ( "\nNow floor pedal of car1"); car1.changeSpeedBy( 300 ); } //end of main } // end of the UseCar class Compare 'constructing' to int x = 5; Car car1 = new Car(); Car car2 = new Car(); Class of object to construct Name of the object to construct Call the constructor Keyword "new" public Car () { speed=0; direction=FORWARDS; }
22
Using Cars (via Methods) (UseCar.java)
public class UseCar { public static void main(String args[]) { Car car1 = new Car(); Car car2 = new Car(); System.out.print ( "Initial car speed : "); System.out.println ( car1.getSpeed()); System.out.println ( car2.getSpeed()); System.out.println ( "\nNow floor pedal of car1"); car1.changeSpeedBy( 300 ); } //end of main } // end of the UseCar class public int getSpeed() { return speed; } // end of method 'getSpeed' Output: car1 : 0 car2 : 0 dot Name of the object Method called returns speed
23
Using Cars (cont.) (UseCar.java)
public void changeSpeedBy(int amnt) { speed = speed + amnt; if ( speed > 70 ) { speed = 70; } if ( speed < 0 ) { speed = 0; } // end of method 'changeSpeedBy' public class UseCar { public static void main(String args[]) { Car car1 = new Car(); Car car2 = new Car(); System.out.print ( "Initial car speed : "); System.out.println ( car1.getSpeed()); System.out.println ( car2.getSpeed()); System.out.println ( "Now floor pedal of car1"); car1.changeSpeedBy( 300 ); } //end of main } // end of the UseCar class Output: car1 : 70 car2 : 0
24
Done ! Car instances design once Car “Blueprint” - methods
- attributes Multiple builds Car 3 - methods - attributes Car 2 - methods - attributes Car 1 - methods - attributes Car instances
25
Review: Object Orientated Basics
The state of an object is represented by the attributes (object variables) of the object. (Object variables 'speed' and 'direction') The state of an object can be changed or interrogated via the methods. (changeSpeedBy( int amnt ) , getSpeed() )
26
Review: “Car” Fundamentals
We start with a single underlying “blueprint“ for the Cars we want to use (The 'Car' class in 'Car.java') Lots of Cars will then be instances (i.e. copies) of the same blueprint; (The 'UseCar' class in 'UseCar.java')
27
Review: “Car” Fundamentals
Each Car instance (copy) can access methods such as: Setting the attribute changeSpeedBy getSpeed Interrogating the attribute In this example a Car attributes (e.g. int speed, int direction ) store the state of the cars. attributes methods
28
Review: The keyword 'static'
'static' methods and variables (usually constants) exist only once for all copies made from the 'blueprint'. These methods or variables are then called 'class' methods or 'class' variables public static final int FORWARDS=1; public static final int BACKWARDS=0; If methods and class variables (rarely constants) are declared WITHOUT 'static' a separate copy is made for each instance produced from the 'blueprint' These methods or variables are then called 'object' methods or 'object' variables private int speed=0; private int direction=FORWARDS;
29
Review: 'private' Object Variables
Object variables (i.e. no 'static'), declared 'private' can NOT be accessed directly from other classes (e.g. UseCar.java) The reason for this 'encapsulation' is 'safety'. Access to these variables is ONLY indirectly via public methods. private int speed=0; private int direction=FORWARDS; public void changeSpeedBy(int amnt) { speed = speed + amnt; if ( speed > 70 ) { speed = 70; } if ( speed < 0 ) { speed = 0; } // end of method 'changeSpeedBy'
30
Review: Constructors Can be thought of as factories turning blueprints (the 'Car' class) into 'real' (well…) objects. Once "constructed" an object 'exists' (i.e. has its own space inside the memory). It has: a name (car1, car2, myCar, andrewsWreck) attributes (speed, direction) a state (values stored in 'speed', 'direction') methods (changeSpeedBy(…), getSpeed() ) Car car1 = new Car();
31
Review: Methods Can manipulate and interrogate the state of objects.
Scope Returned type Method name (Formal parameter list) body of the method where computations are made return statement (if anything gets returned) { } // end of method Can manipulate and interrogate the state of objects. Are often 'public' and then act as "safety filters" to prevent damage (more about that next week). Are accessed using the ObjectName-dot-methodName convention. Method Call Returned parameter = Method name (Actual parameter list) ;
32
And now: Let’s repeat.... Then: how to use objects
The ‘Car' example re-packaged as a 'Switch' Then: how to use objects more about 'constructing' testing Finally: The concept of inheritance don't re-invent the wheel re-usability
33
Object Orientated Example: “Switch” Fundamentals (1 of 2)
Consider Switches: We start with a single underlying “blueprint“ for the Switches we want to use Lots of Switches will then be instances (roughly "copies") made from the same blueprint;
34
“Switch” Fundamentals (2 of 2)
Each Switch instance ("copy") can access methods such as: Changing the attribute turnOn, turnOff getStatus Interrogating the attribute attributes methods In this example a single Switch attribute (e.g. int state) stores the state of the Switch.
35
“Switch” Implementation (1 of 4)
design once Switch “Blueprint” - methods - attributes ‘Switch’ class Switch.java Multiple builds Switch 3 - methods - attributes Switch 2 - methods - attributes Switch 1 - methods - attributes ‘UseSwitch’ class UseSwitch.java Switch instances
36
General Structure of “Blueprints”
Attributes (variables, constants) Class attributes Attributes which are identical for all objects created from the blueprint. e.g. "ON" for Switches - same for all. ‘static’ keyword public class NameOfClass { // Class attribute(s) go here // Object attribute(s) go here // Constructor(s) go here // Other methods go here // Optional ‘main’ method here } // end of the ‘blueprint’ class Object attributes Variables which are copied into individual objects created from the blueprint. e.g. “state”, - different for each. NO 'static' keyword
37
General Structure of “Blueprints”
Constructor(s) Special method that creates a new object from the blueprint. Has same name as blueprint. Other methods Usually so called ‘get’ and ‘set’ methods that manipulate the attributes. Possibly other ‘helper’ methods Methods (manipulate attributes) ’main’ method Not required, but may be used for testing and demonstration of usage public class NameOfClass { // Class attribute(s) go here // Object attribute(s) go here // Constructor(s) go here // Other methods go here // Optional ‘main’ method here } // end of the ‘blueprint’ class
38
Switch.java “Blueprint”
public class Switch { // Class attribute(s) go here // Object attribute(s) go here // constructor(s) // Other methods } // end of the Switch class Switch.java “Blueprint” public static final int ON = 1; public static final int OFF = 0; private int state = OFF; Class attributes Attributes which are identical for all objects created from the blueprint. e.g. the constant ON for Switches - same for all. ‘static’ keyword usually 'public' keyword ‘final’ if constants public Switch () { state=OFF; } Objects attributes Variables which are copied into individual objects created from the blueprint. e.g. “state”, - different for each Switch ‘private’ keyword No ‘static’ Constructor(s) Special methods that create a new object from the blueprint. Has same name as the blueprint class (i.e. 'Switch'). Returns a "Switch" object ‘public’ keyword public void turnOn() { state = ON; } public void turnOff() { state = OFF; public String getStatus() { if ( state == ON ) return “On”; else return “Off”; Other methods Usually so called ‘get’ and ‘set methods that manipulate the attributes. Other ‘helper’ methods ‘public’ keyword ’main’ method Not required, but may be used for testing and usage demonstration
39
“Switch” Implementation (1 of 4)
design once Switch “Blueprint” - methods - attributes Multiple builds Switch 3 - methods - attributes Switch 2 - methods - attributes Switch 1 - methods - attributes ‘UseSwitch’ class UseSwitch.java Switch instances
40
Building and Using Switches UseSwitch.java
public class UseSwitch { public static void main(String args[]) { Switch switch1 = new Switch(); Switch switch2 = new Switch(); System.out.println ( "Initial switch states : "); System.out.println ( switch1.getStatus()); System.out.println ( switch2.getStatus()); System.out.println ( "Now turn switch 1 on"); switch1.turnOn(); } //end of main } // end of the UseSwitch class
41
Building and Using Cars UseCar.java
public class UseSwitch { public static void main(String args[]) { Switch switch1 = new Switch(); Switch switch2 = new Switch(); System.out.println ( "Initial switch states : "); System.out.println ( switch1.getStatus()); System.out.println ( switch2.getStatus()); System.out.println ( "Now turn switch 1 on"); switch1.turnOn(); } //end of main } // end of the UseSwitch class Call the constructor Class of object to construct Keyword "new" Name of the object to construct public Switch () { state=OFF; } Compare 'constructing' to int x = 5;
42
Building and Using Switches UseSwitch.java
public String getStatus() { if ( state == ON ) return “On”; else return “Off”; } public class UseSwitch { public static void main(String args[]) { Switch switch1 = new Switch(); Switch switch2 = new Switch(); System.out.println ( "Initial switch states : "); System.out.println ( “switch1: “ + switch1.getStatus()); System.out.println ( “switch2:” + switch2.getStatus()); System.out.println ( "Now turn switch 1 on"); switch1.turnOn(); System.out.println ( switch1.getStatus()); System.out.println ( switch2.getStatus()); } //end of main } // end of the UseSwitch class Output: switch1 : Off switch2 : Off dot Name of the object Method called returns state
43
Building and Using Switches UseSwitch.java
public void turnOn() { state = ON; } public String getStatus() { if ( state == ON ) return “On”; else return “Off”; public class UseSwitch { public static void main(String args[]) { Switch switch1 = new Switch(); Switch switch2 = new Switch(); System.out.println ( "Initial switch states : "); System.out.println ( “switch1: “ + switch1.getStatus()); System.out.println ( “switch2: “ + switch2.getStatus()); System.out.println ( "Now turn switch 1 on"); switch1.turnOn(); System.out.println ( “switch1:” + switch1.getStatus()); System.out.println ( “switch2” + switch2.getStatus()); } //end of main } // end of the UseSwitch class Output: switch1 : On switch2 : Off
44
Done ! Switch instances design once Switch “Blueprint” - methods
- attributes Multiple builds Switch 3 - methods - attributes Switch 2 - methods - attributes Switch 1 - methods - attributes Switch instances
45
Review: Object Orientated Basics
The states of an object are represented by the (usually private) attributes of the object. (Object variable 'state') The states of an object can be changed or interrogated via the (usually public) methods . (turnOn, turnOff , getStatus() ) This means that the private attributes are protected from unauthorised access by the public methods. The methods act as gatekeepers to the data. The data are ENCAPSULATED (next slide)
46
Important: Encapsulation
In Objects METHODS shield the DATA from other objects data method “talks to” another object… data method data method data method One object… Which in turn talks to others…
47
Review: “Switch” Fundamentals
We start with a single underlying “blueprint“ for the Switches we want to use (The 'Switch' class in 'Switch.java') Lots of Switches will then be instances (i.e. "copies") of the same blueprint; (The 'UseSwitch' class in 'UseSwitch.java')
48
Review: “Switch” Fundamentals
Each Switch instance ("copy") can access methods such as: Changing the attribute turnOn, turnOff getStatus Interrogating the attribute attributes methods In this example a single Switch attribute (e.g. int state) stores the state of the Switch.
49
Review: The keyword 'static'
'static' methods and variables (or constants) exist only once for all copies made from the 'blueprint'. These methods or variables are then called 'class' methods or 'class' variables public static final int ON=1; public static final int OFF=0; If methods and class variables (rarely constants) are declared WITHOUT 'static' a separate copy is made for each instance produced from the 'blueprint' These methods or variables are then called 'object' methods or 'object' variables private int state=ON;
50
Constructors: We already know….
Can be thought of as factories turning blueprints (the 'Switch' class) into 'real' (well…) objects. Once "constructed" an object 'exists'. (i.e. has its own space inside the memory) It has: a name (switch1, switch2, mySwitch,….) attributes (state) a state (values stored in 'state') methods (turnOn(), turnOff(), getStatus() ) Switch switch1 = new Switch();
51
Constructors: And this is new….
There can be more than 1 constructor in a class: 'blueprint' Switch class UseSwitch class public Switch (int initialState) { state=initialState; } // end of second constructor Switch switch2 = new Switch( Switch.ON ); public static final int ON = 1; public static final int OFF = 2; public Switch () { state=OFF; } // end of DEFAULT constructor Switch switch1 = new Switch();
52
Remember the 'Car' class ? Is this a good idea? Think ‘Safety’
'blueprint' Car class UseCar class public static final int FORWARDS=1; public static final int BACKWARDS=0; public Car () { speed=0; direction=FORWARDS; } // end of DEFAULT constructor Car car1 = new Car(); public Car (int iniSpeed) { speed=iniSpeed; direction=FORWARDS; } // end of second constructor Car car2 = new Car( 500 ); Is this a good idea? Think ‘Safety’ public Car (int iniSpeed, int iniDir) { speed=iniSpeed; direction=iniDir; } // end of third constructor Car car3 = new Car(30, Car.FORWARDS);
53
Use "Safety" Features Instead of: Better use:
public Car (int iniSpeed) { speed=iniSpeed; direction=FORWARDS; } Car car2 = new Car( 500 ); Better use: public Car (int iniSpeed) { setSpeed( iniSpeed ); direction=FORWARDS; } public void setSpeed(int spd) { if ( spd > 70 ) { spd = 70; } if ( spd < 0 ) { spd = 0; speed = spd; } // end of method 'setSpeed'
54
Testing the "Blueprint" Testing and to give a
The "Switch" and the "Car" class don't have a 'main' method. (Not required for function) However, it is a good idea to do some Testing and to give a Demonstration of how to use the class Therefore:……….
55
// Class attribute(s) go here
public class Switch { // Class attribute(s) go here // Object attribute(s) go here // constructor(s) // Other methods } // end of class Switch public static final int ON = 1; public static final int OFF = 2; private int state = OFF; public Switch () { state=OFF; } // main method to test and demonstrate public static void main(String args[ ]) { Switch switch1 = new Switch(); Switch switch2 = new Switch(); System.out.println ( "Initial switch states : "); System.out.println ( switch1.getStatus()); System.out.println ( switch2.getStatus()); System.out.println ( "\nNow turn switch 1 on"); switch1.turnOn(); } // end of main public void turnOn() { state = ON; } // end of turnOn public void turnOff() { state = OFF; } // end of turnOff public String getStatus() { if ( state == ON ) return “On”; else return “Off”; } // end of getStatus 11/12/2018
56
Today's Content The use of Objects requires:
a ‘template‘ class that defines the Object a ‘use’ class that ‘instantiates’ the Object(s) using ‘constructors’ private object attributes are encapsulated safely by public accessor methods public class attributes tend to be constants and thus do not need this protection
57
END OF LESSON 7
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.