2. Outline
Phase 1
▪ Creating a class
▪ Get and set methods
▪ Constructors
▪ Private and public
▪ Encapsulation
3. Recall…
▪ So far we
have been
dealing with
a simple
template.
– Some import
statements
– Main class
▪ Attributes
▪ Methods
(one must be
main)
import <something>;
public class L3{
//<some attributes>
public static void main(String[] args) {
//<some stuff>
}
}
4. Recall…
▪ In this lecture, we will be shifting between
– Writing a class
– Creating objects using that class in the main method
▪ Make sure you know which one we are in.
5. Writing your own class
▪ Not necessary but recommended that each class gets
its own file – name the .java file after the class.
▪ Remember that classes are helpful in creating
programming versions of real-world things.
▪ Lets make some classes for a University program. What
objects would be useful?
– Students
– Staff
– Courses
– Degrees
– …
6. Writing your own class
▪ Let’s start with Student:
▪ We need some attributes and
methods.
▪ For now, some basic attributes:
– firstName, lastName
public class Student {
String firstName;
String lastName;
//Methods
}
7. Writing your own class
▪ Now in the main method, I
could create an object from this
class and access its attributes:
public class L4 {
public static void main(String[] args) {
Student s = new Student();
s.firstName = "Jonathan";
s.lastName = "Parker";
}
}
But…
8. Accessor and Mutator Methods
▪ Accessor methods return the value of a variable.
▪ Typically named with “get” in front of the variable name
▪ Mutator methods set the value of a variable.
▪ Typically named with “set” in front of variable name
A good practice is to prevent the user from accessing or
changing attributes directly, but instead to do so through
accessor and mutator methods
9. Accessor and Mutator Methods
▪ Accessor method for firstName.
– No input argument
– return a String type
– return value of firstName
▪ Mutator method for firstName.
– Must take new value for firstName as
input argument
– No return type
– No return value
public class Student {
String firstName;
String lastName;
String getFirstName(){
return firstName;
}
void setFirstName(String s){
firstName = s;
}
String getLastName(){
return lastName;
}
void setLastName(String s){
lastName = s;
}
}
10. ▪ The reason for doing this
will become clear later on.
▪ It helps control which
classes have access to
these variables.
public class Student {
String firstName;
String lastName;
String getFirstName(){
return firstName;
}
void setFirstName(String s){
firstName = s;
}
String getLastName(){
return lastName;
}
void setLastName(String s){
lastName = s;
}
}
Accessor and Mutator Methods
11. Constructor Methods
▪ Useful for initializing variables
▪ Constructors are named after the class
▪ Constructors do not return anything, no return
type or return statement
▪ Constructors are run immediately after an object is
created.
Constructor method
A method executed when a new instance of a class is
created.
12. Constructor Methods
Constructor method:
▪ We can pass parameters to the constructor.
▪ We can use these parameters to initialize some
variables, or initialization can be hard-coded.
▪ Say, default first name is “Jonathan”, default last name
is “Parker”.
▪ If we don’t define a constructor, then the compiler
creates a default constructor, which is blank.
13. Constructor Methods
▪ Constructor method:
public class Student {
String firstName;
String lastName;
Student(String defaultFirstName, String defaultLastName){
firstName = defaultFirstName;
lastName = defaultLastName;
}
//Other methods
}
Same
name
14. Constructor Methods
…
Student(){
firstName = "John";
lastName = "Smith";
}
…
…
Student(String defaultFirstName,
String defaultLastName){
firstName = defaultFirstName;
lastName = defaultLastName;
}
…
Constructor taking arguments
to set default values.
Constructor with hard coded
default values.
15. Constructor Methods
▪ Now we can create an object
public class L4 {
public static void main(String[] args) {
Student s = new Student("Jonathan", "Parker");
}
}
16. Accessor and Mutator Methods
▪ We can use the objects methods.
public class L4 {
public static void main(String[] args) {
Student s = new Student("Jonathan", "Parker");
System.out.println("First Name is " + s.getFirstName());
System.out.println("Last Name is " + s.getLastName());
}
}
First Name is Jonathan
Last Name is Parker
17. Accessor and Mutator Methods
▪ We can use the objects methods.
public class L4 {
public static void main(String[] args) {
Student s = new Student("Jonathan", "Parker");
s.setFirstName("Harry");
s.setLastName("Potter");
System.out.println("First Name is " + s.getFirstName());
System.out.println("Last Name is " + s.getLastName());
}
}
First Name is Harry
Last Name is Potter
18. Writing your own class
▪ At the moment, our Student class doesn’t do much…
▪ Let’s add an attribute: an array that contains test marks
public class Student {
…
float[] testMarks;
…
Student(String defaultFirstName, String defaultLastName){
firstName = defaultFirstName;
lastName = defaultLastName;
testMarks = new float[5];
}
}
19. Writing your own class
▪ When is the array created?
▪ We only create the array at the creation of the object - we can
get the desired size as an input to the constructor.
public class Student {…
float[] testMarks;
…
Student(String defaultFirstName, String defaultLastName , int NoTests){
firstName = defaultFirstName;
lastName = defaultLastName;
testMarks = new float[NoTests];
}
}
20. Writing your own class
▪ We can give get and set methods for this array.
▪ There are more sophisticated ways of interacted with
arrays which we will see later.
void setTestMark(float mark, int id){
testMarks[id] = mark;
}
float getTestMark(int id){
return testMarks[id];
}
21. Writing your own class
▪ We can also write a method that displays all the marks.
void displayAllTestMarks() {
System.out.println();
for (int i = 0; i < testMarks.length;i++) {
System.out.printf("Test " + i + ": %.1fn",testMarks[i]);
}
}
22. Writing your own class
Exercise:
▪ Write a method that gives the maximum mark for the tests
▪ Write a method that gives the minimum mark for the tests
▪ Write a method that gives the average mark for the tests
23. Writing your own class
Exercise:
▪ Write a method that gives the maximum mark for the tests
– Initialise the maximum mark to minimum possible value
– Loop through all the marks if mark > max_mark then set max_mark =
mark
▪ Write a method that gives the minimum mark for the tests
– Initialise the minimum mark to maximum possible value
– Loop through all the marks if mark < min_mark then set min_mark =
mark
▪ Write a method that gives the average mark for the tests
– Loop through all the marks, add them up
– After the loop, divide the marks by the number of marks
24. Writing your own class
float returnMaxMark() {
float max = 0;
for (float t : testMarks) {
max = t > max ? t : max;
}
return max;
}
float returnMinMark() {
float min = 100;
for (float t : testMarks) {
min = t < min ? t : min;
}
return min;
}
float returnAveMark() {
float sum = 0, ave = 0;
for (float t : testMarks) {
sum += t;
}
ave = sum/testMarks.length;
return ave;
}
25. Methods calling methods
▪ Methods calling methods: methods of one object can call
methods of that same object.
▪ Example: if we want to display…
– the students name,
– with all the test marks
– and the max, min and average marks,
▪ …we can use some of the methods we wrote earlier.
26. Methods calling methods
▪ Note: we don’t need to use the dot notation i.e.
Student.displayAllTestMarks()
▪ Can just say displayAllTestMarks() – why can we do this?
void displayAllStats() {
System.out.println("Name: " + firstName +" " + lastName);
System.out.println();
displayAllTestMarks();
System.out.println();
System.out.printf("Average: %.1fn", returnAveMark());
System.out.printf("Maximum: %.1fn", returnMaxMark());
System.out.printf("Minimum: %.1fn", returnMinMark());
}
27. Writing your own class
▪ Summary so far:
– Created a class
– Given it some attributes
– Wrote methods to access and change these values
– Wrote a constructor to initialize the attributes
– Wrote methods that did stuff with these attributes
– Wrote a method that used another method
28. Accessibility Modifiers
▪ A private attribute can only be accessed by the methods
of that class or object.
▪ A private method can only be accessed by the methods
of that class or object.
▪ We can also modifier whole classes to be public or
private – more later.
Accessibility modifiers
Change what methods can access the members of a class
29. Accessibility Modifiers
▪ By default, members are public. Good practice to include
them anyway.
private String firstName;
private String lastName;
private float[] testMarks;
A common practice is to declare most or all attributes private
and then use the get and set methods to interact with the
attributes outside of the class.
30. Accessibility Modifiers
▪ Now, if we try to access the private attributes directly in
the main class, we won’t be able to:
public class L4 {
public static void main(String[] args) {
Student s = new Student("Jonathan", "Parker");
s.firstName = "Jonathan";
s.lastName = "Parker";
}
}
Will not compile
31. Accessibility Modifiers
▪ But accessing the private attributes directly from within
the same class will be fine:
public class Student {
void displayAllTestMarks() {
System.out.println();
for (int i = 0; i < testMarks.length;i++) {
System.out.printf("Test " + i + ": %.1fn",testMarks[i]);
}
}
}
32. Encapsulation
▪ It is a core tenet of object orientated programming.
▪ Why?
– Prevents the user of our class accessing information or functions
that they shouldn’t.
– Helps provide an extra layer of abstraction between what the
class does and how it does it.
Encapsulation
Information hiding – members of a class or object
are hidden from the outside.
33. Encapsulation
▪ Example: Imagine a class that controls the movement of
a humanoid robot.
▪ We want the robot to:
– Move forward
– Increase/decrease speed
– Change direction
▪ The way we implement these might be with methods:
– Take one step forward
– Increase/decrease speed of motor
– Change relative speed each leg
34. Encapsulation
▪ Example: But if we have changed our robot to one that
moves on wheels
▪ We still want the robot to:
– Move forward
– Increase/decrease speed
– Change direction
▪ But we now implement with different methods, such as:
– Rotate wheels at defined speed
– Increase/decrease speed of motor and/or change gears
– Change relative speed each wheel
same
different
35. Encapsulation
▪ We have separated the external methods and attributes
from the internal methods and attributes.
▪ This has allowed us to keep the external facing interface
the same, while changing how we have implemented its
functionality.
▪ We have changed how we do something, without
changing what we are doing.
▪ Allow for easier modification of code.
36. Summary
Summary so far
▪ Created a class
▪ Get and set methods
▪ Constructors
▪ Private and public modifiers
▪ Encapsulation