The Plan

• The Keyword • Wrapper classes • Object interaction Lecture 2 Java Intermediate • Inheritance

Dr. Tommy Yuan

Java Refresher Java Refresher 1 2

The “static” Keyword

• The data in a class may exhibit different scopes, e.g. – shared amongst all instances of that class - – local to that object instance -

The “static” Keyword Shared Class A static attributes and static methods

Object A1 Object A2 Object A3 Object A4

Local A1 Local A2 Local A3 Local A4

Java Refresher Java Refresher 3 4

Class Attributes – The static Keyword Class Methods – The static Keyword Class exercise:What do we get? A better design public void testBankAccount() class BankAccount public void testBankAccount() class BankAccount { { { { //Create two bank accounts // the attributes //Create two bank accounts // the attributes BankAccount account1 = new private String accountNumber; BankAccount account1 = new private String accountNumber; BankAccount(); private String accountName; BankAccount(); private String accountName; BankAccount account2 = new private double balance; BankAccount account2 = new private double balance; BankAccount(); private static double interestRate; BankAccount(); private static double interestRate; //Deposit some money // the methods //Deposit some money // the methods account1.deposit(1000); public void setInterestRate(double rateIn) account1.deposit(1000); public static void setInterestRate(double rateIn) account2.deposit(2000); { account2.deposit(2000); { //Set the interest rate interestRate = rateIn; //Set the interest rate interestRate = rateIn; account1.setInterestRate(10); } BankAccount.setInterestRate(10); } account2.setInterestRate(20); public void addInterest() BankAccount.setInterestRate(20); public void addInterest() //Add interest to account1 and display { //Add interest to account1 and display { account1.addInterest(); balance = balance account1.addInterest(); balance = balance System.out.println(account1.getBalance()); + (balance *interestRate)/100; System.out.println(account1.getBalance()); + (balance *interestRate)/100; … } … } } … Java Refresher } … Java Refresher } } 5 6

1 Class Methods – The static Keyword JOptionPane – Another Example of Static Methods

• We want to use the services of a class (i.e. call a • Earlier we have seen the use of the Scanner class method), without having to create an object. in handling terminal input/output • Here are some examples you may recognize. • The javax.swing.OptionPane class provides – System.out.println(“ ….”); prepackaged Graphical User Interface dialog – Math.sqrt(x); boxes to get information from users and display – Math.random(); messages – showInputDialog(..) – showMessageDialog(..)

Java Refresher Java Refresher 7 8

JOptionPane – Another Example of Static Methods 1/2 JOptionPane – Another Example of Static Methods 2/2

import javax.swing.JOptionPane; public class GUI_IO { public void basicPromptDisplay() • There is a problem …. The showInputDialog() { String name = JOptionPane.showInputDialog("What is your name"); method will ONLY return strings. Therefore how JOptionPane.showMessageDialog(null, can we use this GUI box to input other data (int, "Hi " + name + " how do you like these dialog boxes?", doubles…) "A Question", JOptionPane.QUESTION_MESSAGE ); } • Answer …Wrapper classes public static void main(String args[]) { GUI_IO gui=new GUI_IO(); gui.basicPromptDisplay(); } }

Java Refresher Java Refresher 9 10

Wrapper Classes Wrapper Classes

• Autoboxing Object o=37; Primitive Class • Wrap around the basic type, and add some very int Integer • Unboxing Integer io=(Integer)o; useful methods to it. int x=io; double Double • For example, those • The following example shows how to convert a string to an integers by using the parseInt(s) method: which allow conversion float Float from one type to another- e.g. strings to numbers and vice-versa. char Character

• In the java.lang package … …

Java Refresher Java Refresher 11 12

2 Object Interaction

. 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 Object Interaction . Closely related concept is class association . Self interaction . One-way interaction . Two-way interaction

Java Refresher Java Refresher 13 14

Object Interaction Object Interaction

. Self interaction . One way interaction . Association via public class Student { parameter public double consumeDrink(Drink drink) public class Circle { { alcohol += drink.getLitres() * … drink.getProof(); public void changeColor() return alcohol; { } color = newColor; draw(); Public class Drink } { private void draw() public double getLitres(){…} {…} public String getProof(){…} } }

Java Refresher Java Refresher 15 16

Object Interaction Object Interaction

. One way interaction, 0..1 . Composition (whole part relation) . Association via attribute Patient Consultant . Aggregation-weaker notation

public class ClockDisplay { public class Patient { // declare two references to NumberDisplay objects private Consultant assignedConsultant; private NumberDisplay hours; //Methods for assign and unassign consultant private NumberDisplay minutes; … private String displayString; // simulates the actual display public String getConsultant() { // Constructor to create a new clock set at the time specified by String conDetails; the parameters. conDetails = "\nConsultant Name = "+assignedConsultant.getName(); public ClockDisplay(int hour, int minute) return conDetails; { hours = new NumberDisplay(24); } minutes = new NumberDisplay(60); setTime(hour, minute); Java Refresher } Java Refresher 17 18

3 Object Interaction

. Two-way interaction View { Control =new Control (this); View Control doit(){c.m();} display(…){…} }

Control Inheritance In Java { View v; Control (View v) { this.v=v; } m(){v.display(…);} }

Java Refresher Java Refresher 19 20

Inheritance In Our Life Single Inheritance In Java

. Inherits all the Sub(){super(); attributes and ...} . In Biology methods except Double inheritance . constructor …… . method overriding . Inherits the type . The subclass Shape s=new Triangle(); specialises . In Law The child may not accept it ….

Java Refresher Java Refresher 21 22

Single Inheritance In Java Single Inheritance In Java

public class Shape{ . Concrete Shape . Abstract Animal class public abstract class Animal{ ... class abstract public void run(…); } . At least one abstract method } . Not permitted to create instances

public class Circle public class Rectangle extends Shape{ extends Shape{ ...... Each concrete class public class Tortoise extends } } should implement all Animal{ inherited abstract public void run(…){…} methods } keyword keyword

Java Refresher Java Refresher 23 24

4 Single Inheritance In Java Key Benefits

1. Parent class reuse . Actor interface public interface Actor{ . All methods are abstract though void run(…); Code reuse and duplication avoidance abstract keyword is not needed boolean active(); 2. Type conformance } . Not permitted to create instances Increasing flexibility through polymorphic variables and . All methods are public though public dynamic binding keyword is not needed

. All attributes are final, public and Shape s1 = area() keyword static new Circle(20,30,50); Shape s2 = new Triangle(); Shape s3 = new Rectangle(); public class Tortoise . Each concrete class should implements Actor{ implement all inherited methods ... } Received the same message, but react differently What are the issues with dynamic binding?

Java Refresher Java Refresher 25 26

Multiple Inheritance Multiple Inheritance Having a class inherit directly from multiple ancestors

. Key problem Ambiguities e.g. the diamond problem

D d=new D(); d.m1(); Does Java support multiple inheritance? Which method should do the job?

Cause: inherited code from several places (classes)

Java Refresher Java Refresher 27 28

Multiple Inheritance In Java What do we actually gain by implementing interfaces?

. Java forbids it for classes 1. Multiple parent class reuse . Java permits it for interfaces class D extends A, B{} – No competing implementation . Extends at most one class, and/or 2. Multiple type conformance implements one or A a=new D(); more interfaces B b=new D();

class D implements A, B {}

Java Refresher Java Refresher 29 30

5 Is Java good enough? Is Java good enough?

From Java Designer Joseph says (Gosling and McGilton 1996 pp29) (Bergin J. 2000 ) “ Multiple inheritance - and all the problems it “…Java is a good, sound, and complete generates - was discarded from Java. The language design that supports the kinds of desirable features of multiple inheritance are things that developers need. It takes skill, provided by interfaces” however, to see how to achieve some of the less used idioms such as multiple inheritance.”

Convinced? How?

Java Refresher Java Refresher 31 32

Interface-delegation Technique Interface-delegation Technique

Aims: 1. A StudentTeacher wants to become a Teacher 2. A StudentTeacher wants to be able to grade [reuse grade()] Step 2: Teacher talks to StudentTeacher: Now, you can become Step 1: Separate Teacher class a Teacher. Go for it.

Java Refresher Java Refresher 33 34

Interface-delegation Technique Interface-delegation Technique

Step 3: StudentTeacher: I am a teacher now, but I don’t know how to grade [reuse grade()] yet? All done! Teacher: Ask my delegate TeacherImpl to do it for Delegation takes place you, she knows how to do it. Java Refresher Java Refresher 35 36

6 Interface-delegation Technique Interface-delegation Technique

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)

Homework reading Java Refresher Java Refresher 37 38

Java Inheritance Summary Session Summary

. Inheritance provides two key benefits: • The static Keyword . Parent class reuse • Wrapper classes . Type conformance . Java forbids multiple parent class reuse for the sake of • Object interaction disambiguity • Inheritance . But can be simulated via pattern solutions, e.g. Interface- delegation . Java support multiple type inheritance via interfaces

Java Refresher Java Refresher 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].

Java Refresher Java Refresher 41 42

7