The static Keyword. Lecture 2 Java Intermediate. The static Keyword. The Plan. Class Attributes The static Keyword. Class Methods The static Keyword

Similar documents
Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

Introduction to Classes and Objects

Chapter 5. Inheritance

Java Tutorial. Saarland University. Ashkan Taslimi. Tutorial 3 September 6, 2011

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

Java Object Oriented Design. CSC207 Fall 2014

index.pdf January 21,

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

ITI Introduction to Computing II

Introduction to Inheritance

ITI Introduction to Computing II

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

PIC 20A Number, Autoboxing, and Unboxing

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Introduction to Programming Using Java (98-388)

Chapter 2: Using Data

CST141 Thinking in Objects Page 1

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

Data Types Reference Types

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

19. GUI Basics. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

ITI Introduction to Computing II

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

ITI Introduction to Computing II

Unit 3 INFORMATION HIDING & REUSABILITY. Interface:-Multiple Inheritance in Java-Extending interface, Wrapper Class, Auto Boxing

Language Features. 1. The primitive types int, double, and boolean are part of the AP

JAVA MOCK TEST JAVA MOCK TEST II

In this lab, you will be given the implementation of the classes GeometricObject, Circle, and Rectangle, as shown in the following UML class diagram.

Full file at

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

INHERITANCE Mrs. K.M. Sanghavi

Chapter 02: Using Data

Use the scantron sheet to enter the answer to questions (pages 1-6)

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

Inheritance and Polymorphism

In this lab we will practice creating, throwing and handling exceptions.

Building custom components IAT351

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.


Inheritance and Interfaces

Software Design and Analysis for Engineers

Computer Science II (20073) Week 1: Review and Inheritance

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Example: Count of Points

Course PJL. Arithmetic Operations

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

The class diagram contains only 2 elements: LabClass and Student. The LabClass class is linked to the Student class.

String is one of mostly used Object in Java. And this is the reason why String has unique handling in Java(String Pool). The String class represents

Inheritance, and Polymorphism.

Objects and Classes. Lecture 10 of TDA 540 (Objektorienterad Programmering) Chalmers University of Technology Gothenburg University Fall 2017

CS-202 Introduction to Object Oriented Programming

Java Fundamentals (II)

Programming overview

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

CT 229 Fundamentals of Java Syntax

Lesson 3: Accepting User Input and Using Different Methods for Output

What is Inheritance?

Instance Members and Static Members

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

Overview. OOP: model, map, reuse, extend. Examples of objects. Introduction to Object Oriented Design

APCS Semester #1 Final Exam Practice Problems

Arrays Classes & Methods, Inheritance

CS121/IS223. Object Reference Variables. Dr Olly Gotel

In this Lecture you will Learn: Object Design. Information Sources for Object Design. Class Specification: Attributes

More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario

Inheritance and Polymorphism

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Data Structures and Other Objects Using C++

Example: Monte Carlo Simulation 1

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Course Description. Learn To: : Intro to JAVA SE7 and Programming using JAVA SE7. Course Outline ::

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

Another IS-A Relationship

Polymorphism and Interfaces. CGS 3416 Spring 2018

CS 520 Theory and Practice of Software Engineering Fall 2018

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

Lecture 7: Classes and Objects CS2301

Inheritance. A mechanism for specialization A mechanism for reuse. Fundamental to supporting polymorphism

Preface. The Purpose of this Book and Its Audience. Coverage and Approach

A final method is a method which cannot be overridden by subclasses. A class that is declared final cannot be inherited.

Review: Object Diagrams for Inheritance. Type Conformance. Inheritance Structures. Car. Vehicle. Truck. Vehicle. conforms to Object

Inheritance. Transitivity

Object Oriented Programming. Java-Lecture 11 Polymorphism

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

CS 1302 Chapter 9 (Review) Object & Classes

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

CSCI 355 Lab #2 Spring 2007

OVERRIDING. 7/11/2015 Budditha Hettige 82

CS 110 Practice Final Exam originally from Winter, Instructions: closed books, closed notes, open minds, 3 hour time limit.

Transcription:

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