Overloading Example. Overloading. When to Overload. Overloading Example (cont'd) (class Point continued.)

Similar documents
Java. GUI building with the AWT

GUI in Java TalentHome Solutions

CHAPTER 2. Java Overview

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages.

SD Module-1 Advanced JAVA

SD Module-1 Advanced JAVA. Assignment No. 4

encompass a group of features for building Graphical User Interfaces (GUI).

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Computer Programming Java AWT Lab 18

Java Applets / Flash

The Java Programming Language Basics. Identifiers, Keywords, and Types. Expressions and Flow Control. Object-Oriented Programming. Objects and Classes

GUI Event Handlers (Part I)

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Packages: Putting Classes Together

Systems Programming Graphical User Interfaces

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

CSE 331. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Introduction. Introduction

CS-202 Introduction to Object Oriented Programming

CS11 Java. Fall Lecture 3

UNIT-3 : MULTI THREADED PROGRAMMING, EVENT HANDLING. A Multithreaded program contains two or more parts that can run concurrently.

Practice for Chapter 11

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

Objective Questions. BCA Part III Paper XIX (Java Programming) page 1 of 5

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline

Java: introduction to object-oriented features

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling

CSE 331. Event- driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Table of Contents. Chapter 1 Getting Started with Java SE 7 1. Chapter 2 Exploring Class Members in Java 15. iii. Introduction of Java SE 7...

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing.

User interfaces and Swing

Chapter 5 Object-Oriented Programming

Graphic User Interfaces. - GUI concepts - Swing - AWT

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008

CONTENTS. Chapter 1 Getting Started with Java SE 6 1. Chapter 2 Exploring Variables, Data Types, Operators and Arrays 13

Handout 14 Graphical User Interface (GUI) with Swing, Event Handling

2. (True/False) All methods in an interface must be declared public.

Dr. Hikmat A. M. AbdelJaber

Datenbank-Praktikum. Universität zu Lübeck Sommersemester 2006 Lecture: Swing. Ho Ngoc Duc 1

Introduction to the JAVA UI classes Advanced HCI IAT351

8. Polymorphism and Inheritance

Java for Programmers Course (equivalent to SL 275) 36 Contact Hours

Inheritance and Polymorphism

Lecture 5: Java Graphics

The AWT Event Model 9

Programming graphics

Introduction to Programming Using Java (98-388)

G51PRG: Introduction to Programming Second semester Applets and graphics

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing

COMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed

Object Oriented Java

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

BASICS OF GRAPHICAL APPS

15CS45 : OBJECT ORIENTED CONCEPTS

Previously, we have seen GUI components, their relationships, containers, layout managers. Now we will see how to paint graphics on GUI components

Inheritance (cont.) Inheritance. Hierarchy of Classes. Inheritance (cont.)

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

G Programming Languages - Fall 2012

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

EXCEPTIONS & GUI. Errors are signals that things are beyond help. Review Session for. -Ankur Agarwal

Declarations and Access Control SCJP tips

Chapter 1 GUI Applications

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

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

Java Programming Lecture 6

Chapter 7: A First Look at GUI Applications

Window Interfaces Using Swing Objects

Java Mouse Actions. C&G criteria: 5.2.1, 5.4.1, 5.4.2,

Java Object Oriented Design. CSC207 Fall 2014

What is Inheritance?

Class, Variable, Constructor, Object, Method Questions

Inheritance (continued) Inheritance

CS260 Intro to Java & Android 03.Java Language Basics

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

CS Exam 1 Review Suggestions

AWT DIALOG CLASS. Dialog control represents a top-level window with a title and a border used to take some form of input from the user.

Supporting Materials

CSCE3193: Programming Paradigms

DM503 Programming B. Peter Schneider-Kamp.

Advanced Java Programming (17625) Event Handling. 20 Marks

Which of the following syntax used to attach an input stream to console?

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries

ITI Introduction to Computing II

Essential Series. Springer-Verlag London Ltd.

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

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

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

Programming Mobile Devices J2SE GUI

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

ITI Introduction to Computing II

Contents. iii Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services August 1998, Revision B

5. In JAVA, is exception handling implicit or explicit or both. Explain with the help of example java programs. [16]

PIC 20A GUI with swing

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Transcription:

Overloading Each method has a signature: its name together with the number and types of its parameters Methods Signatures String tostring() () void move(int dx,int dy) (int,int) void paint(graphicsg) (Graphics) Two methods can have the same name if they have different signatures. They are overloaded. public class Point { Overloading Example protected double x, y; public Point() { x = 0.0; y = 0.0; public Point(double x, double y) { this.x = x; this.y = y; /**calculate the distance between this point and the other point */ public double distance(point other) { double dx = this.x - other.x; double dy = this.y - other.y; return Math.sqrt(dx * dx + dy * dy); Overloading Example (cont'd) (class Point continued.) /**calculate the distance between this point and (x,y)*/ public double distance(double x, double y) { double dx = this.x - x; double dy = this.y - y; return Math.sqrt(dx * dx + dy * dy); /**calculate the distance between this point and the origin*/ public double distance() { return Math.sqrt(x * x + y * y); // other methods When to Overload When there is a general, non-discrimitive description of the functionality that can fit all the overloaded methodes. public class StringBuffer { StringBuffer append(string str) {... StringBuffer append(boolean b) {... StringBuffer append(char c) {... StringBuffer append(int i) {... StringBuffer append(long l) {... StringBuffer append(float f) {... StringBuffer append(double d) {... //...

When to Overload (cont'd) When all the overloaded methods offer exactly the same functionality, and some of them provide default values for some of the parameters. public class String { public String substring(int i, int j) { // base method: return substring [i.. j-1] public String substring(int i) { // provide default argument return substring(i, length - 1); //... Inheritance and Extended Classes Extended classes are also known as subclasses. Inheritance models the is-a relationship. If class E is an extended class of class B, then any object of E can act-as an object of B. Only single inheritance is allowed among classes. All public and protected members of a super class are accessible in the extended classes. All protected members are also accessible within the package. Constructors of Extended Classes The constructor of the super class can be invoked. super(...) must be the first statement. If the super constructor is not invoked explicitly, by default the no-arg super() is invoked implicitly. You can also invoke another constructor of the same class. Constructors of Extended Classes (cont'd) public class ColoredPoint extends Point { public Color color; public ColoredPoint(double x, double y, Color color) { super(x, y); this.color = color; public ColoredPoint(double x, double y) { this(x, y, Color.black); // default value of color public ColoredPoint() { color = Color.black;

Default Constructor of Extended Classes Default no-arg constructor is provided: public class Extended extends Super { public Extended() { super(); // methods and fields Execution Order of Constructors public class Super { int x =...; // executed first public Super() { x =...; // executed second //... public class Extended extends Super { int y =...; // executed third public Extended() { super(); y =...; // executed fourth //... Overriding and Hiding Overloading More than one methods have the same name but different signatures Overriding Replacing the implementation of a methods in the superclass with one of your own. You can only override a method with the same signature. You can only override non-static methods. Hiding Fields and static methods can not be overridden. They can only be hidden. Hidden fields and static methods are still accessible via references to the superclass. A static method can be only be hidden by another static method. A static variable may be hidden by an instance variable. Overriding and Hiding (cont'd) Which implementation is used? When invoking a non-static method, the actual class of the object determines. (run-time) When accessing a field, the declared type determines. (compile time) When invoking a static method, the declared type determines. (compile time)

Object Reference: super Keyword super is an reference to the current object but acts as an instance of its superclass. Consider the equals() method in ColorPoint public boolean equals(object other) { if (other!= null && other instanceof ColorPoint) { ColorPoint p = (ColorPoint) other; return (super.equals(p) && p.color.equals(this.color)); else { retrrn false; Type Conversion --- Implicit Java allows two kinds of implicit type conversions: Numeric variables Any numeric types can be converted to another numeric type with larger range, e.g. char ==> int, int ==> long, int ==> float, float ==> double. Object reference An object reference of class C can be converted to a reference of a superclass of C. Type Conversion --- Explicit Cast Numeric variables Any numeric types can be explicitly cast to any other numeric type. May lose bits, precision. Object reference Cast an object reference of a class to a reference of any other class is: syntactically allowed; but runtime checked. Cast Object References class Student {... class Undergraduate extends Student {... class Graduate extends Student {... Student student1, student2; student1 = new Undergraduate(); // ok student2 = new Graduate(); // ok Graduate student3; student3 = student2; // compilation error student3 = (Graduate) student2; // explicit cast, ok student3 = (Graduate) student1; // compilation ok // run-time exception

Graphical User Interfaces (GUI) Abstract Windows Toolkit (AWT): java.awt GUI elements: Primitive Button, Label, Checkbox, Scrollbar, etc. Container Panel, Frame, Dialog, etc. Layout managers: FlowLayout, BorderLayout, etc. Supporting classes: Event handling java.awt.event package Graphics Color, Font, Graphics, etc. Geometry Point, Rectangle, Dimension, etc. Imaging Image class and java.awt.image package The Component Hierarchy The Swing Components Layout Managers The layout of the elements in a container is handled by the layout manager associated with the container. Relative positions of the elements are specified, not their absolute coordinates. The positions and sizes of the element will be automatically adjusted when the window is resized.

The Layout Manager Hierarchy Buttons and Flow Layout width=400 height=50 width=100 height=120 Buttons and Flow Layout (cont'd) Border Layout Layout elements in horizontal rows. import java.awt.*; import java.applet.applet; public class Flow extends Applet { public Flow () { setlayout(new FlowLayout()); add(new Button("Java")); add(new Button("C++")); add(new Button("Perl")); add(new Button("Ada")); add(new Button("Smalltalk")); add(new Button("Eiffel"));

Border Layout (cont'd) import java.awt.*; import java.applet.applet; public class Border extends Applet { public Border () { setlayout(new BorderLayout()); add(new Button("North"), BorderLayout.NORTH); add(new Button("South"), BorderLayout.SOUTH); add(new Button("East"), BorderLayout.EAST); add(new Button("West"), BorderLayout.WEST); add(new Button("Center"), BorderLayout.CENTER); row=3 col=2 row=1 col=0 Grid Layout row=0 col=1 Grid Layout (cont'd) Grid Layout (cont'd) import java.awt.*; import java.applet.applet; public class Grid extends Applet { public void init () { int row = 0, col = 0; String att = getparameter("row"); if (att!= null) row = Integer.parseInt(att); att = getparameter("col"); if (att!= null) col = Integer.parseInt(att); if (row == 0 && col == 0) { row = 3; col = 2; (class Grid continued.) setlayout(new GridLayout(row, col)); add(new Button("Java")); add(new Button("C++")); add(new Button("Perl")); add(new Button("Ada")); add(new Button("Smalltalk")); add(new Button("Eiffel"));

Nested Panels Nested Panels (cont'd) public class NestedPanels extends Applet { protected Label messagebar; protected Choice choice; public NestedPanels () { // set up the center panel Panel center = new Panel(); center.setlayout(new BorderLayout()); center.add(new Button("south"), BorderLayout.SOUTH); center.add(new Button("north"), BorderLayout.NORTH); center.add(new Button("east"), BorderLayout.EAST); center.add(new Button("west"), BorderLayout.WEST); center.add(new Button("center"), BorderLayout.CENTER); Nested Panels (cont'd) (class NestedPanels continued.) // set up the south panel Panel south = new Panel(); south.setlayout(new FlowLayout()); south.add(new Button("Help")); choice = new Choice(); choice.additem("one"); choice.additem("two"); choice.additem("three"); choice.additem("four"); choice.additem("five"); south.add(choice); messagebar = new Label("This is a message bar."); south.add(messagebar); Nested Panels (cont'd) (class NestedPanels continued.) // set up the outer panel setlayout(new BorderLayout()); add(new Button("North"), BorderLayout.NORTH); add(new Button("East"), BorderLayout.EAST); add(new Button("West"), BorderLayout.WEST); add(south, BorderLayout.SOUTH); add(center, BorderLayout.CENTER);

Event Handling Event source: buttons, checkboxes, choices Event listener: any class interested in handling certain events A listener must implement an appropriate listener interface; inform the source that it is interested in handling a certain type of events. A listener may listen to several sources and different types of events. The source may also be the listener. Listeners can be full-fledged classes or inner classes. The Event Object and Listener Classes ActionEvent ActionListener ItemEvent ItemListener MouseEvent MouseListener MouseMotionListener MouseAdapter MouseMotionAdapter KeyEvent KeyListener KeyAdapter WindowEvent WindowListener WindowAdapter XyzListener are interfaces. XyzAdapter are classes that implement the corresponding listener interfaces. Nested Panels, Handling Events import java.awt.*; import java.awt.event.*; public class NestedPanels2 extends NestedPanels implements ActionListener, ItemListener { public NestedPanels2() { super(); // create all the components // register item listener choice.additemlistener(this); // register action listener registerbuttonhandler(this); <Event handling methods> <Method registerbuttonhandler()> Event Handling Methods public void itemstatechanged(itemevent event) { if (event.getstatechange() == ItemEvent.SELECTED) { messagebar.settext("choice selected: " + event.getitem()); public void actionperformed(actionevent event) { Button source = (Button) event.getsource(); messagebar.settext("button pushed: " + source.getlabel());

Register The Listener protected void registerbuttonhandler(component comp) { if (comp!= null) { if (comp instanceof Button) { Button button = (Button) comp; button.addactionlistener(this); else if (comp instanceof Container) { Container container = (Container) comp; int n = container.getcomponentcount(); for (int i = 0; i < n; i++) registerbuttonhandler( container.getcomponent(i)); Event Handling Using Inner Class import java.awt.*; import java.awt.event.*; public class NestedPanels3 extends NestedPanels { public NestedPanels3() { super(); ChoiceEventHandler chandler = new ChoiceEventHandler(); choice.additemlistener(chandler); ButtonEventHandler bhandler = new ButtonEventHandler(); bhandler.registerbuttonhandler(this); <Inner class ChoiceEventHandler> <Inner class ButtonEventHandler> Inner Class Listener Inner classes classes that reside inside other (full-fledged) classes. Intended to be small. serve as helpers to the enclosing class. class ChoiceEventHandler implements ItemListener { public void itemstatechanged(itemevent event) { if (event.getstatechange() == ItemEvent.SELECTED) { messagebar.settext("choice selected: " + event.getitem()); Inner Class Listener (cont'd) class ButtonEventHandler implements ActionListener { public void actionperformed(actionevent event){ Button source = (Button) event.getsource(); messagebar.settext("button pushed: " + source.getlabel());

Inner Class Listener (cont'd) (class ButtonEventHandler continued.) protected void registerbuttonhandler(component comp) { if (comp!= null) { if (comp instanceof Button) { Button button = (Button) comp; button.addactionlistener(this); else if (comp instanceof Container) { Container container = (Container) comp; int n = container.getcomponentcount(); for (int i = 0; i < n; i++) registerbuttonhandler( container.getcomponent(i));