Download presentation
Presentation is loading. Please wait.
1
Lecture 2 Objects and Classes
EE2E1. JAVA Programming Lecture 2 Objects and Classes
2
Contents Using existing classes Creating new classes
private/public access Implementation/interface Constructors this object reference Objects as function arguments static methods
3
Using existing classes
We have already seen examples of classes in Java System Math Arrays String There are 100’s more which come with all the various Java API’s These classes are grouped into packages The documentation for all Java classes is at
4
Example Java provides a Date class for representing the time and date
Date date = new Date(); // Initialized to current // time and date Effectively, object date is a pointer to a Date variable Date Friday Oct 16, 2004 12:07pm date
5
Class methods (member functions)
These specify the functionality of the class They are called through the object name Date date = new Date(); int h=date.getHours(); int m=date.getMonth();
6
We can think of these methods as operating on the objects – they are called through the object variable name Date date Friday Oct 16, 2004 12:07pm Date date = new Date(); int h=date.getHours(); // returns 12 int m=date.getMonth(); // returns 10 The object has to exist before one of its methods can be called
7
Creating new classes A class consists of class methods and instance fields Methods specify the functionality of the class (what we can do with objects of the class) Instance fields specify the state of the objects
8
Example A StudentInfo class is used to store student records information 2 (public) methods StudentInfo(..) – a method with the same name as the class, known as a constructor printInfo() 3 (private) instance fields name idNumber address
9
public class StudentInfo
{ public StudentInfo(String n, int id, String a) name=new String(n); idNumber=id; address=new String(a); } public void printInfo() System.out.println(name + “ ”+ idNumber + “ ” address); private String name; private int idNumber; private String address;
10
public class StudentInfoTest
{ public static void main(String[] args) StudentInfo si1=new StudentInfo(“John Smith”, 3429, “21 Bristol Rd”); StudentInfo si2=new StudentInfo(“Alan Jones”, 5395, “30 Bournbrook Rd”); si1. printInfo(); si2.printInfo(); }
11
StudentInfoTest class creates StudentInfo objects using the new operator
The constructor is automatically called from the new StudentInfo(…) statement Calling the constructor initializes the objects Method printInfo() called from the 2 object variables si1 and si2 Class StudentInfoTest is made public which gives it public scope. The class is visible outside of its package.
12
private/public access
Keyword private means only methods in the StudentInfo class can access these fields Keyword public means the method can be called from any other method in any other class
13
Accessed from anywhere StudentInfo
public StudentInfo() printInfo() private Accessed only by String name int idNumber String address
14
Generally, instance fields are private
They represent the implementation of the class Methods are generally public They represent the interface to the class The separation of a class into public/private is a key feature of object-oriented programming Sometimes known as encapsulation in OO circles
15
Implementation/interface (state/behaviour)
The implementation of a class is specified in the private instance fields They are hidden from outside the class The interface to the class is specified by the public methods They can be accessed from anywhere The implementation may change but the interface must stay the same
16
Example Class Point represents the position in the 2D (x-y) plane
{ public Point(int x, int y) { xpos=x; ypos=y;} public int getX() { return xpos;} public int getY() { return ypos; } private int xpos, ypos; }
17
Suppose this class is used to represent a polygon as an array of points – also includes a method to compute the perimeter The x and y co-odinates are accessed through methods getX() and getY()
18
class Polygon { public Polygon() {…} public double perimeter() double pm=0; int nn; for (int n=1; n<numVertices; n++) int xv1= vertices[n-1].getX(); int yv1=vertices[n-1].getY(); nn=n%numVertices; int xv=vertices[nn].getX(); int yv=vertices[nn].getY(); pm+=(Math.sqrt((xv1-xv)*(xv1-xxv)+(yv1-yv)*(yv1-yv))); } return pm; private Point[] vertices; private int numVertices;
19
The key point is that we can change the implementation of Point to use polar co-ordinates
The implementation of the Polygon class (and in particular the perimeter() method) doesn’t change We have created a re-useable software component Point
20
class Point { public Point(int x, int y) r=Math.sqrt(x*x+y*y); theta=Math.atan2(y,x); } public int getX() return r*Math.cos(theta); public int getY() return r*Math.sin(theta); private float r, float theta;
21
Constructors Constructors are special methods for initialising an object It must have the same name as the class and not have a return type Constructors can be overloaded A class can have several constructors with different arguments
22
Example An Employee class can be used to store information about employees in a company Constructor Employee() is the default constructor Used for creating un-initialized objects Constructor Employee(String, int) initializes the instance fields name and age EmployeeTest class creates Employee objects using both constructors
23
class Employee { public Employee() // default constructor {} public Employee(String n, int a) name=new String(n); age=a; } private String name; private int age;
24
public class EmployeeTest
{ public static void main(String[] args) Employee emp=new Employee(); // default cnstr. Employee emp1=new Employee(“John Smith”,35); }
25
The this object reference
Allows access to the current object as a whole and not just particular instance fields The keyword this refers to the object on which the method operates One simple use of this is to force the default constructor to call another constructor There are many other uses for this
26
class Employee { public Employee() // default constructor this(“No name”, 0); // Call other constructor } public Employee(String n, int a) name=n; age=a; private String name; private int age;
27
Objects as function arguments
Object names are references (pointers!) to the objects It is tempting to think that object arguments to functions are effectively passed by reference This means that objects can be changed inside functions Unfortunately this is wrong – the object references are passed by value!! The object state can be changed by calling mutator methods of the object inside the function
28
class Employee { public Employee() {}// default constructor public Employee(String n, int a) name=new String(n); age=a; } public void incrementAge() {age++;} private String name; private int age;
29
class changeEmployeeDetails
{ static void swap(Employee e1, Employee e2) Employee temp=e2; e2=e1; e1=temp; } static void incrementAge(Employee e) e.incrementAge();
30
public class EmployeeTest
{ public static void main(String[] args) Employee emp=new Employee(“John Smith”,35); Employee emp1=new Employee(“John Smith”,36); // Update age? changeEmployeeDetails.swap(emp,emp1); // emp.age still 35! // Update age changeEmployeeDetails.incrementAge(emp); // emp.age now 36 }
31
In the first case, the swap() method doesn’t change the state of the object
After the method is called, emp still refers to the 35 y/o John Smith The object references are passed by value and hence don’t change on exit from the function
32
Start of swap() In swap Employee emp John Smith 35 Employee emp1
36 In swap e1 e2
33
End of swap() In swap Employee emp John Smith 35 Employee emp1
36 In swap e1 e2
34
In the second case, incrementAge() is a mutator method which changes the age instance field of an Employee object Method incrementAge() in class changeEmployeeDetails() can then update the age of the Employee object passed by reference The object reference has not been changed, just the object’s internal state
35
Static methods Static methods belong to the class and are called through the class name We have already seen examples of static methods Console.readDouble() Math.pow(x,y) Arrays.sort() We don’t need to create an object (instantiate the class) in order to call a static method The main() method in a class is static which means the Java interpreter can start the main() method without creating an object public static void main(String[] args)
36
Static methods cannot access the instance fields (which belong to objects)
classes can also have static fields, which again belong to the class and not the objects These are typically constants defined in the context of the class Example – the Color class has 13 public static fields representing colour constants – Color.black, Color.red etc
37
class MyClass private int n; private static int m=15; public MyClass(int nn) {n=nn;} MyClass obj1=new Myclass(10); MyClass obj2=new Myclass(20); obj1 obj2 n=10 n=20
38
Example Static methods cannot access non-static instance fields – vice versa is OK A common error is to try and access a non-static from main public class SayHello { public static void main(String[] args) System.out.println(message); // Error! message non-static } private String message=“Hello”;
39
The static method main cannot access the non-static instance field message
Need to declare message as static for this program to work private static String message=“Hello”;
40
And finally….. There has been a lot of detail in this lecture
Its important to appreciate the significance of encapsulation – implementation/interface as well as the difference between static and non-static members In the first assessed programming lab exercise, you will have to design and implement a number of classes to create a relatively sophisticated application
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.