D06 PROGRAMMING with JAVA
|
|
|
- Elinor Todd
- 9 years ago
- Views:
Transcription
1 Cicles Formatius de Grau Superior Desenvolupament d Aplicacions Informàtiques D06 PROGRAMMING with JAVA Ch11 Interfaces & Polymorphism PowerPoint presentation, created by Angel A. Juan - ajuanp(@)gmail.com, for accompanying the book Big Java, by Cay S. Horstmann (2006)
2 Chapter Goals To learn about interfaces To be able to convert between class and interface references To understand the concept of polymorphism To appreciate how interfaces can be used to decouple classes To learn how to implement helper classes as inner classes To understand how inner classes access variables from the surrounding scope To implement event listeners for timer events
3 Using Interfaces for Code Reuse It is often possible to make code more general and more reusable by focusing on the essential operations that are carried out. Interface types are used to express these common operations In Chap. 7 (Iteration), we created the DataSet class to compute the average and maximum of a set of input values However, the DataSet class was suitable only for computing the average and maximum of a set of numbers. What if we want to find the average and maximum of a set of BankAccount values? Then, we would have to modify the class Or suppose we wanted to find the coin with the highest value among a set of coins. We would need to modify the DataSet class again Continued
4 Using Interfaces for Code Reuse public class DataSet // Modified for BankAccount objects... public void add(bankaccount x) sum = sum + x.getbalance(); if (count == 0 maximum.getbalance() < x.getbalance()) maximum = x; count++; public BankAccount getmaximum() return maximum; private double sum; private BankAccount maximum; private int count;
5 Using Interfaces for Code Reuse public class DataSet // Modified for Coin objects... public void add(coin x) sum = sum + x.getvalue(); if (count == 0 maximum.getvalue() < x.getvalue()) maximum = x; count++; public Coin getmaximum() return maximum; private double sum; private Coin maximum; private int count;
6 Using Interfaces for Code Reuse The mechanics of analyzing the data is the same in all cases, but details of measurement differ Classes could agree on a method getmeasure that obtains the measure to be used in the data analysis. For bank accounts, getmeasure returns the balance. For coins, getmeasure returns the coin value, and so on Then, we can implement a single reusable DataSet class whose add method looks like this: sum = sum + x.getmeasure(); if (count == 0 maximum.getmeasure() < x.getmeasure()) maximum = x; count++; Continued
7 Using Interfaces for Code Reuse What is the type of the variable x? Ideally, x should refer to any class that has a getmeasure method In Java, an interface type is used to specify required operations. We will define an interface type that we call Measurable: public interface Measurable double getmeasure(); The interface declaration lists all methods (and their signatures) that the interface type requires Note that the Measurable type is not a type in the standard library it is a type that was created specifically for making the DataSet class more reusable
8 Interfaces vs. Classes An interface type is similar to a class, but there are several important differences: All methods in an interface type are abstract; that is, they have a name, parameters, and a return type, but they don't have an implementation All methods in an interface type are automatically public An interface type does not have instance fields Now we can use the interface type Measurable to declare the variables x and maximum:
9 Generic dataset for Measurable Objects public class DataSet... public void add(measurable x) sum = sum + x.getmeasure(); if (count == 0 maximum.getmeasure() < x.getmeasure()) maximum = x; count++; public Measurable getmaximum() return maximum; private double sum; private Measurable maximum; private int count;
10 Implementing an Interface Type This DataSet class is usable for analyzing objects of any class that implements the Measurable interface. A class implements an interface type if it declares the interface in an implements clause. It should then implement the method or methods that the interface requires: public class BankAccount implements Measurable public double getmeasure() return balance; // Additional methods and fields public class Coin implements Measurable public double getmeasure() return value;... A class can implement more than one interface type. The class must then define all the methods that are required by all the interfaces it implements Note that the class must declare the method as public, whereas the interface need not all methods in an interface are public The Measurable interface expresses what all measurable objects have in common. This commonality makes the DataSet class reusable. Objects of the DataSet can be used to analyze collections of objects of any class that implements the Measurable interface
11 UML Diagram of Dataset and Related Classes Interfaces can reduce the coupling between classes UML notation: Interfaces are tagged with a "stereotype" indicator «interface» A dotted arrow with a triangular tip (--- ) denotes the "is-a" relationship between a class and an interface A dotted line with an open v-shaped arrow tip (---->) denotes the "uses" relationship or dependency Note that DataSet is decoupled from BankAccount and Coin Figure 2: UML Diagram of Dataset Class and the Classes that Implement the Measurable Interface
12 Syntax 11.1: Defining an Interface public interface InterfaceName // method signatures Example: public interface Measurable double getmeasure(); Purpose: To define an interface and its method signatures. The methods are automatically public.
13 Syntax 11.2: Implementing an Interface public class ClassName implements InterfaceName, InterfaceName,... // methods // instance variables Example: public class BankAccount implements Measurable // Other BankAccount methods public double getmeasure() // Method implementation Purpose: To define a new class that implements the methods of an interface
14 File DataSetTester.java 01: /** 02: This program tests the DataSet class. 03: */ 04: public class DataSetTester 05: 06: public static void main(string[] args) 07: 08: DataSet bankdata = new DataSet(); 09: 10: bankdata.add(new BankAccount(0)); 11: bankdata.add(new BankAccount(10000)); 12: bankdata.add(new BankAccount(2000)); 13: 14: System.out.println("Average balance = " 15: + bankdata.getaverage()); 16: Measurable max = bankdata.getmaximum(); 17: System.out.println("Highest balance = " 18: + max.getmeasure()); Continued
15 File DataSetTester.java 19: 20: DataSet coindata = new DataSet(); 21: 22: coindata.add(new Coin(0.25, "quarter")); 23: coindata.add(new Coin(0.1, "dime")); 24: coindata.add(new Coin(0.05, "nickel")); 25: 26: System.out.println("Average coin value = " 27: + coindata.getaverage()); 28: max = coindata.getmaximum(); 29: System.out.println("Highest coin value = " 30: + max.getmeasure()); 31: 32: Output: Average balance = Highest balance = Average coin value = Highest coin value = 0.25
16 Common Errors & Advanced Topics It is a common error to forget the public keyword when defining a method from an interface Interfaces cannot have instance fields, but it is legal to specify constants. When defining a constant in an interface, you can (and should) omit the keywords public static final, because all fields in an interface are automatically public static final
17 Self Check 1. Suppose you want to use the DataSet class to find the Country object with the largest population. What condition must the Country class fulfill? 2. Why can't the add method of the DataSet class have a parameter of type Object?
18 Answers 1. It must implement the Measurable interface, and its getmeasure method must return the population 2. The Object class doesn't have a getmeasure method, and the add method invokes the getmeasure method
19 Converting Between Class and Interface Types You can convert from a class type to an interface type, provided the class implements the interface: BankAccount account = new BankAccount(10000); Measurable x = account; // OK Coin dime = new Coin(0.1, "dime"); Measurable x = dime; // Also OK Thus, when you have an object variable of type Measurable, you don t actually know the exact type of the object to which x refers. All you know is that the object has a getmeasure method However, you cannot convert between unrelated types: Measurable x = new Rectangle(5, 10, 20, 30); // ERROR That assignment is an error, because the Rectangle class doesn't implement the Measurable interface Continued
20 Converting Between Class and Interface Types Occasionally, it happens that you convert an object to an interface reference and you need to convert it back. This happens in the getmaximum method of the DataSet class. The DataSet stores the object with the largest measure, as a Measurable reference: DataSet coindata = new DataSet(); coindata.add(new Coin(0.25, "quarter")); coindata.add(new Coin(0.1, "dime"));... Measurable max = coindata.getmaximum(); // Get the largest coin Now what can you do with the max reference? You know it refers to a Coin object, but the compiler doesn t. For example, you cannot call the getname method: String name = max.getname(); // ERROR That call is an error, because the Measurable type has no getname method However, as long as you are absolutely sure that max refers to a Coin object, you can use the cast notation to convert it back: Coin maxcoin = (Coin) max; String name = maxcoin.getname(); If you are wrong, your program will throw an exception and terminate Continued
21 Converting Between Class and Interface Types There is one big difference between casting of number types and casting of class types: When casting number types, you lose information, and you use the cast to tell the compiler that you agree to the information loss When casting object types, on the other hand, you take a risk of causing an exception, and you tell the compiler that you agree to that risk You can define variables whose type is an interface, for example: Measurable x; However, you can never construct an interface: Measurable x = new Measurable(); // ERROR Interfaces aren t classes. There are no objects whose types are interfaces. If an interface variable refers to an object, then the object must belong to some class a class that implements the interface: Measurable x = new BankAccount(); // OK
22 Self Check 3. Can you use a cast (BankAccount) x to convert a Measurable variable x to a BankAccount reference? 4. If both BankAccount and Coin implement the Measurable interface, can a Coin reference be converted to a BankAccount reference?
23 Answers 3. Only if x actually refers to a BankAccount object. 4. No a Coin reference can be converted to a Measurable reference, but if you attempt to cast that reference to a BankAccount, an exception occurs.
24 Polymorphism When multiple classes implement the same interface, each class implements the methods of the interface in different ways. How is the correct method executed when the interface method is invoked? It is perfectly legal to have variables whose type is an interface, such as: Measurable x; Note that the object to which x refers doesn't have type Measurable; the type of the object is some class that implements the Measurable interface: x = new BankAccount(10000); x = new Coin(0.1, "dime"); What can you do with an interface variable, given that you don t know the class of the object that it references? You can invoke the methods of the interface: double m = x.getmeasure(); But which getmeasure method is called? Continued
25 Polymorphism How did the correct method get called if the caller didn t even know the exact class to which x belongs? The Java virtual machine makes a special effort to locate the correct method that belongs to the class of the actual object. That is, if x refers to a BankAccount object, then the BankAccount.getMeasure method is called. If x refers to a Coin object, then the Coin.getMeasure method is called The principle that the actual type of the object determines the method to be called is called polymorphism. The same computation works for objects of many shapes, and adapts itself to the nature of the object. In Java, all instance methods are polymorphic Continued
26 Polymorphism You have already seen another case in which the same method name can refer to different methods, namely when a method name is overloaded: that is, when a single class has several methods with the same name but different parameter types. Then, the compiler selects the appropriate method when compiling the program, simply by looking at the types of the parameters: account = new BankAccount(); // Compiler selects BankAccount() account = new BankAccount(10000); // Compiler selects BankAccount(double) There is an important difference between polymorphism and overloading. The compiler picks an overloaded method when translating the program, before the program ever runs (early binding). However, when selecting the appropriate getmeasure method in a call x.getmeasure(), the compiler does not make any decision when translating the method. The program has to run before anyone can know what is stored in x. Therefore, the virtual machine, and not the compiler, selects the appropriate method (late binding)
27 Self Check 5. Why is it impossible to construct a Measurable object? 6. Why can you nevertheless declare a variable whose type is Measurable? 7. What do overloading and polymorphism have in common? Where do they differ?
28 Answers 5. Measurable is an interface. Interfaces have no fields and no method implementations. 6. That variable never refers to a Measurable object. It refers to an object of some class a class that implements the Measurable interface. 7. Both describe a situation where one method name can denote multiple methods. However, overloading is resolved early by the compiler, by looking at the types of the parameter variables. Polymorphism is resolved late, by looking at the type of the implicit parameter object just before making the call.
29 Inner Classes When you have a class that servers a very limited purpose, you can declare the class inside the method that needs it: public class DataSetTester3 public static void main(string[] args) class RectangleMeasurer implements Measurer... Measurer m = new RectangleMeasurer(); DataSet data = new DataSet(m);... Such a class is called an inner class. An inner class is any class that is defined inside another class. Since an inner class inside a method is not a publicly accessible feature, you don t need to document it as thoroughly
30 Inner Classes You can also define an inner class inside an enclosing class, but outside of its methods. Then the inner class is available to all methods of the enclosing class When you compile the source files for a program that uses inner classes, you will find that the inner classes are stored in files with curious names DataSetTester$1$RectangleMeasurer.class The exact names aren t important. The point is that the compiler turns an inner class into a regular class file
31 Syntax 11.3: Inner Classes Declared inside a method class OuterClassName method signature... class InnerClassName // methods // fields Declared inside the class class OuterClassName // methods // fields accessspecifier class InnerClassName // methods // fields... Continued
32 Syntax 11.3: Inner Classes Example: public class Tester public static void main(string[] args) class RectangleMeasurer implements Measurer Purpose: To define an inner class whose scope is restricted to a single method or the methods of a single class
33 Self Test 11. Why would you use an inner class instead of a regular class?
34 Answers 11. Inner classes are convenient for insignificant classes. Also, their methods can access variables and fields from the surrounding scope.
35 Processing Timer Events Timer event handling uses interfaces in the same way that events triggered by buttons and menus in a graphical program do The Timer class in the javax.swing package generates a sequence of events, spaced apart at even time intervals. This is useful whenever you want to have an object updated in regular intervals When a timer event occurs, the timer must call some method. The designers of the Timer class had no idea how you would want to use the Timer. Therefore, they simply chose an interface, called ActionListener, with a method that the timer can call: public interface ActionListener void actionperformed(actionevent event); A timer generates timer events at fixed intervals. An event listener is notified when a particular event occurs. Continued
36 Processing Timer Events When you use a timer, you need to define a class that implements the ActionListener interface. Place whatever action you want to occur inside the actionperformed method. Construct an object of that class. Pass it to the Timer constructor. Finally, start the timer: class MyListener implements ActionListener public void actionperformed(actionevent event) // This action will be executed at each timer event Place listener action here MyListener listener = new MyListener(); Timer t = new Timer(interval, listener); t.start(); Then the timer calls the actionperformed method of the listener object every interval milliseconds When you implement an interface, you must define each method exactly as it is specified in the interface. Accidentally making small changes to the parameter or return types is a common error
37 Example: Countdown Example: a timer that counts down to zero: Figure 3: Running the TimeTester Program Unlike a for loop, which would print all lines immediately, there is a onesecond delay between decrements. To keep the program alive after setting up the timer, the program displays a message dialog box
38 File TimeTester.java 01: import java.awt.event.actionevent; 02: import java.awt.event.actionlistener; 03: import javax.swing.joptionpane; 04: import javax.swing.timer; 05: 06: /** 07: This program tests the Timer class. 08: */ 09: public class TimerTester 10: 11: public static void main(string[] args) 12: 13: class CountDown implements ActionListener 14: 15: public CountDown(int initialcount) 16: 17: count = initialcount; 18: Continued
39 File TimeTester.java 19: 20: public void actionperformed(actionevent event) 21: 22: if (count >= 0) 23: System.out.println(count); 24: if (count == 0) 25: System.out.println("Liftoff!"); 26: count--; 27: 28: 29: private int count; 30: 31: 32: CountDown listener = new CountDown(10); 33: 34: final int DELAY = 1000; // Milliseconds between // timer ticks Continued
40 File TimeTester.java 35: Timer t = new Timer(DELAY, listener); 36: t.start(); 37: 38: JOptionPane.showMessageDialog(null, "Quit?"); 39: System.exit(0); 40: 41:
41 Self Check 13. Why does a timer require a listener object? 14. How many times is the actionperformed method called in the preceding program?
42 Answers 13. The timer needs to call some method whenever the time interval expires. It calls the actionperformed method of the listener object. 14. It depends. The method is called once per second. The first eleven times, it prints a message. The remaining times, it exits silently. The timer is only terminated when the user quits the program.
43 Accessing Surrounding Variables An attractive feature of inner classes is that their methods can access variables that are defined in surrounding blocks. In this regard, method definitions of inner classes behave similarly to nested blocks Except for some technical restrictions, the methods of an inner class can access the variables from the enclosing scope. It allows the inner class to access variables without having to pass them as constructor or method parameters
44 Accessing Surrounding Variables class Mover implements ActionListener public void actionperformed(actionevent event) // Move the rectangle ActionListener listener = new Mover(); final int DELAY = 100; // Milliseconds between timer ticks Timer t = new Timer(DELAY, listener); t.start();
45 Accessing Surrounding Variables The actionperformed method can access variables from the surrounding scope, like this: public static void main(string[] args)... final Rectangle box = new Rectangle(5, 10, 20, 30); class Mover implements ActionListener public void actionperformed(actionevent event) // Move the rectangle box.translate(1, 1);...
46 Accessing Surrounding Variables There is a technical wrinkle. An inner class can access surrounding local variables only if they are declared as final. That sounds like a restriction, but it is usually not an issue in practice (an object variable is final when the variable always refers to the same object: the state of the object can change, but the variable can t refer to a different object) An inner class can also access fields of the surrounding class, again with a restriction. The field must belong to the object that constructed the inner class object If the inner class object was created inside a static method, it can only access static surrounding fields
47 File TimeTester2.java 01: import java.awt.rectangle; 02: import java.awt.event.actionevent; 03: import java.awt.event.actionlistener; 04: import javax.swing.joptionpane; 05: import javax.swing.timer; 06: 07: /** 08: This program uses a timer to move a rectangle once per second. 09: */ 10: public class TimerTester2 11: 12: public static void main(string[] args) 13: 14: final Rectangle box = new Rectangle(5, 10, 20, 30); 15: 16: class Mover implements ActionListener 17: Continued
48 File TimeTester2.java 18: public void actionperformed(actionevent event) 19: 20: box.translate(1, 1); 21: System.out.println(box); 22: 23: 24: 25: ActionListener listener = new Mover(); 26: 27: final int DELAY = 100; // Milliseconds between timer ticks 28: Timer t = new Timer(DELAY, listener); 29: t.start(); 30: 31: JOptionPane.showMessageDialog(null, "Quit?"); 32: System.out.println("Last box position: " + box); 33: System.exit(0); 34: 35: java.awt.rectangle[x=6,y=11,width=20,height=30] java.awt.rectangle[x=7,y=12,width=20,height=30] java.awt.rectangle[x=8,y=13,width=20,height=30]... Output: java.awt.rectangle[x=28,y=33,width=20,height=30] java.awt.rectangle[x=29,y=34,width=20,height=30] Last box position: java.awt.rectangle[x=29,y=34,width=20,height=30]
49 Self Check 15. Why would an inner class method want to access a variable from a surrounding scope? 16. If an inner class accesses a local variable from a surrounding scope, what special rule applies?
50 Answers 15. Direct access is simpler than the alternative passing the variable as a parameter to a constructor or method. 16. The local variable must be declared as final.
51 Chapter Summary Use interface types to make code more reusable A Java interface type declares a set of methods and their signatures Unlike a class, an interface type provides no implementation Use the implements keyword to indicate that a class implements an interface type Interfaces can reduce the coupling between classes You can convert from a class type to an interface type, provided the class implements the interface You need a cast to convert from an interface type to a class type Continued
52 Chapter Summary Polymorphism denotes the principle that behavior can vary depending on the actual type of an object Early binding of methods occurs if the compiler selects a method from several possible candidates. Late binding occurs if the method selection takes place when the program runs An inner class is declared inside another class. Inner classes are commonly used for tactical classes that should not be visible elsewhere in a program A timer generates timer events at fixed intervals An event listener is notified when a particular event occurs Methods of an inner class can access variables from the surrounding scope Local variables that are accessed by an inner-class method must be declared as final
D06 PROGRAMMING with JAVA. Ch3 Implementing Classes
Cicles Formatius de Grau Superior Desenvolupament d Aplicacions Informàtiques D06 PROGRAMMING with JAVA Ch3 Implementing Classes PowerPoint presentation, created by Angel A. Juan - ajuanp(@)gmail.com,
D06 PROGRAMMING with JAVA
Cicles Formatius de Grau Superior Desenvolupament d Aplicacions Informàtiques D06 PROGRAMMING with JAVA Ch13 Inheritance PowerPoint presentation, created by Angel A. Juan - ajuanp(@)gmail.com, for accompanying
D06 PROGRAMMING with JAVA
Cicles Formatius de Grau Superior Desenvolupament d Aplicacions Informàtiques D06 PROGRAMMING with JAVA Ch15 Exception Handling PowerPoint presentation, created by Angel A. Juan - ajuanp(@)gmail.com, for
Moving from CS 61A Scheme to CS 61B Java
Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you
Chapter 13 - Inheritance
Goals Chapter 13 - Inheritance To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn about protected and package
Java Interview Questions and Answers
1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java
CSS 543 Program 3: Online Tic-Tac-Toe Game Professor: Munehiro Fukuda Due date: see the syllabus
CSS 543 Program 3: Online Tic-Tac-Toe Game Professor: Munehiro Fukuda Due date: see the syllabus 1. Purpose This assignment exercises how to write a peer-to-peer communicating program using non-blocking
Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language
Translation Translating to Java Introduction to Computer Programming The job of a programmer is to translate a problem description into a computer language. You need to be able to convert a problem description
ICOM 4015: Advanced Programming
ICOM 4015: Advanced Programming Lecture 10 Reading: Chapter Ten: Inheritance Copyright 2009 by John Wiley & Sons. All rights reserved. Chapter 10 Inheritance Chapter Goals To learn about inheritance To
D06 PROGRAMMING with JAVA
Cicles Formatius de Grau Superior Desenvolupament d Aplicacions Informàtiques D06 PROGRAMMING with JAVA Ch16 Files and Streams PowerPoint presentation, created by Angel A. Juan - ajuanp(@)gmail.com, for
Computing Concepts with Java Essentials
2008 AGI-Information Management Consultants May be used for personal purporses only or by libraries associated to dandelon.com network. Computing Concepts with Java Essentials 3rd Edition Cay Horstmann
History OOP languages Year Language 1967 Simula-67 1983 Smalltalk
History OOP languages Intro 1 Year Language reported dates vary for some languages... design Vs delievered 1957 Fortran High level programming language 1958 Lisp 1959 Cobol 1960 Algol Structured Programming
SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin
SE 360 Advances in Software Development Object Oriented Development in Java Polymorphism Dr. Senem Kumova Metin Modified lecture notes of Dr. Hüseyin Akcan Inheritance Object oriented programming languages
The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1
The Java Series Java Essentials I What is Java? Basic Language Constructs Slide 1 What is Java? A general purpose Object Oriented programming language. Created by Sun Microsystems. It s a general purpose
Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition
Java 6 'th edition Concepts INTERNATIONAL STUDENT VERSION CONTENTS PREFACE vii SPECIAL FEATURES xxviii chapter i INTRODUCTION 1 1.1 What Is Programming? 2 J.2 The Anatomy of a Computer 3 1.3 Translating
MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.
Exam Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) The JDK command to compile a class in the file Test.java is A) java Test.java B) java
AP Computer Science Java Subset
APPENDIX A AP Computer Science Java Subset The AP Java subset is intended to outline the features of Java that may appear on the AP Computer Science A Exam. The AP Java subset is NOT intended as an overall
Java (12 Weeks) Introduction to Java Programming Language
Java (12 Weeks) Topic Lecture No. Introduction to Java Programming Language 1 An Introduction to Java o Java as a Programming Platform, The Java "White Paper" Buzzwords, Java and the Internet, A Short
Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go
Debugging ESE112 Java Programming: API, Psuedo-Code, Scope It is highly unlikely that you will write code that will work on the first go Bugs or errors Syntax Fixable if you learn to read compiler error
C++ INTERVIEW QUESTIONS
C++ INTERVIEW QUESTIONS http://www.tutorialspoint.com/cplusplus/cpp_interview_questions.htm Copyright tutorialspoint.com Dear readers, these C++ Interview Questions have been designed specially to get
Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007
Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 The Java Type System By now, you have seen a fair amount of Java. Time to study in more depth the foundations of the language,
Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved.
1 2 Introduction to Java Applications 2.2 First Program in Java: Printing a Line of Text 2 Application Executes when you use the java command to launch the Java Virtual Machine (JVM) Sample program Displays
13 Classes & Objects with Constructors/Destructors
13 Classes & Objects with Constructors/Destructors 13.1 Introduction In object oriented programming, the emphasis is on data rather than function. Class is a way that binds the data & function together.
Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.
Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6 Handout 3 Strings and String Class. Input/Output with JOptionPane. Strings In Java strings are represented with a class type String. Examples:
INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction
INTRODUCTION TO COMPUTER PROGRAMMING Richard Pierse Class 7: Object-Oriented Programming Introduction One of the key issues in programming is the reusability of code. Suppose that you have written a program
Programming with Java GUI components
Programming with Java GUI components Java includes libraries to provide multi-platform support for Graphic User Interface objects. The multi-platform aspect of this is that you can write a program on a
Programming Languages CIS 443
Course Objectives Programming Languages CIS 443 0.1 Lexical analysis Syntax Semantics Functional programming Variable lifetime and scoping Parameter passing Object-oriented programming Continuations Exception
Iteration CHAPTER 6. Topic Summary
CHAPTER 6 Iteration TOPIC OUTLINE 6.1 while Loops 6.2 for Loops 6.3 Nested Loops 6.4 Off-by-1 Errors 6.5 Random Numbers and Simulations 6.6 Loop Invariants (AB only) Topic Summary 6.1 while Loops Many
Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.
Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java
This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output: 1 2 3 4 5 6 7 8 9 10
Java Loops & Methods The while loop Syntax: while ( condition is true ) { do these statements Just as it says, the statements execute while the condition is true. Once the condition becomes false, execution
6. Control Structures
- 35 - Control Structures: 6. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose,
Getting Started with the Internet Communications Engine
Getting Started with the Internet Communications Engine David Vriezen April 7, 2014 Contents 1 Introduction 2 2 About Ice 2 2.1 Proxies................................. 2 3 Setting Up ICE 2 4 Slices 2
LOOPS CHAPTER CHAPTER GOALS
jfe_ch04_7.fm Page 139 Friday, May 8, 2009 2:45 PM LOOPS CHAPTER 4 CHAPTER GOALS To learn about while, for, and do loops To become familiar with common loop algorithms To understand nested loops To implement
GUIs with Swing. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2012
GUIs with Swing Principles of Software Construction: Objects, Design, and Concurrency Jonathan Aldrich and Charlie Garrod Fall 2012 Slides copyright 2012 by Jeffrey Eppinger, Jonathan Aldrich, William
Visual Logic Instructions and Assignments
Visual Logic Instructions and Assignments Visual Logic can be installed from the CD that accompanies our textbook. It is a nifty tool for creating program flowcharts, but that is only half of the story.
GUI Event-Driven Programming
GUI Event-Driven Programming CSE 331 Software Design & Implementation Slides contain content by Hal Perkins and Michael Hotan 1 Outline User events and callbacks Event objects Event listeners Registering
An Overview of Java. overview-1
An Overview of Java overview-1 Contents What is Java Major Java features Java virtual machine Java programming language Java class libraries (API) GUI Support in Java Networking and Threads in Java overview-2
Creating a Java application using Perfect Developer and the Java Develo...
1 of 10 15/02/2010 17:41 Creating a Java application using Perfect Developer and the Java Development Kit Introduction Perfect Developer has the facility to execute pre- and post-build steps whenever the
File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)
File class in Java File Input and Output (Savitch, Chapter 10) TOPICS File Input Exception Handling File Output Programmers refer to input/output as "I/O". The File class represents files as objects. The
D06 PROGRAMMING with JAVA
Cicles Formatius de Grau Superior Desenvolupament d Aplicacions Informàtiques D06 PROGRAMMING with JAVA Ch20 Data Structures I PowerPoint presentation, created by Angel A. Juan - ajuanp(@)gmail.com, for
Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:
In creating objects of the type, we have used statements similar to the following: f = new (); The parentheses in the expression () makes it look like a method, yet we never created such a method in our
Designing with Exceptions. CSE219, Computer Science III Stony Brook University http://www.cs.stonybrook.edu/~cse219
Designing with Exceptions CSE219, Computer Science III Stony Brook University http://www.cs.stonybrook.edu/~cse219 Testing vs. Debugging Testing Coding Does the code work properly YES NO 2 Debugging Testing
Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas
CS 110B - Rule Storage Classes Page 18-1 Attributes are distinctive features of a variable. Data type, int or double for example, is an attribute. Storage class is another attribute. There are four storage
How To Use The Command Pattern In Java.Com (Programming) To Create A Program That Is Atomic And Is Not A Command Pattern (Programmer)
CS 342: Object-Oriented Software Development Lab Command Pattern and Combinations David L. Levine Christopher D. Gill Department of Computer Science Washington University, St. Louis levine,[email protected]
Sources: On the Web: Slides will be available on:
C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,
Computer Programming C++ Classes and Objects 15 th Lecture
Computer Programming C++ Classes and Objects 15 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2013 Eom, Hyeonsang All Rights Reserved Outline
CSE 1020 Introduction to Computer Science I A sample nal exam
1 1 (8 marks) CSE 1020 Introduction to Computer Science I A sample nal exam For each of the following pairs of objects, determine whether they are related by aggregation or inheritance. Explain your answers.
Java Application Developer Certificate Program Competencies
Java Application Developer Certificate Program Competencies After completing the following units, you will be able to: Basic Programming Logic Explain the steps involved in the program development cycle
Part 1 Foundations of object orientation
OFWJ_C01.QXD 2/3/06 2:14 pm Page 1 Part 1 Foundations of object orientation OFWJ_C01.QXD 2/3/06 2:14 pm Page 2 1 OFWJ_C01.QXD 2/3/06 2:14 pm Page 3 CHAPTER 1 Objects and classes Main concepts discussed
6.1. Example: A Tip Calculator 6-1
Chapter 6. Transition to Java Not all programming languages are created equal. Each is designed by its creator to achieve a particular purpose, which can range from highly focused languages designed for
Building Java Programs
Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: 3.3-3.4 self-check: #16-19 exercises: #11 videos: Ch. 3 #4 Interactive programs We have written programs that print
Working with SmartArt
CHAPTER Working with SmartArt In this chapter by Geetesh Bajaj Understanding SmartArt 206 Adding SmartArt to a Presentation 206 Formatting SmartArt 208 Sample SmartArt Variants 211 Common SmartArt Procedures
Introducing Variance into the Java Programming Language DRAFT
Introducing Variance into the Java Programming Language A Quick Tutorial DRAFT Christian Plesner Hansen Peter von der Ahé Erik Ernst Mads Torgersen Gilad Bracha June 3, 2003 1 Introduction Notice: This
WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.
WA2099 Introduction to Java using RAD 8.0 Student Labs Web Age Solutions Inc. 1 Table of Contents Lab 1 - The HelloWorld Class...3 Lab 2 - Refining The HelloWorld Class...20 Lab 3 - The Arithmetic Class...25
Model Simulation in Rational Software Architect: Business Process Simulation
Model Simulation in Rational Software Architect: Business Process Simulation Mattias Mohlin Senior Software Architect IBM The BPMN (Business Process Model and Notation) is the industry standard notation
Fundamentals of Java Programming
Fundamentals of Java Programming This document is exclusive property of Cisco Systems, Inc. Permission is granted to print and copy this document for non-commercial distribution and exclusive use by instructors
Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts
Third AP Edition Object-Oriented Programming and Data Structures Maria Litvin Phillips Academy, Andover, Massachusetts Gary Litvin Skylight Software, Inc. Skylight Publishing Andover, Massachusetts Skylight
Syllabus for CS 134 Java Programming
- Java Programming Syllabus Page 1 Syllabus for CS 134 Java Programming Computer Science Course Catalog 2000-2001: This course is an introduction to objectoriented programming using the Java language.
The Basic Java Applet and JApplet
I2PUJ4 - Chapter 6 - Applets, HTML, and GUI s The Basic Java Applet and JApplet Rob Dempster [email protected] School of Computer Science University of KwaZulu-Natal Pietermaritzburg Campus I2PUJ4 - Chapter
J a v a Quiz (Unit 3, Test 0 Practice)
Computer Science S-111a: Intensive Introduction to Computer Science Using Java Handout #11 Your Name Teaching Fellow J a v a Quiz (Unit 3, Test 0 Practice) Multiple-choice questions are worth 2 points
CS170 Lab 11 Abstract Data Types & Objects
CS170 Lab 11 Abstract Data Types & Objects Introduction: Abstract Data Type (ADT) An abstract data type is commonly known as a class of objects An abstract data type in a program is used to represent (the
Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions
COMP209 Object Oriented Programming Designing Classes 2 Mark Hall Programming by Contract (adapted from slides by Mark Utting) Preconditions Postconditions Class invariants Programming by Contract An agreement
Chapter 1 Java Program Design and Development
presentation slides for JAVA, JAVA, JAVA Object-Oriented Problem Solving Third Edition Ralph Morelli Ralph Walde Trinity College Hartford, CT published by Prentice Hall Java, Java, Java Object Oriented
Understanding class definitions
OFWJ_C02.QXD 2/3/06 2:28 pm Page 17 CHAPTER 2 Understanding class definitions Main concepts discussed in this chapter: fields methods (accessor, mutator) constructors assignment and conditional statement
Building Java Programs
Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: 3.3-3.4 self-check: #16-19 exercises: #11 videos: Ch. 3 #4 Interactive programs We have written programs that print
Computer Programming I
Computer Programming I COP 2210 Syllabus Spring Semester 2012 Instructor: Greg Shaw Office: ECS 313 (Engineering and Computer Science Bldg) Office Hours: Tuesday: 2:50 4:50, 7:45 8:30 Thursday: 2:50 4:50,
CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013
Oct 4, 2013, p 1 Name: CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 1. (max 18) 4. (max 16) 2. (max 12) 5. (max 12) 3. (max 24) 6. (max 18) Total: (max 100)
JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4
JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4 NOTE: SUN ONE Studio is almost identical with NetBeans. NetBeans is open source and can be downloaded from www.netbeans.org. I
Chapter 5 Names, Bindings, Type Checking, and Scopes
Chapter 5 Names, Bindings, Type Checking, and Scopes Chapter 5 Topics Introduction Names Variables The Concept of Binding Type Checking Strong Typing Scope Scope and Lifetime Referencing Environments Named
Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example
Operator Overloading Lecture 8 Operator Overloading C++ feature that allows implementer-defined classes to specify class-specific function for operators Benefits allows classes to provide natural semantics
Tools for Integration Testing
Tools for Integration Testing What is integration ing? Unit ing is ing modules individually A software module is a self-contained element of a system Then modules need to be put together to construct the
Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.
Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to
CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5
This Week CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5 School of Computer Science University of St Andrews Graham Kirby Alan Dearle More on Java classes Constructors Modifiers cdn.videogum.com/img/thumbnails/photos/commenter.jpg
Advanced Data Structures
C++ Advanced Data Structures Chapter 8: Advanced C++ Topics Zhijiang Dong Dept. of Computer Science Middle Tennessee State University Chapter 8: Advanced C++ Topics C++ 1 C++ Syntax of 2 Chapter 8: Advanced
www.sahajsolns.com Chapter 4 OOPS WITH C++ Sahaj Computer Solutions
Chapter 4 OOPS WITH C++ Sahaj Computer Solutions 1 Session Objectives Classes and Objects Class Declaration Class Members Data Constructors Destructors Member Functions Class Member Visibility Private,
Lecture 5: Java Fundamentals III
Lecture 5: Java Fundamentals III School of Science and Technology The University of New England Trimester 2 2015 Lecture 5: Java Fundamentals III - Operators Reading: Finish reading Chapter 2 of the 2nd
Java Basics: Data Types, Variables, and Loops
Java Basics: Data Types, Variables, and Loops If debugging is the process of removing software bugs, then programming must be the process of putting them in. - Edsger Dijkstra Plan for the Day Variables
Chapter 2 Introduction to Java programming
Chapter 2 Introduction to Java programming 1 Keywords boolean if interface class true char else package volatile false byte final switch while throws float private case return native void protected break
LAB 1. Familiarization of Rational Rose Environment And UML for small Java Application Development
LAB 1 Familiarization of Rational Rose Environment And UML for small Java Application Development OBJECTIVE AND BACKGROUND The purpose of this first UML lab is to familiarize programmers with Rational
Database Programming with PL/SQL: Learning Objectives
Database Programming with PL/SQL: Learning Objectives This course covers PL/SQL, a procedural language extension to SQL. Through an innovative project-based approach, students learn procedural logic constructs
Basic Object-Oriented Programming in Java
core programming Basic Object-Oriented Programming in Java 1 2001-2003 Marty Hall, Larry Brown http:// Agenda Similarities and differences between Java and C++ Object-oriented nomenclature and conventions
JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.
http://www.tutorialspoint.com/java/java_quick_guide.htm JAVA - QUICK GUIDE Copyright tutorialspoint.com What is Java? Java is: Object Oriented Platform independent: Simple Secure Architectural- neutral
TABLE OF CONTENTS...2 INTRODUCTION...3 APPLETS AND APPLICATIONS...3 JAVABEANS...4 EXCEPTION HANDLING...5 JAVA DATABASE CONNECTIVITY (JDBC)...
Advanced Features Trenton Computer Festival May 1 sstt & 2 n d,, 2004 Michael P.. Redlich Senior Research Technician ExxonMobil Research & Engineering [email protected] Table of Contents
PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON
PROBLEM SOLVING WITH SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON Addison Wesley Boston San Francisco New York London
Chapter 5. Recursion. Data Structures and Algorithms in Java
Chapter 5 Recursion Data Structures and Algorithms in Java Objectives Discuss the following topics: Recursive Definitions Method Calls and Recursion Implementation Anatomy of a Recursive Call Tail Recursion
CPS122 Lecture: State and Activity Diagrams in UML
CPS122 Lecture: State and Activity Diagrams in UML Objectives: last revised February 14, 2012 1. To show how to create and read State Diagrams 2. To introduce UML Activity Diagrams Materials: 1. Demonstration
Week 2 Practical Objects and Turtles
Week 2 Practical Objects and Turtles Aims and Objectives Your aim in this practical is: to practise the creation and use of objects in Java By the end of this practical you should be able to: create objects
D06 PROGRAMMING with JAVA
Cicles Formatius de Grau Superior Desenvolupament d Aplicacions Informàtiques D06 PROGRAMMING with JAVA Ch8 Arrays and Array Lists PowerPoint presentation, created by Angel A. Juan - ajuanp(@)gmail.com,
System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :
Benjamin Michael Java Homework 3 10/31/2012 1) Sales.java Code // Sales.java // Program calculates sales, based on an input of product // number and quantity sold import java.util.scanner; public class
CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals
CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals 1 Recall From Last Time: Java Program import java.util.scanner; public class EggBasket { public static void main(string[]
qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq
qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq Introduction to Programming using Java wertyuiopasdfghjklzxcvbnmqwertyui
An Introduction to Classes
3 CHAPTER An Introduction to Classes Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To understand the purpose and use of constructors To
Extending Desktop Applications to the Web
Extending Desktop Applications to the Web Arno Puder San Francisco State University Computer Science Department 1600 Holloway Avenue San Francisco, CA 94132 [email protected] Abstract. Web applications have
We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.
LING115 Lecture Note Session #4 Python (1) 1. Introduction As we have seen in previous sessions, we can use Linux shell commands to do simple text processing. We now know, for example, how to count words.
Time Limit: X Flags: -std=gnu99 -w -O2 -fomitframe-pointer. Time Limit: X. Flags: -std=c++0x -w -O2 -fomit-frame-pointer - lm
Judge Environment Language Compilers Language Version Flags/Notes Max Memory Limit C gcc 4.8.1 Flags: -std=gnu99 -w -O2 -fomit-frame-pointer - lm C++ g++ 4.8.1 Flags: -std=c++0x -w -O2 -fomit-frame-pointer
Object Oriented Software Design
Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction
Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is
Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is preceded by an equal sign d. its name has undereline 2. Associations
JavaScript. JavaScript: fundamentals, concepts, object model. Document Object Model. The Web Page. The window object (1/2) The document object
JavaScript: fundamentals, concepts, object model Prof. Ing. Andrea Omicini II Facoltà di Ingegneria, Cesena Alma Mater Studiorum, Università di Bologna [email protected] JavaScript A scripting language:
Massachusetts Institute of Technology 6.005: Elements of Software Construction Fall 2011 Quiz 2 November 21, 2011 SOLUTIONS.
Massachusetts Institute of Technology 6.005: Elements of Software Construction Fall 2011 Quiz 2 November 21, 2011 Name: SOLUTIONS Athena* User Name: Instructions This quiz is 50 minutes long. It contains
LAB4 Making Classes and Objects
LAB4 Making Classes and Objects Objective The main objective of this lab is class creation, how its constructer creation, object creation and instantiation of objects. We will use the definition pane to
