320 likes | 362 Views
Java and OOP. Part 5 – More. More OOP. More OOP concepts beyond the introduction: constants this clone and equals inheritance exceptions reflection interfaces. Constants. final is used for classes which cannot be sub-classed Data members can also be declared final
E N D
Java and OOP Part 5 – More
More OOP • More OOP concepts beyond the introduction: • constants • this • clone and equals • inheritance • exceptions • reflection • interfaces
Constants • final is used for classes which cannot be sub-classed • Data members can also be declared final • Which means they are constants – for example • public final double π = 3.1415926; • Also note you can use Unicode in source code
this • Keyword this is a reference to the object executing the current method • Usually this can be omitted public void someMethod() { field1=99; field2=32; } field1 of the object carrying out someMethod We could have said this.field1=99;
Example of this public void putInQueue() { q.add(this); } This might be a method to place an object in a queue. The queue has a method add, and we need to pass to it a reference to the object to be added to the queue
Exercise • Set up code to do the last example. Follow these steps - • Define a Queue class. This holds objects in an array. Have 3 data members - the current size (how many objects currently in the array), a max size, and the array itself. Have a constructor which takes as argument the max size required. Have an add method which adds an object to the array, and a display method • Define a QueueableObject class. It has just one data member - which Queue object it will be stored in. It has just one method - putInQueue • In main(), make 1 Queue. Then make some Queueable objects, add them to the queue, and display the queue.
object = object? • Two distinct questions - • are 2 objects the same? (Do 2 references refer to th esame object) • do 2 objects contain equal data?
Example .equals Integer i1 = new Integer(4); Integer i2=new Integer(4); if (i1.equals(i2)) YES System.out.println("Contain same data"); if (i1 == i2) NO System.out.println("Same object");
Example = Integer i1 = new Integer(4); Integer i2=i1; if (i1.equals(i2)) YES System.out.println("Contain same data"); if (i1 == i2) YES System.out.println("Same object");
Over-riding clone public class CloneableClass { public CloneableClass(int i) { field1=i; } public CloneableClass clone() { CloneableClass newOne = new CloneableClass(field1); return newOne; } private int field1; } CloneableClass c1 = new CloneableClass(9); CloneableClass c2 = c1.clone();
Danger - why is this wrong? public class CloneableClass { public CloneableClass clone() { CloneableClass newOne = new CloneableClass(); newOne.field1=this.field1; return newOne; } public int[] field1 = {1,2,3}; }
Because.. CloneableClass c1 = new CloneableClass(); CloneableClass c2 = c1.clone(); c1.field1[1]=99; System.out.println(c2.field1[1]); // outputs 99 c2 object c1 object same array - we didn't make a new one the field1 array
Exercise • Copy the CloneableClass and fix its clone method
Exceptions • exception = unusual situation • here program cannot execute 'normally' • with a more-or-less external cause • not a program bug • eg file not found • connection with server lost • out of memory • broken Java machine
Exceptions • Some methods are declared to 'throw' an exception • Compiler will insist code 'catches' checked exception • Code form - • try { • .. call of method that may throw ExceptionType • } • catch ( ExceptionType e) • { • .. code to deal with exception • }
Example try catch FileReader fr = null; try { fr= new FileReader("test.dat"); } catch (FileNotFoundException fe) { System.out.println("Cant find file"); } FileReader is in package java.io Note declare fr outside try and initialise Else compiler complains fr may not be initialised
Exercise • A FileReader inherits a method called read • read takes a char[] as argument • Look at the documentation • Extend the code on the last slide to display the file
More on inheritance • Suppose we have a base class called BaseClass, and that SubClass extends this. • What do we get if we say: • BaseClass s = new SubClass();
More on inheritance • Suppose we have a base class called BaseClass, and that SubClass extends this. • What do we get if we say: • BaseClass s = new SubClass(); • Then s is an object which is 'really' a SubClass • But its been declared to be a BaseClass • What happens? • We get the subclass methods, but • The base class fields • For example
Example public class BaseClass { public void method() { System.out.println("Base class method"); } public int field=1;} public class SubClass extends BaseClass { public void method() { System.out.println("Subclass method"); } public int field = 2; } BaseClass s = new SubClass(); s.method(); System.out.println(s.field); outputs: Subclass method 1
Reflection • Sometimes your code must deal with objects when you do not know what type they are • Reflection enables you to ask an object what class it is • A Class object carries info about a class • The Object class has a method called getClass • So all classes have this - eg BaseClass s = new SubClass(); Class theClass= s.getClass(); System.out.println(theClass); .. outputs class test.SubClass (SubClass was defined in package test)
Using Class objects • This example shows how we can trace up a class hierarchy • See the doc of Class for more info • public static void main(String[] args) { • BaseClass s = new SubClass(); • Class theClass= s.getClass(); • upTree(theClass); • } • public static void upTree(Class someClass) • { • if (someClass==null) return; • System.out.println(someClass); • upTree(someClass.getSuperclass()); • } • output: • class test.SubClass • class test.BaseClass • class java.lang.Object
Reflection exercise • Look at the doc of Class • Use Class.forName and .getMethods to output the methods of a given class • Note .forName needs package eg • theClass= Class.forName("java.lang.Class"); • and need to catch exception
No multiple inheritance • In some languages (C++) a class can inherit from more than one super class • Called multiple inheritance • Cannot do it in Java • Idea of interface kind of substitute • Enables a class to 'be like' more than one class interface • Interfaces heavily used in Swing - simpler than what follows..
What is an interface • Like a ghostly class • An interface has a set of methods (names, arguments, return types) • The interface declares but does not define the methods • A class can be declared to implement the interface • It must then define the methods in the interface • Or the compiler will complain • Classes can implement several interfaces
Example interface • Comparable • just one method - • int compareTo(Object obj) • should return negative, 0 or positive depending on whether obj comes before, is =, or comes after
Example implementation public class Order implements Comparable { public Order(double amount, int id, int day, int month, int year) { value=amount; key = id; date=new GregorianCalendar(); date.set(year, month, day); } public int compareTo(Object obj) { Order otherOne = (Order) obj; return date.compareTo(otherOne.date); } private GregorianCalendar date; private double value; private int key; } Calendar implements Comparable
Using a Comparable class Order order1 = new Order(34.50, 1, 2, 1, 2004); Order order2 = new Order(44.50, 2, 1, 1, 2004); System.out.println(order1.compareTo(order2)); get 1 Exercise Copy the Order class Change it so it compares on order value not order date Test it
Variables of interface type • You can declare variables of a type which is interface not a class eg • Comparable someObj; • But you can't refer to any method other than that in the interface • Enables you to write routines which work on any object which implements the interface • So you could write a Sorter class which would sort arrays of any Comparable type (like a template in C++):
Example : the Sorter class public class Sorter { public static void sort(Comparable[] things) { .. .. the sort method.. } } in use.. String[] array = {"ppp", "a", "aaa", "ccc"}; Sorter.sort(array); for (int i = 0; i<array.length; i++) System.out.println(array[i]); output - a aaa ccc ppp
Exercise • Copy the Sorter class • Fill in the sort method eg a bubble sort • Check it works • Check it works with arrays of other Comparable types eg Integer