CP4044 Lecture 5 1 Classes Lecture 5 Object-Orientation Object-oriented design (OOD) Models real-world objects Models communication among objects Encapsulates data (attributes) and functions (behaviors) Information hiding Communication through well-defined interfaces Object-oriented language Used to implement OO designs Programming is called object-oriented programming (OOP) Java We will not be looking at OO in depth just enough to facilitate systems programming in Java CP4044 Lecture 5 2 State and Behaviour Attributes define the state of an object Called instance variables in Java Attributes have a name, type and value e.g. a car might have an attribute with the name bodycolour of type colour and has the value red Methods define the behaviour of an object Similar to functions or procedures in other programming languages Methods have names that should indicate their behaviour e.g. a car might have a method moveforward CP4044 Lecture 5 3 Classes Definition Every object belongs to a group of objects of the same type called the object s class. A class defines the types of states and behaviour belonging to a group of objects Examples My Ferrari Belongs to the car class Wolverhampton Wanderers Football club class MT008 Lecture theatre class CP4044 Lecture 5 4 Object vs. Classes Class A template that defines attributes and methods Written by programmer as part of program Cannot be altered during program execution Is named by a class name Object Must belong to some class Exists whilst the program is executing Must be declared and constructed by a program Has attributes with values and methods that can execute Class defines these Referenced by an identifier (variable name) CP4044 Lecture 5 5 Instance Variables Scope: Instance variables may be accessed by all the methods in the class Variables declared in methods are local to the method and cannot be seen outside it more on this next week. All variables in Java must be initialised before use When a class is instantiated (i.e. object is created) the default values of its variables are 0 or null This is not the case with local variables, as we shall CP4044 Lecture 5 6
CP4044 Lecture 5 7 Creating Objects An object is an instance of a class An object is constructed or instantiated from a class Instantiation is done with the new operator An object reference is used to refer to an object Declaration of a TV object reference called mytv Construction and assignment of a TV object TV mytv; mytv = new TV(); new Operator TV constructor Parameters Used for passing data to a method Return type Defines the type of data to be passed from the method. Keyword void is used here if methods returns no data. Anatomy of a Method int calculatearea(int w, int h) { int area = w * h; return area; Return statement Used for passing data from the method. Omitted for void methods CP4044 Lecture 5 8 Parameters values Are used to transfer data to a method Return value Contains the data passed from the method. Here it is copied into a variable Calling a Method int calculatearea(int w, int h) { int area = w * h; return area; int area; area = calculatearea(2, 5); System.out.println("Area =" + area); A non-void method can be called anywhere an expression of the same type is permitted. e.g. from within calculations CP4044 Lecture 5 9 Overloaded Methods It is possible to have more than one method with the same name. Called overloading methods Must have different parameter types Must have the same return type double calculatecost(double price) { double taxrate = 1.175; return price * taxrate; Method uses default tax rate double calculatecost(double price, double taxrate) { return price * taxrate; User specifies tax rate CP4044 Lecture 5 10 Accessing Methods and Attributes An object reference acts as an alias for an object Object references can be used to access instance variables and methods Object-reference.variable-name Object-reference.method-name Examples: mytv.channel = 1; Sets the channel instance variable of the mytv object to the value 1 mytv.press2(); Calls the press2 method of the mytv object CP4044 Lecture 5 11 Types of Variables & Scope Instance variables Defined inside a class, but outside all methods Used to store the state of an object Can be accessed from any method in the class Automatically initialised - given default values Parameter variables Defined in a method header Used to pass data to a method Can only be accessed from the method they are defined in Initialised by values from the caller Local variables Defined inside a method Used for storing intermediate/temporary values Can only be accessed from the method they are defined in Must be explicitly initialised before they can be used CP4044 Lecture 5 12
CP4044 Lecture 5 13 Resolving Ambiguity The this reference points to the current object. this.name therefore references the instance variable called name belonging to the current object. Constructors Constructors Similar to methods and invoked when an object is created Used to perform additional initialisation Constructor has same name as class No return type Can be overloaded This line copies the value from the parameter variable to the instance variable. class Person { String name; void setname(string name) { this.name = name; Default Constructor Constructor without parameters Invoked if no other constructor is specified when object is created Automatically created by Java if not explicitly declared CP4044 Lecture 5 14 Default Constructors Constructors are like methods: But have no return type (not even void) Must have exactly the same name as the class Can be overloaded Default constructor has no parameters Used to give initial values to instance variables If you do not supply a default constructor, the compiler will generate one for you. But its behaviour might not be what you want Parameterised Constructors Parameterised constructors require the caller to supply parameters Parameters are used to initialise instance variables Saves the caller calling update methods just after the default constructor This is what you have to do in some semi-oo languages such as VB 6. Constructor uses similar syntax to update methods The this reference is used to resolve ambiguity Can have various different overloaded versions of constructors for complex classes Allow the user to specify some parameters, but use defaults for others. CP4044 Lecture 5 15 CP4044 Lecture 5 16 House Class House Class Instance variables 1 2 3 class House { int number; String street; 1 2 3 class House { int number; String street; 13 14 15 int getnumber() { return number; Default constructor Parameterised constructor 4 House() { 5 number = 0; 6 street = "not known"; 7 8 House(int number, 9 String street) { 10 this.number = number; 11 this.street = street; 12 13 4 5 6 7 8 9 10 11 12 House() { number = 0; street = "not known"; House(int number, String street) { this.number = number; this.street = street; 16 17 18 void setnumber(int number){ this.number = number; 19 String getstreet() { 20 return street; 21 22 void setstreet(string street){ 23 this.street = street; 24 25 CP4044 Lecture 5 17 CP4044 Lecture 5 18
CP4044 Lecture 5 19 Data Integrity Problems We cannot trust users of our classes to use them in the way we intended. The internal state of an object get damaged We need to maintain the integrity of the data TV ison : boolean channel : int TV() TV kevstv; kevstv = new TV(); kevstv.channel = 2; Data Hiding Ensure integrity of the data Other classes cannot directly access the data, thus cannot corrupt it. Hide internal workings of class Provides a minimal interface. Reduces complexity when using the class or visualising a whole system. Others can treat class as a black box. They don t need to know how it works, just assume it meets specifications. TV kevstv; kevstv = new TV(); kevstv.channel = -768; We need to make sure the channel is between 1 and 3 CP4044 Lecture 5 20 Public and Private Members Instance variables and methods are preceded with public or private keywords. Defines the interface between the class and other classes. i.e. the means of communication private class members May only be accessed from the class itself. Public and Private Members public class Person { private String name; public Person () { this.name = "unknown"; public void setname(string name) { this.name = name; public String getname() { return name; public class members May be accessed from any class. invalid Person p1 = new Person(); p1.name = "Billy"; valid Person p1 = new Person(); p1.setname("billy"); CP4044 Lecture 5 21 CP4044 Lecture 5 22 Protected Members In some examples you will see protected in place of public or private. This is something we are not ready to cover yet. For now assume protected does the same thing as private. This is effectively what it does for the types of programs we are looking at on this module. Rules for Data Hiding Don t allow direct external access to instance variables. Make all instance variables private. Provide public methods to access data. Validate data before assigning to instance variables. Provide other methods on a need to know basis. Only make public the methods useful outside the class. Keep the interface as simple as possible. CP4044 Lecture 5 23 CP4044 Lecture 5 24
CP4044 Lecture 5 25 Rational Number Class Worked Example Development of a Rational Class For storing fractions, e.g. 1/7 Cannot be stored accurately as floating point numbers Store as a pair of integers Class provides methods for operating on rational numbers CP4044 Lecture 5 26 Rational Number Operators Test Harness public class RatDemo1 { RatNumber k = new RatNumber(3, 4); k.show(); Object construction Method call We should reduce results to their lowest terms (50, 100) (1,2) CP4044 Lecture 5 27 CP4044 Lecture 5 28 Rational Number Class public class RatNumber { int num; int den; public RatNumber(int x, int y) { num = x; den = y; Instance variables constructor Results C:\>javac RatNumber.java C:\>javac RatDemo1.java C:\>java RatDemo1 (3/4) public String tostring() { return "(" + num + "/" + den + ")"; Method CP4044 Lecture 5 29 CP4044 Lecture 5 30
CP4044 Lecture 5 31 New Test Harness public class RatDemo { RatNumber k, l, m; k = new RatNumber(3, 4); l = new RatNumber(5, 6); m = k.add(l); System.out.println( m.tostring() ); Call by value Add Method Implementation public RatNumber add(ratnumber a) { result = new RatNumber(0,0); result.num = num * a.den + a.num * den; result.den = den * a.den; return result; (38/24) CP4044 Lecture 5 32 Alternative Add Method Implementation public RatNumber add(ratnumber a) { return new RatNumber( num * a.den + a.num * den, den * a.den); CP4044 Lecture 5 33 Adding an Integer to a Rational public RatNumber add(int a) { return new RatNumber(num + a * den, den); public class RatDemo { RatNumber k, l, m; k = new RatNumber(3, 4); l = new RatNumber(5, 6); m = K.add(L); System.out.println( m ); m = m.add(2); System.out.println( m ); (38/24) (86/24) CP4044 Lecture 5 34 Simplification private RatNumber simplify(ratnumber a) { int gcd; gcd = euclid(a.num, a.den); a.num /= gcd; a.den /= gcd; return a; private int euclid(int a, int b) { if (b == 0) return a; else return euclid(b, a % b); CP4044 Lecture 5 35 Euclid is a Recursive Method private int euclid(int a, int b) { if (b == 0) return a; euclid(27,45) else return euclid(45,27) return euclid(b, a % b); euclid(45,27) return euclid(27,18) euclid(27,18) return euclid(18,9) euclid(18,9) return euclid(9,0) euclid(9,0) return 9 CP4044 Lecture 5 36
CP4044 Lecture 5 37 Simplification public RatNumber add(ratnumber a) { return simplify (new RatNumber( num * a.den + a.num * den, den * a.den)); public RatNumber add(int a) { return simplify ( new RatNumber(num + a * den, den)); Array of Rationals public class RatDemo { RatNumber[] nums; nums = new RatNumber[10]; (3/6) (4/7) (5/8) 0.5 0.571428 0.625 for (int i = 0; i < 10; i++) { (3/9) 0.333333 int j = i % 3; (4/10) 0.4 nums[i] = new RatNumber(j + 3, i + 6); (5/11) 0.454545 for (int i = 0; i < 10; i++) System.out.println(nums[i].toString() (3/12) 0.25 (4/13) 0.307692 (5/14) 0.357142 +"\t"+nums[i].todouble() );(3/15) 0.2 CP4044 Lecture 5 38 Sorting import java.util.arrays; Arrays.sort( array, comparator ); public interface Comparator<T> { public abstract int compare( T obj1, T obj2 ); public abstract boolean equals(object obj); CP4044 Lecture 5 39 Sorting import java.util.comparator; public class AscOrder implements Comparator<RatNumber> { // Method to compare RatNumber objects. public int compare(ratnumber a, RatNumber b) { return (a.num * b.den)-(a.den * b.num); Define the method compare( a, b ) to return +ve int if a > b -ve int if a < b 0 if a equals b CP4044 Lecture 5 40 Sorted RatNumber Objects Arrays.sort(nums, new AscOrder); System.out.println("Ascending order"); for(int i=0;i<10;i++) System.out.println(nums[i]+"\t"+nums[i].toDecimal(); Ascending order: (3/15) 0.2 (3/12) 0.25 (4/13) 0.3076923076923077 (3/9) 0.3333333333333333 (5/14) 0.35714285714285715 (4/10) 0.4 (5/11) 0.45454545454545453 (3/6) 0.5 (4/7) 0.5714285714285714 (5/8) 0.625 CP4044 Lecture 5 41 Summary Object orientation State and behavior Data hiding public and private member variables Instantiating a class - objects User-defined classes Constructors, instance variables, methods Developing a class - RatNumber Using a Test Harness to develop a class Sorting arrays CP4044 Lecture 5 42