The Plan Lecture 2 Java Intermediate The static Keyword Wrapper classes Object interaction Inheritance Dr. Tommy Yuan 1 2 The static Keyword The data in a class may exhibit different scopes, e.g. shared amongst all instances of that class - class variable local to that object instance - instance variable The static Keyword static attributes and static methods Shared Class A Object A1 Object A2 Object A3 Object A4 Local A1 Local A2 Local A3 Local A4 3 4 Class Attributes The static Keyword public void testbankaccount() //Create two bank accounts BankAccount account1 = new BankAccount account2 = new //Deposit some money account1.deposit(1000); account2.deposit(2000); //Set the interest rate account1.setinterestrate(10); account2.setinterestrate(20); //Add interest to account1 and display account1.addinterest(); System.out.println(account1.getBalance()); Class exercise: What do we get? 5 class BankAccount // the attributes private String accountnumber; private String accountname; private double balance; private static double interestrate; // the methods public void setinterestrate(double ratein) interestrate = ratein; public void addinterest() balance = balance + (balance *interestrate)/100; Class Methods The static Keyword A better design public void testbankaccount() //Create two bank accounts BankAccount account1 = new BankAccount account2 = new //Deposit some money account1.deposit(1000); account2.deposit(2000); //Set the interest rate BankAccount.setInterestRate(10); BankAccount.setInterestRate(20); //Add interest to account1 and display account1.addinterest(); System.out.println(account1.getBalance()); class BankAccount // the attributes private String accountnumber; private String accountname; private double balance; private static double interestrate; // the methods public static void setinterestrate(double ratein) interestrate = ratein; public void addinterest() balance = balance + (balance *interestrate)/100; 6 1
Class Methods The static Keyword We want to use the services of a class (i.e. call a method), without having to create an object. Here are some examples you may recognize. System.out.println(. ); Math.sqrt(x); Math.random(); JOptionPane Another Example of Static Methods Earlier we have seen the use of the Scanner class in handling terminal input/output The javax.swing.optionpane class provides prepackaged Graphical User Interface dialog boxes to get information from users and display messages showinputdialog(..) showmessagedialog(..) 7 8 JOptionPane Another Example of Static Methods 1/2 import javax.swing.joptionpane; public class GUI_IO public void basicpromptdisplay() String name = JOptionPane.showInputDialog("What is your name"); JOptionPane.showMessageDialog(null, "Hi " + name + " how do you like these dialog boxes?", "A Question", JOptionPane.QUESTION_MESSAGE ); public static void main(string args[]) GUI_IO gui=new GUI_IO(); gui.basicpromptdisplay(); JOptionPane Another Example of Static Methods 2/2 There is a problem. The showinputdialog() method will ONLY return strings. Therefore how can we use this GUI box to input other data (int, doubles) Answer Wrapper classes 9 10 Wrapper Classes Wrapper Classes Wrap around the basic type, and add some very useful methods to it. For example, those which allow conversion from one type to anothere.g. strings to numbers and vice-versa. In the java.lang package Primitive int double float char Class Integer Double Float Character Autoboxing Object o=37; Unboxing Integer io=(integer)o; int x=io; The following example shows how to convert a string to an integers by using the parseint(s) method: 11 12 2
Much of the power of Object Oriented programming lies in the ability for objects to interact with one another to deliver the overall functionality. Need to know who to interact Closely related concept is class association Self interaction One-way interaction Two-way interaction 13 14 Self interaction public class Circle public void changecolor() color = newcolor; draw(); private void draw() One way interaction Association via parameter public class Student public double consumedrink(drink drink) alcohol += drink.getlitres() * drink.getproof(); return alcohol; Public class Drink public double getlitres() public String getproof() 15 16 One way interaction, Association via attribute Patient 0..1 Consultant Composition (whole part relation) Aggregation-weaker notation public class Patient private Consultant assignedconsultant; //Methods for assign and unassign consultant public String getconsultant() String condetails; condetails = "\nconsultant Name = "+assignedconsultant.getname(); return condetails; 17 public class ClockDisplay // declare two references to NumberDisplay objects private NumberDisplay hours; private NumberDisplay minutes; private String displaystring; // simulates the actual display // Constructor to create a new clock set at the time specified by the parameters. public ClockDisplay(int hour, int minute) hours = new NumberDisplay(24); minutes = new NumberDisplay(60); settime(hour, minute); 18 3
Two-way interaction View Control View Control c =new Control (this); doit()c.m(); display() Control View v; Control (View v) this.v=v; m()v.display(); Inheritance In Java 19 20 Inheritance In Our Life In Biology Double inheritance In Law The child may not accept it. Single Inheritance In Java Inherits all the attributes and methods except constructor method overriding Inherits the type The subclass specialises Sub()super(); Shape s=new Triangle(); 21 22 Single Inheritance In Java Single Inheritance In Java Concrete Shape class public class Shape Abstract Animal class At least one abstract method Not permitted to create instances public abstract class Animal abstract public void run(); public class Circle extends Shape keyword public class Rectangle extends Shape Each concrete class should implement all inherited abstract methods public class Tortoise extends Animal public void run() keyword 23 24 4
Single Inheritance In Java Key Benefits Actor interface All methods are abstract though abstract keyword is not needed Not permitted to create instances All methods are public though public keyword is not needed All attributes are final, public and static Each concrete class should implement all inherited methods 25 public interface Actor void run(); boolean active(); public class Tortoise implements Actor keyword 1. Parent class reuse Code reuse and duplication avoidance 2. Type conformance Increasing flexibility through polymorphic variables and dynamic binding Shape s1 = new Circle(20,30,50); Shape s2 = new Triangle(); Shape s3 = new Rectangle(); Received the same message, but react differently 26 area() What are the issues with dynamic binding? Multiple Inheritance Multiple Inheritance Having a class inherit directly from multiple ancestors Key problem Ambiguities e.g. the diamond problem Does Java support multiple inheritance? D d=new D(); d.m1(); Which method should do the job? Cause: inherited code from several places (classes) 27 28 Multiple Inheritance In Java What do we actually gain by implementing interfaces? Java forbids it for classes Java permits it for interfaces No competing implementation Extends at most one class, and/or implements one or more interfaces class D extends A, B class D implements A, B A a=new D(); B b=new D(); 1. Multiple parent class reuse 2. Multiple type conformance 29 30 5
Is Java good enough? Is Java good enough? From Java Designer (Gosling and McGilton 1996 pp29) Multiple inheritance - and all the problems it generates - was discarded from Java. The desirable features of multiple inheritance are provided by interfaces Joseph says (Bergin J. 2000 ) Java is a good, sound, and complete language design that supports the kinds of things that developers need. It takes skill, however, to see how to achieve some of the less used idioms such as multiple inheritance. Convinced? How? 31 32 Aims: 1. A StudentTeacher wants to become a Teacher 2. A StudentTeacher wants to be able to grade [reuse grade()] Step 1: Separate Teacher class Step 2: Teacher talks to StudentTeacher: Now, you can become a Teacher. Go for it. 33 34 Step 3: StudentTeacher: I am a teacher now, but I don t know how to grade [reuse grade()] yet? Teacher: Ask my delegate TeacherImpl to do it for you, she knows how to do it. 35 All done! Delegation takes place 36 6
1. Multiple parent class reuse - not directly supported, but - can be simulated 2. Multiple type conformance Any side effect? See (Tempero & Biddle 1998; Bettini et al. 1999) 37 38 Homework reading Java Inheritance Summary Inheritance provides two key benefits: Parent class reuse Type conformance Java forbids multiple parent class reuse for the sake of disambiguity But can be simulated via pattern solutions, e.g. Interfacedelegation Java support multiple type inheritance via interfaces Session Summary The static Keyword Wrapper classes Object interaction Inheritance 39 40 References 1. Bettini L., Loreti M. & Venneri B. (2002). On Multiple Inheritance in Java. In Proc. of Tools Eastern Europe, Emerging Technologies, Emerging Markets. Available at [http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.13.7749] 2. Bergin J. (2000). Multiple inheritance in Java. Paice University. Available at [http://pclc.pace.edu/~bergin/patterns/multipleinheritance.html] 3. Gosling J. & McGilton H. (1996). The Java Language Environment (A White Paper). Sun Microsystems. Available at [http://java.sun.com/docs/white/langenv/] 4. Tempero E. & Biddle R. (1998). Simulating Multiple Inheritance in Java. Technical report CS-TR-98/1, Victoria University of Wellington. Available at [http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.17.834]. 41 42 7