174
Object Oriented Programming in Java Third Year University of Salahaddin-Erbil College of Engineering Department of Software Engineering Karim Zebari 2002-2003

Java for C++ programers

Embed Size (px)

Citation preview

Page 1: Java for C++ programers

Object Oriented Programming in JavaThird Year

University of Salahaddin-Erbil College of Engineering

Department of Software Engineering

Karim Zebari

2002-2003

Page 2: Java for C++ programers

About this course

This course is about object-oriented programming in Java. You already know how to write object-oriented programs using C++; but C++ supports object-oriented programming, whereas Java is a pure object-oriented programming language. Everything in Java is an object; you only deal with objects.

Java is very similar to C++, both in its syntax and semantics. Designers of Java deliberately made Java similar to a popular language (C++) so the learning curve for Java would be shorter. Since you already have experience with C++, learning Java should not take too long. Of course, there are some differences too which we will point out throughout this course.

Java’s slogan is: “write once, run everywhere”. Which means that if a program is written in Java on any platform, the same program should run on any other platform without any modifications: portability

Object Oriented Programming in Java 2

Page 3: Java for C++ programers

About this course 2

This portability of Java is very desirable and is one of the reasons why Java has become so popular among programmers. Java also provides for network programming especially on the Internet, and with the spread of Internet, Java has become more widespread.

In this course, we will study Java in detail and will focus on the following main features:

- Java language (syntax and semantics)- Graphical User Interface (GUI) programming- Object Oriented programming in Java- Advanced features of Java, including database programming, network programming, multi-threading…

Internet programming in Java will be covered in the course: Web Programming.

Object Oriented Programming in Java 3

Page 4: Java for C++ programers

About this course 3

At the end of this course, students should be able to:

- write complex and large OO programs in Java- demonstrate a deep understanding of OO concepts- write sophisticated GUI programs - utilize advanced features of Java in their programs

Assessment for this course will be as follows:

Assignments ( 2 ) 15%Theoretical Exams 10%Lab Exams ( 2 ) 20%Discipline 5%Final Exam 50%

Object Oriented Programming in Java 4

Page 5: Java for C++ programers

About this course 4Programming courses, such as this course, usually involve a considerable amount of practical coursework or programming in the labs. You should find as much time as possible in the labs for exercises, assignments and testing in Java. The only way to really learn a new programming language is to write many programs and read other people’s programs. You have 2 scheduled hours in the lab for this course and you should work at least 1 extra hour in the lab.

These notes are intended to cover the bulk of this course, but you should never rely on notes ONLY. At this stage of your education, you should read more books, consult other related textbooks and explore the subject from different angles. The following textbooks are recommended:

1) Java How to Program, 3rd Edition, 1999, Deitel & Deitel 2) Java The Complete Reference, 3) http://java.sun.com Java Homepage4) http://java.sun.com/docs/books/tutorial Java Online Tutorial, also available locally

Several other books are available in the department’s library.

Object Oriented Programming in Java 5

Page 6: Java for C++ programers

The Syllabus

The following topics will be covered in this course:

- Java (history, language, philosophy, versions…)- Basics (simple programs, variables, strings, control flow…)- Arrays and Methods in Java- Object-Oriented programming - Exception Handling, Files and Streams- Basics in graphics programming- Advanced graphical user interface programming- Multi-threading - Database access in Java- Client/server and networking programming- Remote Method Invocation (RMI)- Collections and JavaBeans

Object Oriented Programming in Java 6

Page 7: Java for C++ programers

Java

The Sun Microsystems company formally announced Java at a conference in May 1995. Java was initially (1991) designed for programming embedded systems. The project soon ran into problems and later the company almost had to abandon the entire project. But mid-90s saw the fast and explosive development of the World Wide Web (WWW) and the company thought that they could adapt the language into a programming language for creating dynamic content on web pages.

Java is a programming language designed by James Gosling and is described in detail in a white paper written by James Gosling and Henry McGilton. This paper is 98 pages long; a simpler and shorter overview paper is available called “The Java Language: An Overview”. Both of these documents are available on the department’s intranet and you should definitely read them both. You should read the overview paper as soon as possible and make an attempt on the official paper during the course of this year. Every paper mentioned in the notes is examinable.

Object Oriented Programming in Java 7

Page 8: Java for C++ programers

Java 2

Java is defined as: A simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, and dynamic language.

Simple: Java is designed to be syntactically very similar to C/C++ (C/C++ community is very large) but without the arcane and hard-to-use features of C/C++. The following C/C++ features which are usually the source of many bugs and are troublesome to use are eliminated in Java:

- Pointer arithmetic- Multiple inheritance- Operator Overloading (programmer controlled)- Explicit memory management - Preprocessor - Unions, enum, struct, typedef,

Object Oriented Programming in Java 8

Page 9: Java for C++ programers

Java 3

Another feature of Java is that it is a small language. Since the initial design was aimed for small embedded consumer devices the designers had to make the language small.

Object-Oriented: Java is an object-oriented programming language meaning it supports encapsulation, inheritance and polymorphism. Everything in Java is a class. Even writing a simple “Hello World” program requires you to define a class. Java is a pure object-oriented language, with some small exceptions. Classes are instantiated at runtime to create objects. Java class functions are called methods.

Distributed: With Java, programs can easily communicate access data across TCP/IP networks such as the Internet. Network support is built into Java and has an extensive library of classes to support network programming. Security, which is a concern for network programs is also built into the language (more on this later).

Object Oriented Programming in Java 9

Page 10: Java for C++ programers

Java 4

Interpreted: Java programs (source code) are first compiled into architecture-neutral bytecodes. Then the bytecodes are interpreted by the Java virtual machine and exxecuted on any machine to which the Java interpreter has been ported.

Robust: Generally, smaller programs are more robust than larger ones. Java puts a lot of emphasis on error checking both at compile-time and at run-time. Further, Java is a very strongly-typed language. Every type of data must be given a type and type conversions are performed in a more organized way. Contrast this with VB for example, which is weakly-typed language. Errors can more easily be checked in strongly-typed languages. C++ is also a strongly-typed language, but it inherits some compile-time checking problems in C, such as procedure declarations. Pointer arithmetic and array boundary errors are non-existent in Java. Exception handling which is used to support run-time error checking is built into the language.

Object Oriented Programming in Java 10

Page 11: Java for C++ programers

Java 5

Secure: Java is intended to be used in networked/distributed environments. Toward that end, a lot of emphasis has been placed on security. Java includes built-in security features.

Architecture-neutral: A design goal of Java was that programs would be able to run on networks and distributed systems; and usually there are many different kinds of computer systems on larger networks. To achieve this goal, the language had to be architecture-neutral.

The Java compiler generates Java bytecode instructions which are completely independent of any computer architecture. This generated bytecode could be run on any computer for which a Java run-time systems has been installed. The disadvantage of this, of course, is that performance suffers as a result.

Portable: Primitive type sizes are explicit and not dependent on any

Object Oriented Programming in Java 11

Page 12: Java for C++ programers

Java 6underlying architecture (integer sizes are always 32-bit, doubles are always 64-bit…, independent of the computer architecture). This unlike C/C++ where primitive type sizes depend on the computer architecture.

High-Performance: The performance of interpreted code is usually more than adequate but for high-performance applications the speed may be a problem. Just-in-time compilers can overcome this problem by generating machine specific codes which run faster than normal Java bytecodes. But of course this would limit portability.

Java also supports native code invocation for mission-critical applications (C and C++ code can be called inside Java classes)

Multithreaded: C and C++ are single-threaded languages: only one process or program or thread can run at any one time. Java is a multithreaded language meaning multiple threads can run simultaneously. A thread is analogous to a program or a process ( more on this later).

Object Oriented Programming in Java 12

Page 13: Java for C++ programers

Java 7

Dynamic: In Java, class linking, memory layout decisions, name resolution, and object references are not resolved until run-time. Run-time Type Information (RTTI) is available as part of the language which is used to used to find out the type of objects at runtime.

That is Java!! Well, many of the aspects of the language explained above may not be so clear at first; that’s only natural and they will be clearer as we delve deeper into the course in the coming weeks and months.

With Java you can create two types of programs:1- Applications: ordinary standalone programs (like C++ and VB

programs) which are run locally on your computer.2- Applets: these are programs designed to be transported over the Internet (or intranet) and executed in WWW browsers like

Netscape Communicator, Microsoft’s Internet Explorer and Sun’s HotJava.

Object Oriented Programming in Java 13

Page 14: Java for C++ programers

Java 8

The Java SDK or JDK (Java Development Kit) is made up of two main subsystems: the Java compiler and the Java interpreter or Java Virtual Machine. Java class libraries, Java debugger and some other development tools are also part of Java platform. The following figure illustrates the basic components of the Java system:

Object Oriented Programming in Java 14

Page 15: Java for C++ programers

Java 9

In this course we will be concerned with applications only. This does not mean that we will only learn how to write standalone programs; distributed and client/server applications work on networks and they will make up a major part of this course. Applets will be covered in the course “Web Programming” which you are taking alongside this course. This is because that course is wholly devoted to web and Internet programming and applets are used extensively on the web.

The process of developing a Java program (application) involves:

1- Writing the program source code in a text editor (TextPad )2- Saving the program file with the same name as the main class name.3- Compiling the program file: javac filename.java4- Executing the bytecode file: java filename [parameters]

Object Oriented Programming in Java 15

Page 16: Java for C++ programers

The “Hello World” ProgramAs is the tradition in learning a new language, we will start learning Java by writing the famous “Hello World” program as our first program. Here is the complete program://Filename: HelloWorld.java //1//Date created: 9 July 2002 //2class HelloWorld //3{

public static void main(String args[ ]) //5{

System.out.println(“Hello World”);//6}

}Let’s look at this program line by line:Lines 1 and 2 are familiar C++-style comments. C-style (/*…comments…*/ ) comments are also available for longer comments which span several lines.

Object Oriented Programming in Java 16

Page 17: Java for C++ programers

The “Hello World” Program 2

You should realize the importance of comments by now. Every program should have some comments at the beginning of the program stating the name of the program file, the purpose of the program, the date the program is created and a general description of the program.

Other places that should be commented include: class definitions, method definitions, and any code that is not clear to the reader.

Line 3 begins the definition of class for HelloWorld. Every Java program must have at least one class definition that is defined by the programmer. By convention, class names begin with a capital letter; so does every word in a class name( MyClass ) The class name is called an identifier; identifiers consist of letters, digits, the underscore and the dollar sign, but must not begin with a digit and cannot have spaces within it. Also notice that Java is case sensitive. When you save a Java program make sure the file name is exactly the same as the class name with the main method.

Object Oriented Programming in Java 17

Page 18: Java for C++ programers

The “Hello World” Program 3

Line 5 is part of every Java application which automatically begin execution at main. main is a method ( function ) The void keyword indicates that the method does not return any values; static means that the method belongs to the class not to class objects ( as in C++ ). The keyword public indicates that the method is accessible outside the class.

Line 6, instructs the computer to output the string between the double quotes. System.out is a class and println is a method defined in this class. This method also causes a new-line (ln). If you omitted the ln from println, the curser would remain on the current output line.

This was the simplest possible Java application that does something. It contained only one statement, the output statement. As you have seen, the syntax of this simple Java program is quite simple and familiar. Most probably, if you were asked what the output would be, you would answer correctly, because of simple and familiar syntax.

Object Oriented Programming in Java 18

Page 19: Java for C++ programers

The “Hello World” Program 4

One of the great strengths of the Java language is its support for GUI programming. Throughout this course, we will write increasingly more complex GUI-rich programs. The “Hello World” program using GUI:import javax.swing.JOptionPane;class Welcome {

public static void main(String[] args) { JOptionPane.showMessageDialog(null, “Hello World”); System.exit(0);}

}

We first import or include the the JOptionPane class which is defined in the javax.swing package. This class contains many elements to support GUI programs. showMessageDialog is a static method used for showing a dialog containing message to the user. The first parameter is null (this parameter will be discussed later); the second is a string to be displayed.

Object Oriented Programming in Java 19

Page 20: Java for C++ programers

The “Hello World” Program 5

The static method System.exit(0) is needed to terminate applications that use graphical user interface elements; 0 indicates that the application terminated successfully:

Object Oriented Programming in Java 20

Page 21: Java for C++ programers

The “Hello World” Program 6

In this next example we write a program to prompt the user for two numbers and display the sum of the two numbers to the user:class Add{ public static void main(String[] args) {

String str1Num, str2Num; int num1, num2;str1Num=JOptionPane.showInputDialog(“First Number”);str2Num=JOptionPane.showInputDialog(“Second Number”);num1=Integer.parseInt(str1Num);num2=Integer.parseInt(str2Num);int sum=num1+num2;JOptionPane.showMessageDialog(null, “Sum is: “ + sum, “Results”, JPtionPane.PLAIN_MESSAGE);System.exit(0);

}}//the 4th parameter specifies dialog type: INFORMATION_MESSAGE, ERROR_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE, PLAIN_MESSAGE

Object Oriented Programming in Java 21

Page 22: Java for C++ programers

The “Hello World” Program 7

The method showInputDialog prompts the user for input. The parameter to this method is a string asking the user to enter a value. This dialog box has two buttons: OK and Cancel. If the user enters any value other than an integer number or clicks the Cancel button, a runtime exception will occur. Exceptions will be discussed later.

The result or the return value of this method is a string; but we are expected to enter an integer number. We need to convert this string to an integer, hence the following line:

num1=Integer.parseInt(str1Num);to parse or convert the string to an integer. Class Integer is defined in the package java.lang which is automatically available to your programs.

The overloaded version of showMessageDialog is different from the one we used earlier, requiring 2 more parameters: a string to display in the title of the dialog and a forth parameter to specify the dialog window type.

Object Oriented Programming in Java 22

Page 23: Java for C++ programers

Data Types

Java is a strongly-typed language and this means that you must give every variable a type, or declare it. Java has 8 primitive data types:

Type Storage Range int 4 bytes -2,147,483,648 to 2,147,483,647short 2 bytes -32,768 to 32,767long 8 bytes -9223,372,036,854,775,808L to …byte 1 byte -128 to 127

Note the trailing ‘L’ at the end of long integers. Hexadecimal numbers have the prefix 0x, for example 0x1A represents the decimal number 16.

Unlike in C++, in Java the integer data type ranges do not depend on the underlying machine. There 2 types of floating-number in Java:float 4 bytes approx. +/-3.40282347E+38F (6-7 digits)double 8 bytes approx. +/-1.79769313486231570+308 (15 digits)

Object Oriented Programming in Java 23

Page 24: Java for C++ programers

Data Types 2

Floating-point numbers of type float have a trailing F. Those that don’t have any postfix characters are considered as of type double ( or those with D as a postfix). Usually, the type double is used.

Characters are of type char; as in C++, single quotes are used to denote char constants. Unicode coding scheme is used to represent Java char types. In Unicode, 2 bytes are used for storage which allows 65,536 characters, providing for non-Roman characters. (The ASCII code is 1-byte and allows only 255 characters to be represented)

The Booloean type has two values: true and false. It is used with logical testing used with relational operators. But in Java, unlike in C++, you cannot covert between numbers and boolean values.

You can declare a variable in Java by specifying a data type followed by an identifier for the variable name as in: long aBigNumber;

Object Oriented Programming in Java 24

Page 25: Java for C++ programers

Assignment, Initialization, Constants…

After declaring a new variable, you should always initialize it using an assignment statement. The Java compiler will indicate an error if you have un-initialized variables:

int num=0;Numeric conversions are possible in Java, but sometimes information loss may occur. Conversions can be done using casts:

double d=9.88;int i=(int) d;Then the variable i has the value 9, because casting a floating-point value to an integer discards the fractional part and does not round; if you want to round the number:double d=9.88;int i=(int) Math.round(d);Now i will have the value 10. The Math class is part of base language.

Object Oriented Programming in Java 25

Page 26: Java for C++ programers

Assignment, Initialization, Constants… 2You still need to cast because the return type of Math.round is long and you cannot convert a long to an int without casting. (narrowing)

But certain assignments are allowed without casting: (widening)byte->short->int->long->float->double

In Java you cannot cast between boolean and any numeric type, because boolean values are not numbers (contrary to C++).

In Java, the keyword final is used to denote a constant:final double CM_PER_INCH=2.54;

It’s customary to name constants all in upper case. The familiar arithmetic operators (* , / , + , - , %) can be used with numerical values and behave as in C++. Exponentiation is via a library mrthod:

double d=Math.pow(x, y) where x, y and the return type of the method are all of type double.

Object Oriented Programming in Java 26

Page 27: Java for C++ programers

Assignment, Initialization, Constants… 3

Like C++, Java supports increment and decrement operators while increase/decrease a numeric value by one:

int m=5, n=5;int a=3 * ++m; //a has value 18, m has value 6int b=3 * n++; //b has value 15, n has value 6

Java has the familiar relational operators: ==,>,<, =>,<=, !=,&&, ||

Inexperienced programmers often mistakenly use = in place of == in boolean expressions; this caused a problem in C++ because C++ treats boolean values as numbers but Java eliminates this bug as in Java booleans are not numbers and the compiler would detect the bug:

if(k=0) //would not compile, because it//evaluates to 0 and 0 is not of type boolean.

Object Oriented Programming in Java 27

Page 28: Java for C++ programers

Assignment, Initialization, Constants… 3It is usually best to use parentheses to indicate the order of operations. If not, operator precedence is used in Java according to the following rules:

Operator Associativity

[] . () left to right! ~ ++ -- + - () (cast) new right to left* / % left to right+ - left to right<< >> >>> left to right< <= > >= instanceof left to right== != left to right& left to right^ left to right| left to right&& left to right|| left to right?: left to right= += -= *= /= %= &= |= ^= <<= >>= >>>= right to left

Object Oriented Programming in Java 28

Increasing precedence

Page 29: Java for C++ programers

Strings

Strings are sequences of characters like: “Hello”. Java, like C++, does not have a built-in string type; instead the standard Java library contains a class called String:

String empty=“”;String greeting=“Hello”;

You can concatenate two strings together:String s1=“Hello”;String s2=“ Sir”;String s=s1+s2;

When you concatenate a string with a value that is not a string, the latter is converted to a string: String s=“Hello”;

s+=13;You can extract a substring from a string using the substring method of the String class: String s3=greeting.substring(0,4);

//s3 will contain the string Hell

Object Oriented Programming in Java 29

Page 30: Java for C++ programers

Strings 2

To test two strings for equality use the String method equals:s1.equals(s2);

The return type is boolean. S1 and s2 can be either constant strings or string objects.

s1.equals(“Hello”);To test two strings for equality and ignoring upper/lower case differences:

s1.equalsIgnoreCase(s2);Do NOT use == operator to test two strings for equality; it’s only for determining if the two strings are stored in the same location or not. Strings are references to memory locations and when you use == operator with two strings it checks whether the two strings refer to the same location or not, not to test whether or not the contents of the two strings are equal. Be ware! Other common Strings methods : length(), charAt(n), endsWith(str1), startsWith(str2), toLowerCase(), toUpperCase(), trim(), (about 50 in total)

Object Oriented Programming in Java 30

Page 31: Java for C++ programers

Strings 3Java Strings are immutable meaning that once a string object has been created, it cannot be modified. That is why string methods often return a new string that holds the modified string:

String s=“Now”;String sub=s.subString(0, 2);int len=sub.length(); //length of substring is 2-0char[] ca=s.toCharArray(); //convert string to //array of

charactersString s2=s.toLowerCase();//change to lowercaseboolean b=s.endsWith(“t”); //trueint n=s.compareTo(“Hi”); //returns 0 if two //strings are

equal,<0 if s comes before “Hi”, and >0 //if s comes after “Hi”String s2=s.replace(‘.’,‘!’);//replace every ‘.’ with //‘!’

As you can see, string methods return modified strings. String objects cannot be modified; they are immutable.

Object Oriented Programming in Java 31

Page 32: Java for C++ programers

Strings 4As we mentioned, string objects are immutable; this is because Java designers believe that most of the time, modifying strings is not a common task. If your application needs to change strings in place, you can use a different string-processing class called StringBuffer:

StringBuffer b=new StringBuffer("Hello");b.setChatAt(0, ‘N’); //Nellob.append(‘w’); //Nellowb.append(“text”); //Nellowtextb.insert(4, “ing”);b.delete(5, 9); //Nellob.setCharAt(0, ‘H’); //Hellob.reverse(); //olleH

StringBuffer objects are mutable; they can be modified. For more details, look at “Java: A Complete Reference”.

Object Oriented Programming in Java 32

Page 33: Java for C++ programers

Reading Input

Reading input from the keyboard is unbelievably difficult in Java. Like C++, Java has no built-in features for reading input from the keyboard. You would have to use long and complicated code to be able to read input from the keyboard.

One reason for this is because Java was designed for developing GUI applications which most often obtain their input by GUI elements such as dialog boxes, menus, etc.

For now, we will use a class called console which hides the low level complexities of reading input and presents a simple interface. When we have covered more topics in this course we will look at how we can develop our own classes for reading input.

We will now look at an example if reading input from the keyboard:

Object Oriented Programming in Java 33

Page 34: Java for C++ programers

Reading Input 2

import Corejava.Console;class InputTest{

public static void main(String[] args){ double x=Console.readDouble(“Enter a number: “);

System.out.println(x+2);}

}The import statement is similar to the include directive in C++; it imports the class Console defined in package Corejava into the program.

The Console class has a number of methods for reading input; in this example we use the readDouble method to read a double number from the keyboard. Other methods are readInt and readLine.

Object Oriented Programming in Java 34

Page 35: Java for C++ programers

Conditional Statements and Loops

A block or a compound statement is any number of Java statements enclosed within a pair of braces. Blocks define the scope of variables, as in C++. Consider the following:

public static void main(String[] args) { int n; ……. { //block int k; //k is only visible inside block } }

But, unlike C++, it is not possible to declare two identically named variables in two nested blocks. This is often a source of bugs in C++.

The simplest conditional statement is the if-statement:if (condition) statement;

Object Oriented Programming in Java 35

Page 36: Java for C++ programers

Conditional Statements and Loops 2

Java conditional statements and loops are the same constructs as in C++ and they behave exactly the same. Here is short program:class Test{

public static void main(String[] args){String s1;int JavaProgrammers=0, CplusplusProgrammers=0;for (int k=0; k<20; k++){

s1=Console.readLine("C++ or Java ? ");if (s1.equals("C++"))

CplusplusProgrammers++;else if (s1.equals("Java"))

JavaProgrammers++; }

for (int i=0; i<JavaProgrammers; i++) System.out.println( i+ " Java Programmers");

}}

Object Oriented Programming in Java 36

Page 37: Java for C++ programers

Conditional Statements and Loops 3

In Java, as in C++, you can break out of a loop using the break statement.For breaking out of deeply nested loops you can use labeled breaks:int nreadData:while(…){

……for(…){

if (n<0)break readData;

……}

}if (n<0) …… //deal with bad situationelse …… // proceed normally

The goto statement is used in C++ to have a similar effect.

Object Oriented Programming in Java 37

Page 38: Java for C++ programers

Conditional Statements and Loops 4A simple program demonstrating the Java for-loop:class ForLoops {

public static void main(String[] args){

int count;System.out.println(“How many times” +

“ shall I count? “);count=Console.readInt(“”);for (int i=1; i<=count; i++)

System.out.print(i + “\n”);}

}Java for-loops behave exactly the same as C++ for-loops. This for-loop will repeat n times where n is the number entered by the user. Java also supports the other common loops: while-loop and do-while-loop.

Object Oriented Programming in Java 38

Page 39: Java for C++ programers

Methods

As you know by now, everything in Java must be inside a class. You cannot have C++-style functions defined outside any classes. In Java, functions or procedures are called methods.

You should by now realize and appreciate the significance of functions or methods in solving problems. Some advantages of using methods:

- breaking down large programs into smaller ones- sharing the same procedure/methods in multiple programs- avoiding repeating the same piece of code again and again- etc…

As in C++, you can have two types of methods in a class: static methods and object methods. Static methods are those which act on the class itself and not part of any objects of the class. Ordinary methods or object methods are those which belong to objects of a class and do not operate on the class itself. So far we have seen static methods only.

Object Oriented Programming in Java 39

Page 40: Java for C++ programers

Methods 2We will now create a static method which we will use/call from the main method of the following program. This methods will not do much and is for demonstration purposes only.class MethodDemo{

public static void main(String[] args){

//will now call the myMethodmyMethod();

}public static void myMethod(){

System.out.println(“I am in myMethod!!”);}

}myMethod is called from within the main method. Return type is void and the method is static, so would not be available for any objects of this class.

Object Oriented Programming in Java 40

Page 41: Java for C++ programers

Methods 3Now we will look at another example in which we write a method that returns a value:class Recursion {

public static void main(String[] args){long num=0, result=0;num=Console.readInt(“Enter a number: “);result=myRecursiveMethod(num);System.out.println(“Factorial of “ + num +

“is” “ result”);}public static long myRecursiveMethod(long x){

if (x==0) //Try x=0 and see what happens return 1;else return x * (myRecursiveMethod(x-1));

}}

Object Oriented Programming in Java 41

Page 42: Java for C++ programers

Arrays

An array is a data structure for storing data elements of the same type in a contiguous area of memory. Arrays have many applications as you saw in the C++ course. Arrays in C/C++ can be a major source of bugs if the programmer is not careful. But Java arrays are much simpler than C/C++ arrays and they are protected from misuse.

In Java, arrays are objects and all objects in Java are created using the new operator. To declare an array and allocate memory:

int intArray[]=new int[10];

This statement declares an array object that can hold 10 integer numbers.The size or length of an array is stored in an attribute called length:

int intArraySize=intArray.length;

Arrays are protected from array boundary overruns. An exception is thrown if you attempt to index an element outside the array boundaries.

Object Oriented Programming in Java 42

Page 43: Java for C++ programers

Arrays 2Once you create an array, you cannot change its size; this is the case withC/C++ too. Java has another object vector which can grow and shrink as your program is running. Java vectors are similar to C++ STL vectors. Refer to your text books and the online SDK documentation for working with vectors.

You can create an array and initialize it at the same time:int intArray[]={1,2,3,4,5}; //no need for new

In this case, you do not need to use the new operator. The new operator is automatically called. You can also create anonymous arrays:

new int {1,2,3,4,5};And use it:

myMethod(new int {1,2,3,4,5});

You can use this syntax if you want to pass a temporary array to a method and you don’t want to create a local variable for it.

Object Oriented Programming in Java 43

Page 44: Java for C++ programers

Arrays 3

You can copy one array object into another, but then both will refer to the same array:class Arrays{

public static void main(String args[]){

int array1[]; //only a reference,no memoryint array2[]={1,2,3,4};array1=array2;array1[1]=0;System.out.println(array2[1]); //0

}}Both array objects refer to the same array. Array1 and array2 are references to objects (arrays); they are not themselves objects. Hence when you change an element in one array, it will effect the other array too.

Object Oriented Programming in Java 44

Page 45: Java for C++ programers

Arrays 4

The previous program would create two arrays as follows: array1

array2

If you want to copy values of one array into another, use the arraycopy method from the System class:class CopyArray { public static void main(String[] args) {

int[] smallPrimes={2,3,5,7,11,13}; int[] someNumbers={101,102,103,104,105,106,107}; System.arraycopy(smallPrimes,2, someNumbers,3,4); for (int i=0; i<smallPrimes.length; i++) System.out.print(i+ “after copy“ + someNumbers[i]);

}}

Object Oriented Programming in Java 45

4301

Page 46: Java for C++ programers

Arrays 5The method arraycopy copies the contents of one array into another array and its arguments: the first argument specifies the array to be copied, the second specifies the index of the first element from the first array to be copied, the third specifies the second array, the forth specifies the index of the second array and the fifth argument specifies the count of element to be copied. The output of the previous program would be:

0 after copy is 1011 after copy is 1022 after copy is 1033 after copy is 54 after copy is 75 after copy is 116 after copy is 13A runtime out-of-bound exception would be thrown if the array boundary is exceeded. In C++, the program would run without complaining.

Object Oriented Programming in Java 46

Page 47: Java for C++ programers

Arrays 6

Arrays can be passed to methods as arguments. Since arrays are objects and objects in Java are references, arrays are not copied when passed to methods. In the following example, we pass an array to a method to be sorted (bubble sort):

class BubbleSort {public static void main(String[] args){

int array[]=new int[10];for (int i=0; i<array.length; i++)

a[i]=1+(int) (Math.random() * 100);print(array);sort(array);print(array);

} //--->

Object Oriented Programming in Java 47

Page 48: Java for C++ programers

Arrays 7public static void sort(int[] a){

int i, j;for (i=0; i<a.length-1; i++)

for(j=0; j<a.length-1; j++)if(a[j]>a[j+1])

swap(a, j,j+1);}

} public static void swap(int[] a, int i, int j){

int temp=a[i];a[i]=a[j];a[j]=temp;

} //--->

Object Oriented Programming in Java 48

Page 49: Java for C++ programers

Arrays 8

public static void print(int[] a){

for (int i=0; i<a.length; i++)System.out.print(a[i] + “ “);

System.out.println();}

}As well as the main method, this program has 3 more methods: the print method to print out the elements of an array passed as an argument, the sort method used to bubble sort an array passed as argument and the swap method used in the sort method.

Note that array names like objects are references, hence when an array argument is passed to a method and is changed inside the method, the original array is effected. Also notice the swap method; any differences from the swap function implemented in C++?

Object Oriented Programming in Java 49

Page 50: Java for C++ programers

Arrays 9

The program also makes use of the Math.random() methods for producing a 10 random numbers between 1 and 100. This method returns a random number of type double in the range 0.0 to 1.0 but excluding 1.0. Each value between 0.0 and 1.0 has an equal chance of being chosen each time Math.random is called. To specify a range for the Math.random method of 1 to 6 use the following:

1+ (int) (Math.random() * 6);//for tossing a diceBetween 1 and 2:

1+ (int) (Math.random() * 2);//for tossing a coin

There are many similarities between arrays in Java and C++; but Java arrays are much safer to use than C++ arrays. C++ arrays are a big source of bugs and errors in C++ programming. Multi-dimensional arrays can be represented as arrays of arrays, as we saw in C++.

Object Oriented Programming in Java 50

Page 51: Java for C++ programers

Arrays 10

As you know, arrays are objects, and objects are called reference types.With reference types, there are two kinds of equality: equality of reference and equality of object.

When you use == operator with two objects (or two arrays) for equality, you are testing for equality of references (whether two references point to the same object):

int array1[]={1,2,3};int array2[]={1,2,3};if(array1==array2) //false,equality of references

To test two arrays for equality of object, use the Arrays.equals(a1,a2) method, which is defined in java.util.Arrays:

if(Array.equals(array2, array1))//true

The class Arrays defines other utility methods useful when working with arrays such as searching and sorting methods. For more info, consult the SDK documentation on the department’s intranet.

Object Oriented Programming in Java 51

Page 52: Java for C++ programers

Command-line Arguments

As in C++, you can pass command-line arguments to your programs to work on:class Add {

public static void main(String[] args) {int num1, num2;if(args.length!=2) { //only count

argumentsnum1=0; num2=0; //unlike C++

}else {num1=Integer.parseInt(args[0]);//parse tonum2=Integer.parseInt(args[1]);//integer}System.out.println(num1+num2);

}} Object Oriented Programming in Java 52

Page 53: Java for C++ programers

Formatting Numbers

Look at the following statements:x=10000.0/3; yields the value 3333.3333333333335

To control the output, for example to specify 2 digits after the decimal point, separate groups of 1000s with commas, show trailing 0s, and don’t show leading 0s:import java.text.DecimalFormat;class Test{

public static void main(String[] args){ double d=10000/3.0; DecimalFormat dm=new DecimalFormat(",##0.00"); System.out.println(dm.format(d));}

}For more details, refer to “Java The Complete Reference” or the online Java tutorial.

Object Oriented Programming in Java 53

Page 54: Java for C++ programers

Exercises

1) Write a program that asks the user for a starting value and an ending value and then prints out all the integers (inclusive) between those two values.

2) Write a program that asks the user for a word and prints that word as many times as the length of that word.

3) Write a program to ask the user for two words and then prints out the two words on one line such that the two words are separated by dots and the total length of the line is 30:

Enter first words: ArraysEnter second word: 126Arrays…………………126

This could be used as part of an indexing system for a book.

Object Oriented Programming in Java 54

Page 55: Java for C++ programers

Exercises

4) Write a program that asks the user for a string, and then echoes it to the screen one character per line.

5) Write a program that asks the user for 10 integers and after storing them in an array, finds the maximum, minimum and average of the 10 numbers.

6) Write a method that takes an integer value as parameter and outputs the returns the number with its digits reversed (e.g., 123 to 321) Then test your method in a java application.

7) Write a method that takes a string as parameter and returns the string with its characters reversed. (tool to loot) Then test your method in a Java application.

8) Write a method that takes a string value as parameter and determines if the string is a palindrome. Use the method you wrote for exercise 7

Object Oriented Programming in Java 55

Page 56: Java for C++ programers

Exercises9) This is a classic computer science problem called “Towers of Hanoi”. Look at the following figure: peg 1 peg 2 peg3

The problem is to move (in this example) the 5 disk to peg 3 such that:- Exactly one disk is moved at a time- at no time a larger disk may be placed above a smaller disk.- The middle peg may be used for temporarily holding disks.

Write a method that takes 4 parameters: number of disks to be moved, the peg on which these disks are initially located, the peg to which this stack of disks is to be moved, the temporary peg. Your method should out put the precise sequence of peg-to-peg disk transfers.

Object Oriented Programming in Java 56

Page 57: Java for C++ programers

Exercises

10- Write a method that takes an array and an integer value and returns the subscript of the specified value if the value exists in the array. Use linear search for this algorithm. Test your method.

11- Rewrite the method in exercise 10 such that it uses the binary search algorithm instead. The linear search algorithm is suitable for small arrays or unsorted arrays. For large arrays linear search is inefficient; if the array is sorted, the high-speed binary search can be used as follows: “the algorithm locates the middle array and compares it to the search value; if they are not equal, the problem is reduced to searching half of the array. If the search value is smaller than the middle array element, the first half of the array is searched, otherwise the second half. This process is continued until the search value is equal to the middle element of a subarray or until the subarray consists of one element that is not equal to the search value, i.e. the search value in not found. You also need to use a sort algorithm for this problem”

You should solve this problem in two ways: using iteration and recursion.

Object Oriented Programming in Java 57

Page 58: Java for C++ programers

OO Programming

In procedural programming languages such as C and Pascal, programming tends to be action-oriented whereas in OO programming languages such as Java and Smalltalk, programming object-oriented.

In action-oriented programming, the focus is actions or functions; in OO programming, the focus is objects. Suppose ob is an object:

print(ob); //focus is function/actionob.print(); //focus is object

Most things in the world are classified: a class of students, a class of fish, a class of birds, a class of objects. The word ‘class’ means a type or a group of things which have some common attributes or properties. In most object oriented programming languages, the construct class is used to create a new type or class of objects.

Definition: A class is a collection of data, stored in named fields, and code, organized into named methods, that operates on that data.

Object Oriented Programming in Java 58

Page 59: Java for C++ programers

OO Programming 2

The fields and methods are called members of a class. The members of a class can be of two types: static or class members associated with the class itself and instance members associated with individual instances of the class (i.e., with objects):

- class fields- class methods- instance fields- instance methods

An example:public class Circle { //a class/static field public static final double PI=3.14159; //a class/static method public static double radiansToDegrees(double rads) {

Object Oriented Programming in Java 59

Page 60: Java for C++ programers

OO programming 3return rads * 180 / PI;

}//an instance fieldpublic double r;//two instance methodspublic double area() {

return PI * r * r;}public double circumference(){

return 2 * PI * r;}

}

The static modifier says that the field is a class field. The final modifier says that this field does not change. The public modifier says that this field can be used by any code; it’s a visibility modifier which we will cover in more detail later.

Object Oriented Programming in Java 60

Page 61: Java for C++ programers

OO programming 4

It’s important to know that a class filed is associated with the class itself and not with any instances/objects of that class and that there is only a single copy of it. This field can be accessed inside the class by writing its name only PI, and to access it from outside the class you must write Circle.PI.

A class filed is similar to a global variable; in Java the namespace/collision problem is avoided because global variables must be declared within classes and this reduces chances of name collision.

Class methods are declared with the static modifier. Like class fields, they can be called from within the class by just writing its name, but it’s good programming style to specify the class name in which it is a member of, to make it clear that a class method is being invoked.

Class methods can use class fields or other class methods but they cannot use any instance fields or methods. Why?

Object Oriented Programming in Java 61

Page 62: Java for C++ programers

OO programming 5

Any field declared without the static modifier is an instance field:public double r;

Instance fields are associated with instances or objects of the class; each instance of the class has its own copy of an instance field.

Any method not declared with the static modifier is an instance method. Instance methods operate on instances of the class, not on the class itself. Instance methods have access to both class fields and class methods.

Instance methods operate on class instances or objects; they know which object they operate on because they are passed an implicit reference to the object they operate on; this reference is called this. (As in C++). The instance method area could have been written as:

public double area(){return Circle.PI * this.r * this.r;

}

Object Oriented Programming in Java 62

Page 63: Java for C++ programers

OO programming (Constructors) 6

To create and initialize an object:Circle c=new Circle();

The operator new creates a new object of type Circle. In the class Circle defined earlier, no constructors were written; Java provided a default constructor that takes no parameters and performs no initialization. It is always better to specify a constructor for every new class you define to specify how a new object of that class would be initialized:

public Circle(double r) {this.r=r;}//why this.r?To create an instance/object of type Circle:

Circle c=new Circle(5.0); //object creation & //initialization on

one lineWhen writing a constructor for a class:

- the constructor name is always the same the class name- the constructor has no return values but may take parameters- the constructor should perform initialization of the new object

Object Oriented Programming in Java 63

Page 64: Java for C++ programers

OO programming (Constructors) 7

To provide flexibility in initializing a new object, often multiple constructors are defined:

public Circle() { r=1.0;}public Circle(double r) { this.r=r;}

The two constructors must have different parameter lists or signatures (method overloading)

One of the uses of the this keyword is to invoke constructor from within another constructor:

public Circle(double r) { this.r=r;} public Circle() { this(1.0);}

Instance fields and class fields are initialized by default: primitive numeric types to 0, booleans to false and reference types to null. But local variables (declared inside methods) are not initialized by default. You should initialize them before use.

Object Oriented Programming in Java 64

Page 65: Java for C++ programers

OO programming 8

In Java, memory occupied by an object is automatically reclaimed when the object is no longer needed. This is achieved by a process called Garbage Collection. The programmer does not have to worry about releasing or reclaiming memory used by object. This greatly reduces bugs and helps programmers be more productive.

The Java interpreter knows which objects it has allocated. It also knows which variables or objects refer to which other objects. So the interpreter can determine which objects are no longer referenced by any variable and it then destroys those objects.

The Java garbage collector runs as a low-priority thread, so it does most of its work when nothing else is going on. The only time that it must run even when some high-priority thread is going on is when available memory is dangerously low. But this doesn’t happen often because the low-priority thread is running in the background and cleans unused objects.

Object Oriented Programming in Java 65

Page 66: Java for C++ programers

OO programming 9The garbage collection method used in Java is not as efficient as manually managing memory (in C++), but it makes programming a lot easier and less prone to errors. For most real-world programs, rapid development, lack of bugs and easy maintenance are more important than speed or memory efficiency.

A memory leak is occurs when memory is allocated and never reclaimed. A memory leak can occur in Java when a valid, but unused, reference to an unused object is left hanging around. For example when a method runs for a long time or forever, the local variables in that method can contain object references longer than they are required:

public static void main(String[] args) { int big_array[]=int[1000000]; int result=compute(big_array);//big_array no

//longer needed big_array=null; //destroy the reference //so that its memory can be released for_loop; //method will run forever}

Object Oriented Programming in Java 66

Page 67: Java for C++ programers

OO programming (finalize) 10Constructors are used to create objects: obtain memory, obtain resources, initialize object data…

Finalizers are used to return allocated resources back to the system such as file, print and network connections. Remember that the garbage collector automatically reclaims memory. So you don’t need to worry about reclaiming memory, except in some situations where you may have to help the garbage collector in identifying unused objects.

A class’s finalizer is called just before the garbage collector destroys the object. It always has the name finalize, returns no values, has return type void and takes no parameters. If you don’t define a finalize method for your class, a default one is created that does nothing.

Finalizers are a bit similar to C++’s destructor functions which are used to return resources to the system. Finalizers are not as useful and necessary as C++’s destrcutors and are not often used in normal Java programming. The following is an example demonstrating how finalizers are used:

Object Oriented Programming in Java 67

Page 68: Java for C++ programers

OO programming (finalize) 11

import javax.swing.*;public class EmployeeTest{

public static void main(String[] args){

String output="Hello Finalize";Employee e= new Employee(“X", “YZ");JOptionPane.showMessageDialog(null,

output,"Finalizer Demo", JOptionPane.INFORMATION_MESSAGE);

e=null; //mark for garbage collectionSystem.gc(); //suggest that GC be calledSystem.exit(0);

}}

Object Oriented Programming in Java 68

Page 69: Java for C++ programers

OO programming (finalize) 12class Employee{

public Employee(String fName, String lName){this.fName=fName;this.lName=lName;System.out.println("Constuctor:" + fName+" “ +lName);

}protected void finalize(){

System.out.println("Finalizer Called");}private String fName, lName;

}Finalizer methods are usually declared as protected so that subclasses can directly access and run them. You could also declare them as publicbut information hiding and encapsulation may be compromised.

The output of this program is a frame sowing the message: “Hello Finalize”

Object Oriented Programming in Java 69

Page 70: Java for C++ programers

OO programming (Inheritance) 13

Inheritance allows new classes to be created by reusing existing classes, thus saving time in software development. New classes acquire proven and debugged properties of existing classes.

I Java, the keyword extends is used to inherit a new class from an existing class:

class Child extends Parent {….}The new class Child is the subclass and the Parent is the superclass. Unlike C++, Java does not support multiple inheritance, but it supports interfaces which allow Java achieve many of the advantages of multiple inheritance without the associated problems.

Every object of the subclass is also an object of the super-class but not the other way round. Subclass methods and methods of other classes in the same package as the superclass can directly access protected superclass members.

Object Oriented Programming in Java 70

Page 71: Java for C++ programers

OO programming (Inheritance) 14

Every class in Java must inherit from a superclass; if a new class does not explicitly extend another class, Java implicitly uses the Object class as the superclass for the new class. Class Object provides a set of methods that can be used with any object of any class.

Consider the following example which is taken from the textbook:class Point {

protected int x, y;public Point() {

setPoint(0, 0);}public Point(int a, int b) {

setPoint(a, b);}//see next page…

Object Oriented Programming in Java 71

Page 72: Java for C++ programers

OO programming (Inheritance) 15

public void setPoint(int a, int b) {x=a; y=b;

}public int getX() { return x;}public int getY() { return y;}public String toString() {

return “[“ + x + “, “ + y + “]”;}}Public class Circle extends Point{

protected double radius;public Circle() {

setRadius(0);}//see next page…

Object Oriented Programming in Java 72

Page 73: Java for C++ programers

OO programming (Inheritance) 16

public Circle(double r, int a, int b){super(a, b);setRadius(r);

}public void setRadius(double r) {

radius= (r >=0.0 ? R : 0.0);}public double getRadius() { return radius;}public double area() {

return Math.PI * radius * radius;}public String to String(){

return “Center= “ + “[“ x + “, “ + y +“; Radius= “ + radius; }

}

Object Oriented Programming in Java 73

Page 74: Java for C++ programers

OO programming (Inheritance) 17import java.text.DecimalFormat;import javax.swing.JOptionPane;Public class InheritanceTest {

public static void main(String[] args) {Point pointRef, p;Circle circleRef, c;String output;p=new Point(30, 50);c=new Circle(2.7, 120, 89);output=“Point p: “ + p.toString() +

“\nCircle c: “ +c.toString();pointRef=c; //since a circle is-a pointoutput+=“\nCircle c (via pointRef): “ +

pointRef.toString();circleRef=(Circle) pointRef;//downcast//see next page…

Object Oriented Programming in Java 74

Page 75: Java for C++ programers

OO programming (Inheritance) 18output+=“\nCircle c (via circleref): “ +

circleRef.toString();DecimalFormat precision2=new DecimalFormat(“0.00”);output+=“\nArea of c (via circleRef): “ +

precision2.format(circleRef.area());if(p instanceof Circle) {

circleRef=(Circle) p;output+=“\nCast Successful”;

}else

output+=“\np does not refer to a Circle”;JOptionPane.showMessageDialog(null, output,

“Demonstarting the \”is-a \” relationship”,JOptionPane.INFORMATION_MESSAGE);

System.exit(0);}

Object Oriented Programming in Java 75

Page 76: Java for C++ programers

OO programming (Inheritance) 19

In this example, class Circle inherits from class Point and adds members specific to itself:

- Circle overrides Point’s toString method (polymorphism)- Point and Circle both have a default constructor as well as a parameterized constructor- Subclass Circle needs to call superclass Point’s parameterized constructor using super along with any required arguments, and this statement must come before any other statements.- Default constructors are invoked automatically.- superclass objects or references can be used to refer to subclass objects because of the is-a relationship, hence the statement pointRef=c;- explicit casting is needed to make a Circle object to refer to a Point object, hence the statement: circleRef= (Circle) pointRef;

Object Oriented Programming in Java 76

Page 77: Java for C++ programers

OO programming (Inheritance) 20- attempting to cast a Point object to a Circle object is an error, so

the statement: circleRef=(Circle) p; is illegal because p refers to a Point object.- the operator instanceof is used to check whether the object to which [ refers is a Circle. - superclass constructors are not inherited; subclass constructors

can call superclass constructors using the super reference. If a class defines a finalize method, any subclass finalize method should call the superclass finalize method as its last action. The following simplified example illustrates the order in which constructor and finalize methods are called:

class Point {protected int x, y;public Point() { x=0; y=0;

System.out.println(“Point Cons: “ + this); }

Object Oriented Programming in Java 77

Page 78: Java for C++ programers

OO programming (Inheritance) 21public Point(int a, int b){

x=a; y=b;System.out.println(“Point Cons” “ + this);

}protected void finalize(){

System.out.println(“Point finalize: “+this);

}public String toString(){

return “[“ + x+ “, ” + y + “]”;}}

}class Circle extends Point{

protected double radius;public Circle() {

setRadius(0);System.out.println(“Circle Cons: “ + this);

}

Object Oriented Programming in Java 78

Page 79: Java for C++ programers

OO programming (Inheritance) 22public Circle(double r, int a, int b){

super(a, b);radius-r;System.out.println(“Circle Cons: “ + this);

}public String to String(){

return “Center= “ + “[“ x + “, “ + y +“; Radius= “ + radius;

}protected void finalize(){

System.out.println(“Circle finalize:“+this);super.finalize();

}public String toString(){ return “Center=“ +

super.toString() + “; Radius=“+radius;}

}The keyword super can be used to access parent class members.

Object Oriented Programming in Java 79

Page 80: Java for C++ programers

OO programming (Inheritance) 23

public class Test{public static void main(String[] args){

Circle c1, c2;c1=new Circle(4.5,72,29);c2=NEW Circle(10,5,5);c1=null; c2=null;System.gc(); }

}// the output:Point Cons Center=[72, 29]; Radius=0.0Circle Cons: Center=[72, 29]; Radius=4.5Point Cons Center=[5, 5]; Radius=0.0Circle Cons: Center=[5, 5]; Radius=10.0Circle finalize: Center=[72, 29]; Radius=4.Point finalize: Center=[72, 29]; Radius=4.5Circle finalize: Center=[5, 5]; Radius=10.0Point finalize: Center=[5, 5]; Radius=10.0

Object Oriented Programming in Java 80

Page 81: Java for C++ programers

OO programming (Inheritance) 24

In Java, every class has a superclass called Object; the class Object has a number of methods which are inherited by any class you create. The method toString() is one such method which returns a textual representation of the object. You should always try to override this method as in this example. Outputting the this reference of an object, invokes the toString() method. Also, if you try to output a reference object you implicitly invoke the toString() method:

System.out.println(c1);In this example, after we finish with c1 and c2 objects, we set them to null to indicate that they are no longer needed and then ask that the system’sgarbage collector be called with the call System.gc(). Java guaranteesthat before the garbage collector runs to reclaim the space for each object, the finalize method for each object is called but it does not guarantee the order in which objects will be garbage collected.

Object Oriented Programming in Java 81

Page 82: Java for C++ programers

OO programming (Polymorphism) 25

You can have an inheritance hierarchy where a number of classes extend from a parent class:

Person ---> Students ---> Undergraduate ---> …This is called an inheritance hierarchy. In OOP, when you invoke a method on an object, you send that object a message. When a method is applied to an object of class in an inheritance hierarchy the following occurs:

- the class (subclass) checks whether or not it has a method with that name and with exactly the same parameters. If so, it uses it.

If not:- the parent class becomes responsible for handling the message and looks for a method with that signature. If so, it uses it.

This process continues until a match is found. If not match is found, a compile-time error is reported.

Object Oriented Programming in Java 82

Page 83: Java for C++ programers

OO programming (Polymorphism) 26

Remember that inheritance defines the is-a relationship. The is-a relationship allows subclass objects to be treated as superclass objects, because a subclass object IS A superclass object. Because a student IS A person.

Method-overriding refers to the idea of having a subclass contain a method with the same signature as that of a method in its parent class. In this case, the subclass method overrides the parent class method.

An objects ability to decide what method to apply to itself, depending on where it is in the inheritance hierarchy, is called polymorphism. What makes polymorphism work is late-binding, which means that the compiler does not generate the code to call a method at compile-time; instead the compiler generates code to calculate which method to call, using type information from the object. (In C++, you had to declare functions as virtual for dynamic binding but in Java this is the default behavior)

Object Oriented Programming in Java 83

Page 84: Java for C++ programers

OO programming (Polymorphism) 27In the following example, we see how polymorphism is achieved in java:

import corejava.*;

public class ManagerTest{ public static void main(String[] args) { Manager boss = new Manager("Carl Cracker", 75000, new Day(1987,12,15)); boss.setSecretaryName("Harry Hacker");

System.out.println(boss.Name()); Employee[] staff = new Employee[3];

staff[0] = boss; staff[1] = new Employee("Harry Hacker", 35000, new Day(1989,10,1)); staff[2] = new Employee("Tony Tester", 38000,

new Day(1990,3,15));

Object Oriented Programming in Java 84

Page 85: Java for C++ programers

OO programming (Polymorphism) 28 int i; for (i = 0; i < 3; i++) staff[i].raiseSalary(5); for (i = 0; i < 3; i++) staff[i].print(); System.out.println("The department secretary is " + boss.getSecretaryName());

}}class Employee{ public Employee(String n, double s, Day d) { name = n; salary = s; hireDay = d; } public void print() { System.out.println(name + " " + salary + " " + hireYear()); }

Object Oriented Programming in Java 85

Page 86: Java for C++ programers

OO programming (Polymorphism) 29 public void raiseSalary(double byPercent) { salary *= 1 + byPercent / 100; } hireYear() { return hireDay.getYear(); } String Name() { return name;}

private String name; private double salary; private Day hireDay;}class Manager extends Employee{ public Manager(String n, double s, Day d) { super(n, s, d); secretaryName = ""; }

Object Oriented Programming in Java 86

Page 87: Java for C++ programers

OO programming (Polymorphism) 30public void raiseSalary(double byPercent) { // add 1/2% bonus for every year of service Day today = new Day(); double bonus = 0.5 * (today.getYear() - hireYear()); super.raiseSalary(byPercent + bonus); } public void setSecretaryName(String n) { secretaryName = n; } public String getSecretaryName() { return secretaryName; }

private String secretaryName;}

Class Manager extends class Employee. In the test class we create 3

Object Oriented Programming in Java 87

Page 88: Java for C++ programers

OO programming (Polymorphism) 31objects, 2 of type employee and one of type Manager. Method raiseSalary() is overridden in subclass Manager. Then we create an array of type Employee and store the 3 objects in the array, even the object boss of type Manager.

Then we invoke the method raiseSalary() on all the array elements.Since this method is overridden, its correct version is applied to each individual element.

Also note that since salary is declared private Manager’s raiseSalary() cannot directly access it; it uses the public interface methods of the superclass Employee to access it, even though every Manager object has a salary field. We could have declared it as protected and bypass this restriction.

If you don’t want a class to be inherited or a method overridden, declare them as final. You may do this for efficiency (inlining) and safety.

Object Oriented Programming in Java 88

Page 89: Java for C++ programers

OO programming (Abstract Classes) 32

Abstract classes are classes that cannot be instantiated. Abstract classes are used to factor out common behavior into a general class. You cannot create objects whose type is abstract but you can have abstract class variables that refer to some extended class object.

Abstract classes may contain abstract methods: methods that have no definition in the original class and must be defined in non-abstract subclasses (pure virtual classes in C++).abstract class Message{

public abstract void play();//must be overridden}class TextMessage extends Message{

public void play() { System.out.println(“Text Message”);

}

Object Oriented Programming in Java 89

Page 90: Java for C++ programers

OO programming (Abstract Classes) 33

Rules about abstract classes/methods:- Any class with an abstract method is automatically abstract and must be declared as such. Also, an abstract class cannot be instantiated.

-A subclass of an abstract class can be instantiated only if it overrides each of the abstract methods of its superclass and provides an implementation for all of them. (Concrete class, as opposed to abstract)

- If a subclass of an abstract class does not implement all the abstract methods it inherits, that subclass is itself abstract.

- static, private and final methods cannot be abstract, since they cannot be overridden by a subclass.

- A class can be declared abstract even though it does not have any abstract methods.

Object Oriented Programming in Java 90

Page 91: Java for C++ programers

OO programming (Object) 34

As mentioned before, the Object class is the ultimate ancestor; every class in Java extends this class. You can use a variable or object of type Object to refer to any type:

Object obj=new Employee(“H. Hacker”, 10000);But you need to cast this object to the original type to use Employee objects capabilities:

Employee e=(Employee) obj;The Object class has the method equals which returns true if two object references refer to the same object. For your new classes, you should always override this method so that it tests for object equality not reference equality. For example, for the Employee class:

public boolean equals(Object obj){if(!(obj instanceof Employee)) return false;Empoyee e= (Employee) obj;return name.equals(b.name) &&

salary.equals(b.salary) ...}

Object Oriented Programming in Java 91

Page 92: Java for C++ programers

OO programming (Object) 35

Note that the equals method for the String class is overridden by Java.Another method of Object is toString, which we saw earlier. Since objects of any type or class can be held in variables of type Object, we can use this for generic programming. For example, suppose we need a method that takes an array and a value as parameters and we want the method to return the index of that value in the array:static int find(Object[] ob, Object value){

for (int i=0; i<ob.length; i++)if(ob[i].equals(value)) return i;

return -1; //not found}Employee[] staff=new Employee[10];Employee e=new Employee(“Hacker”, 10000);//...int n=find(staff, e); //works on any object array

Object Oriented Programming in Java 92

Page 93: Java for C++ programers

OO programming (Interfaces) 36

Java does not support multiple inheritance. A Java class can extend only one class. But in some situations we need classes that inherit behavior from more than one parent class. The solution to this is using Java interfaces.

Many believe that multiple inheritance, in C++, introduces more complexity and work on the part of the programmer than solve problems. For example, we saw how it causes complications in dealing with multiple copies of inherited members.

An interface is a class but a class which can only contain abstract methods and constants. It cannot contain any implementation for its methods nor can have any instance fields because an interface is a specification and has no implementation detail. Its methods are implicitly abstract.

Any class that implements an interface must define the interface methods or must itself be an abstract class.

Object Oriented Programming in Java 93

Page 94: Java for C++ programers

OO programming (Interfaces) 37A class can implement as many interfaces as it needs. The following example is taken from the textbook:interface Shape { public abstract double area(); public abstract double volume(); public abstract String getName(); } class Point implements Shape { protected int x, y; // coordinates of the Point public Point() { setPoint( 0, 0 ); } public Point( int a, int b ) { setPoint( a, b ); } public void setPoint( int a, int b ){ x = a; y = b; }//see next page

Object Oriented Programming in Java 94

Page 95: Java for C++ programers

OO programming (Interfaces) 38

public int getX() { return x; } public int getY() { return y; } public String toString() {

return "[" + x + ", " + y + "]"; } public double area() { return 0.0; } public double volume() { return 0.0; } public String getName() { return "Point"; }}public class Circle extends Point { protected double radius; public Circle() {

setRadius( 0 ); }//see next page

Object Oriented Programming in Java 95

Page 96: Java for C++ programers

OO programming (Interfaces) 39

public Circle( double r, int a, int b ){ super( a, b ); setRadius( r ); } public void setRadius( double r ){

radius = ( r >= 0 ? r : 0 ); } public double getRadius() { return radius; } public double area() {

return Math.PI * radius * radius; } //see next page

Object Oriented Programming in Java 96

Page 97: Java for C++ programers

OO programming (Interfaces) 40 public String toString(){

return "Center = " + super.toString() + "; Radius = " + radius; } public String getName() { return "Circle"; }}public class Cylinder extends Circle { protected double height; // height of Cylinder public Cylinder() {

setHeight( 0 ); } public Cylinder( double h, double r, int a, int b) { super( r, a, b ); setHeight( h ); } public void setHeight( double h ){

height = ( h >= 0 ? h : 0 ); } //see next page

Object Oriented Programming in Java 97

Page 98: Java for C++ programers

OO programming (Interfaces) 41

public double getHeight() { return height; } public double area(){ return 2 * super.area() + 2 * Math.PI * radius * height; } public double volume() {

return super.area() * height; } public String toString(){

return super.toString() + "; Height = " + height;

} public String getName() { return "Cylinder"; }}//see next page

Object Oriented Programming in Java 98

Page 99: Java for C++ programers

OO programming (Interfaces) 42import javax.swing.JOptionPane;import java.text.DecimalFormat;public class Test { public static void main( String args[] ){ Point point = new Point( 7, 11 ); Circle circle = new Circle( 3.5, 22, 8 ); Cylinder cylinder = new Cylinder( 10, 3.3, 10, 10 ); Shape arrayOfShapes[]; arrayOfShapes = new Shape[ 3 ]; arrayOfShapes[ 0 ] = point; arrayOfShapes[ 1 ] = circle; arrayOfShapes[ 2 ] = cylinder; String output = point.getName() + ": " + point.toString() + "\n" + circle.getName() + ": " + circle.toString() + "\n" + cylinder.getName() + ": " + cylinder.toString(); Object Oriented Programming in Java 99

Page 100: Java for C++ programers

OO programming (Interfaces) 43 DecimalFormat precision2 = new DecimalFormat( "0.00" ); for ( int i = 0; i < arrayOfShapes.length; i++ ) { output += "\n\n" + arrayOfShapes[ i ].getName() + ": " + arrayOfShapes[ i ].toString() + "\nArea = " + precision2.format( arrayOfShapes[ i ].area() ) + "\nVolume = " + precision2.format( arrayOfShapes[ i ].volume() ); } JOptionPane.showMessageDialog( null, output, "Demonstrating Polymorphism", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); }}This example demonstrates how interfaces are used in a class hierarchy. In C++ this would be achieved by a combination of multiple inheritance and pure virtual functions.

Object Oriented Programming in Java 100

Page 101: Java for C++ programers

OO programming (Interfaces) 44Abstract classes or interfaces: Interfaces are used in place of abstract classes when there is no default implementation and no instance fields. In addition to providing support for multiple inheritance, interfaces are commonly used in GUI programming as will soon see. Usually interfaces are defined in classes of their own with the same name as the interface name and in a .java file.

Since they both may contain abstract methods it is not possible to instantiate objects from them and they may not define constructor methods. Interfaces can only contain abstract instance methods and constants whereas abstract classes can contain instance fields and a mixture of abstract and instance methods. If you add a new method to an interface which has already been implemented by some class, you break that subclass. This is not a problem with abstract classes.

An interface defines a public API. All methods of an interface are implicitly public, even if the public modifier is omitted. Also, it is an error to define protected or private methods in an interface.

Object Oriented Programming in Java 101

Page 102: Java for C++ programers

OO programming (Interfaces) 45Here is another example using interfaces:import java.util.*;public class Interface1{

public static void main(String[] l){Employee[] staff=new Employee[3];staff[0]=new Employee("Harry", 35000, new

Date(1990,1,2));staff[1]=new Employee("Barry", 32000, new

Date(1992,5,6));staff[2]=new Employee("Jerry", 29000, new

Date(1998,11,2));ArrayAlg.Sort(staff);for(int i=0; i<staff.length;i++)System.out.println(staff[i]);}

}//--->

Object Oriented Programming in Java 102

Page 103: Java for C++ programers

OO programming (Interfaces) 46interface Sortable{

public int compareTo(Sortable b);}class Employee implements Sortable {

public Employee(String n, double s, Date d){ name=n;

salary=s;hireDate=d; }

public void raiseSalary(double byPercent){salary*=1+byPercent/100;

}public String getName(){return name;}public double getSalary(){return salary;}public String toString(){

return name + " " + salary + " " + hireYear();}

Object Oriented Programming in Java 103

Page 104: Java for C++ programers

OO programming (Interfaces) 47public int hireYear(){

return 1900 +hireDate.getYear();}public int compareTo(Sortable b){

Employee eb=(Employee) b;if(salary<eb.salary) return -1;if (salary>eb.salary) return 1;return 0;

}private String name;private double salary;private Date hireDate;

}//--->

Object Oriented Programming in Java 104

Page 105: Java for C++ programers

OO programming (Interfaces) 48class ArrayAlg{

public static void Sort(Sortable[] a){for(int i=0; i<a.length; i++){

for(int j=0; j<a.length-1; j++){

if(a[j].compareTo(a[j+1])<0){

Sortable temp=a[j];a[j]=a[j+1];a[j+1]=temp;

}}

}}

}

Object Oriented Programming in Java 105

Page 106: Java for C++ programers

OO programming (Interfaces) 49

In this example, the employee class implements the Sortable interface which has only one method, the compareTo method. Any class which implements this interface must override its methods.

The class ArrayAlg contains a static method Sort which takes an array of objects of any class which implements the Sortable interface and sorts the elements of the array in ascending order. This example uses the bubble sort algorithm, but you can replace it with any other sorting routine.

This example used an interface; you could have used an abstract class to achieve the same effect. But, if the employee class had already inherited (extended) another class, say a class Person, then you wouldn’t have been able to use abstract classes. Why is this?

Instead of the user-defined Sortable interface, you could use the Java library Comparable interface, which has a similar definition to our Sortable interface.

Object Oriented Programming in Java 106

Page 107: Java for C++ programers

OO programming (inner classes) 50

An inner class is a class that is defined inside another class. One of the main reasons of having inner classes is because they are very convenient when you are writing event-driven programs in Java. Since we will study GUI and event-driven programming later on, we need to understand inner classes in detail.

Inner classes are defined inside other classes. The following example demonstrates this feature:Public class Parcel{

class Contents{private int i=1;public int value(){return i;}

}class Destination{

private String label;Destination(String whereTo){ label=whereTo;}

}

Object Oriented Programming in Java 107

Page 108: Java for C++ programers

OO programming (inner classes) 51

String readLabel() {return label;}public void ship(String dest){

Contents c=new Contents();Destination d=new Destination(dest);System.out.println(d.readLabel());

}public static void main(String[] a){

Parcel p=new Parcel();p.ship(“London”);

}}

This example shows how you can create and use inner classes. In this example, two inner classes are defined inside the outer class Parcel. In the method ship(), objects are created of type Contents and Destination.When you compile this program, 3 class files are created, one for each class. Inner classes are given the name of OuterClass$InnerClass format.

Object Oriented Programming in Java 108

Page 109: Java for C++ programers

Exercises

12. Use the SDK documentation to find the method toString() in the Object class. Create a class and override this method in your new class.

13. Use the SDK documentation to find the method equals() in the Object class.

14. Create a Java program that will direct a cashier how to give change. The program has two inputs: the amount due and the amount received from the customer. Compute the difference and then compute the 10-Dinars, 5-Dinars, Dinars that the customer will receive in return. For example:

How much money was due? 100How much money was given? 72

The cashier should return:2 10-Dinars1 5-Dinars3 Dinars

Object Oriented Programming in Java 109

Page 110: Java for C++ programers

Exercises

15. Consider the following two classes: public class ClassA {

public void methodOne(int i) { } public void methodTwo(int i) { } public static void methodThree(int i) { } public static void methodFour(int i) { }

} public class ClassB extends ClassA {

public static void methodOne(int i) { } public void methodTwo(int i) { } public void methodThree(int i) { } public static void methodFour(int i) { }

}

a. Which method overrides a method in the superclass?b. Which method hides a method in the superclass?

Object Oriented Programming in Java 110

Page 111: Java for C++ programers

Exercises

16. What is wrong with the following interface? public interface SomethingIsWrong {

public void aMethod(int aValue){ System.out.println("Hi Mom");

} }

17. Consider the following code:public interface Comparable{

public int compareTo(Object o);}public class Card implements Comparable{

public int compareTo(Object o){Card cardB=(Card) o;...

}}

Object Oriented Programming in Java 111

Page 112: Java for C++ programers

ExercisesPublic class Employee implements Comparable{

public int compareTo(Object o){Employee e=(Employee) o;...

}}

Now consider the following fragments:

a) Which of the fragments are correct? Which are not? Explain.

Object Oriented Programming in Java 112

Page 113: Java for C++ programers

Exercises

b) In Card, can we replace public int compareTo (Object b)by public int compareTo (Card b) ? Why ?c) In Card, can we replace Card cardB=(Card)b by Card cardB=b ?

Why ?

18. Distinguish between non-abstract methods and abstract methods.19. A class can only extend one parent class in Java. How can a class

inherit behaviour from more than one class. 20. What are the differences between abstract classes and interfaces.

21. What is an interface? a.    An interface is a collection of constants and method declarations. b.    An interface is a class that a child class can extend. c.    An interface is a collection of GUI components. d.    An interface is the collection of public methods of a class.

Object Oriented Programming in Java 113

Page 114: Java for C++ programers

Exercises

22. Can an interface ever contain method bodies? a.    No. b.    Yes. c.    Sometimes. d.    Always.

23. When a class implements an interface, what must it do? a.    It must redefine each constant from the interface. b.    It must declare and provide a method body for each method in the interface. c.    It must declare a variable for each constant in the interface. d.    It must include a private method for each method in the interface

24. Which of the following is true? a.    A child class can extend a parent or implement an interface, but not do both.

b.    A child class can extend just one parent and can implement just one interface. c.    A child class can extend just one parent and can implement zero or more interfaces.

d.    A child class can extend zero or more parents, and can implement zero or more interfaces.

25. . Is the following a correct way to start out a class definition: public class SomeClass implements MyInterface

Object Oriented Programming in Java 114

Page 115: Java for C++ programers

Exercisesa.    No—SomeClass must also extend a base class. b.    No—SomeClass cannot be public if it implements an interface c.    Yes—SomeClass is a child of MyInterface d.    Yes—SomeClass is automatically a child of the class Object. 26. Look at the following interface interface Taxable {

double taxRate = 0.06; double calculateTax(); }

Is the interface correct? a.    No—because it contains a variable and interfaces cannot contain variables. b.   

No—because the interface cannot contain a method that returns a value. c.    Yes—taxRate will automatically be a constant since it is in an interface. d.    Yes—the method body will automatically be filled in.

27. Can an interface name be used as the type of a variable, like this: public static void main( String[] args ) {

SomeInterface x; ... }

Object Oriented Programming in Java 115

Page 116: Java for C++ programers

Exercisesa.    No—a variable must always be an object reference type. b.    No—a variable must always be an object reference type or a primitive type. c.    No—a variable must always be a primitive type. d.    Yes—the variable can refer to any object whose class implements the interface.

28. Is it OK if a class definition implements two interfaces, each of which has the same definition for the constant PI?

a.    No—if a class implements several interfaces, each constant must be defined in only one interface.

b.    No—a class may not implement more than one interface. c.    Yes—since the definitions are the same it will not matter. d.    Yes—the more accurate definition of the two will override the other. 29. Can an interface be given the private access modifier? a.    No—then the interface could never be used. b.    No—since only private classes could use the interface. c.    Yes—this would make all of its methods and constants private. d.    Yes—this would mean that only classes in the same file could use the interface.

Object Oriented Programming in Java 116

Page 117: Java for C++ programers

Exercises

30. Can an interface extend another interface? a.    No—only classes can be extended. b.    No—interfaces can not be part of a hierarchy. c.    Yes—since all interfaces automatically extend Object. d.    Yes.

31. What type of inheritance does Java have? a. single inheritance b. double inheritance c. multiple inheritance d. class inheritance 32. Say that there are three classes: Computer, AppleComputer, and

IBMComputer. What are the likely relationships between these classes? a. Computer is the superclass, AppleComputer and IBMComputer are subclasses

of Computer. b. IBMComputer is the superclass, AppleComputer and Computer are subclasses

of IBMComputer.

Object Oriented Programming in Java 117

Page 118: Java for C++ programers

Exercisesc. Computer is a superclass, AppleComputer is a subclasses of Computer, and

IBMComputer is a subclass of AppleComputer d. Computer, AppleComputer and IBMComputer are sibling classes. 33. Can an object be a subclass of another object? • Yes—as long as single inheritance is followed. b. No—inheritance is only between classes. c. Only when one has been defined in terms of the other. d. Yes—when one object is used in the constructor of another.

34. . What restriction is there on using the super reference in a constructor?

a. It can only be used in the parent's constructor. b. Only one child class can use it. c. It must be used in the last statement of the constructor.d. It must be used in the first statement of the constructor.

35. A class Animal has a subclass Mammal. Which of the following is true: a. Because of single inheritance, Mammal can have no subclasses.

Object Oriented Programming in Java 118

Page 119: Java for C++ programers

Exercisesb. Because of single inheritance, Mammal can have no other parent than Animal. c. Because of single inheritance, Animal can have only one subclass. d. Because of single inheritance, Mammal can have no siblings.

36. Does a subclass inherit both member variables and methods? a. No—only member variables are inherited. b. No—only methods are inherited. c. Yes—both are inherited. d. Yes—but only one or the other are inherited. 37. What is a method's signature? a.    The signature of a method is the name of the method the type of its return value. b.    The signature of a method is the name of the method and the names of its

parameters. c.    The signature of a method is the name of the method and the data types of its

parameters. d.    The signature of a method is the name of the method, its parameter list, and its

return type.

Object Oriented Programming in Java 119

Page 120: Java for C++ programers

Exercises

38. Here is a method definition: int compute( a int, y double ){ . . . .}

Which of the following has a different signature? a.    int compute( sum int, value double ){ . . . .} b.    double compute( a int, y double ){ . . . .} c.    double compute( sum int, y double ){ . . . .} d.    int compute( a int, y int ){ . . . .} 39. What must a non-abstract child do about an abstract method in its

parent class? a.    A child must override an abstract method inherited from its parent by defining a

method with the same signature and same return type. b.    A child must define an additional method similar to the one inherited from its

parent by defining a method with the same signature and different return type. c.    A child must not define any method with the same signature as the parent's abstract method.

d.    A non-abstract child must define an abstract method with the same signature and same return type as the parent's abstract method.

Object Oriented Programming in Java 120

Page 121: Java for C++ programers

Exercises

40. Here is an abstract method defined in the parent: public abstract int sumUp ( int[] arr );

Which of the following is required in a non-abstract child? a.    public abstract int sumUp ( int[] arr ) { . . . } b.    public int sumUp ( int[] arr ) { . . . } c.    public double sumUp ( int[] arr ) { . . . } d.    public int sumUp ( long[] arr ) { . . . }

41. What must be true if a child of an abstract parent class does not override all of the parent's abstract methods?

a.    This is always an error. b.    The child class itself must be declared to be abstract. c.    Child classes are automatically non-abstract, so this is OK. d.    The parent class is in error.

42. Here is a situation: Birthday happy; happy = new AdultBirthday( "Joe", 39);

Object Oriented Programming in Java 121

Page 122: Java for C++ programers

Exerciseshappy.greeting();

Which greeting() method is run: the one defined for Birthday or the one defined for AdultBirthday?

a.    The one defined for Birthday because that is the type of the variable happy. b.    The one defined for AdultBirthday because that is the type of the object referred to by happy.

c.    The one closest in the source code to the happy.greeting() statement. d.    Neither---the assignment statement is in error.

43. Say that class Rodent has a child class Rat and another child class Mouse. Class Mouse has a child class PocketMouse. Examine the following Rodent rod; Rat rat = new Rat(); Mouse mos = new Mouse(); PocketMouse pkt = new PocketMouse();

Which one of the following will cause a compiler error? a.    rod = rat; b.    rod = mos; c.    pkt = null; d.    pkt = rat;

Object Oriented Programming in Java 122

Page 123: Java for C++ programers

Exercises

44. Say that the situation is the same as in question 7. Which of the following array declarations is correct for an array that is expected to hold up to 10 objects of types Rat, Mouse, and PocketMouse?

a.    Rat[] array = new Rat[10]; b.    Rodent[] array = new Rat[10]; c.    Rodent[] array = new Rodent[10]; d.    Rodent[10] array;

45. What is the name of the class that is the ancestor to every other class in Java?

a.    Object b.    Class c.    Root d.    Java

46. Examine the following code: String str = "Hot Java"; boolean switch = str instanceof String;

What value is placed in switch? a.    true b.    false c.    "Hot Java" d.    null

Object Oriented Programming in Java 123

Page 124: Java for C++ programers

Exercises

47. What is an abstract class? a.    An abstract class is one without any child classes. b.    An abstract class is any parent class with more than one child class. c.    An abstract class is class which cannot be instantiated. d.    abstract class is another name for "base class."

48. What is an abstract method? a.    An abstract method is any method in an abstract class. b.    An abstract method is a method which cannot be inherited. c.    An abstract method is one without a body that is declared with the reserved

word abstract. d.    An abstract method is a method in the child class that overrids a parent method. 49. Can an abstract class define both abstract methods and non-abstract

methods? a.    No—it must have all one or the other. b.    No—it must have all abstract methods.

Object Oriented Programming in Java 124

Page 125: Java for C++ programers

Exercisesc.    Yes—but the child classes do not inherit the abstract methods. d.    Yes—the child classes inherit both. 50. Can an abstract parent class have non-abstract children? a.    No—an abstract parent must have only abstract children. b.    No—an abstract parent must have no children at all. c.    Yes—all children of an abstract parent must be non-abstract. d.    Yes—an abstract parent can have both abstract and non-abstract children. 51. Can an abstract method be defined in a non-abstract class? a.    No—if a class defines an abstract method the class itself must be abstract. b.   

No—only classes are abstract, not methods. c.    Yes—a method can be declared abstract in any parent as long as the child

classes also declare it abstract. d.    Yes—there is no restriction on where abstract methods can be defined.

52. Can an object of a child type be assigned to a variable of the parent type? For example,

Card crd; BirthDay bd = new BirthDay("Lucinda", 42);

Object Oriented Programming in Java 125

Page 126: Java for C++ programers

Exercisescrd = bd; // is this correct? a.    No—there must always be an exact match between the variable and the object

types. b.    No—but a object of parent type can be assigned to a variable of child type. c.   

Yes—an object can be assigned to a reference variable of the parent type. d.    Yes—any object can be assigned to any reference variable.

53. What is polymorphism in Java? a.    It is when a single variable is used with several different types of related objects

at different places in a program. b.    It is when a program uses several different types of objects, each with its own

variable. c.    It is when a single parent class has many child classes. d.    It is when a class has several methods with the same name but different

parameter types.

54. What determines what method is run in the following: Card crd = new BirthDay("Lucinda", 42); crd.greeting();

The type of the object or the type of the reference variable?

Object Oriented Programming in Java 126

Page 127: Java for C++ programers

Exercisesa.    The type of the object. b.    The type of the reference variable.

55. In order for the following code to be correct, what must be the type of the reference variable card?

_________ card; card = new Valentine( "Joe", 14 ) ; card.greeting(); card = new Holiday( "Bob" ) ; card.greeting(); card = new Birthday( "Emily", 12 ) ; card.greeting(); a.    Valentine b.    Holiday c.    Birthday d.    Card

56. What is an advantage of polymorphism? a.    The same program logic can be used with objects of several related types. b.   

Variables can be re-used in order to save memory. c.    Constructing new objects from old objects of a similar type saves time. d.   

Polymorphism is a dangerous aspect of inheritance and should be avoided.

Object Oriented Programming in Java 127

Page 128: Java for C++ programers

Graphics Programming

Java has extensive support for graphics programming. In the next few lectures we will write Java applications which manipulate windows or frames, text, fonts, colours, shapes etc.

We will start with creating a closable frame, i.e. atop-level window that is not inside another window:import javax.swing.*;class myFrame1 extends JFrame{

public myFrame1(){setTitle(“My First Frame");setSize(300,200);}public static void main(String[] a){JFrame frame=new myFrame1();frame.show();}

}

Object Oriented Programming in Java 128

Page 129: Java for C++ programers

Graphics Programming 2

Java includes a set of classes for dealing with graphics; these classes are stored in a package called Swing. The first line of this program imports this package.

We then create class myFrame1 which extends the Java JFrame class which is a Swing class. We override the methods setTitle and setSize which are inherited from JFrame. The output of this simple program is the following window:

A blank frame which you can resize, maximize, minimize, move, and close. The frame also has asystem menu to perform the aboveoperations (click the top left-handcorner Icon) Most of this behaviour isInherited from parent classes.

Object Oriented Programming in Java 129

Page 130: Java for C++ programers

Graphics Programming 3

A frame is a container object which can hold other user interface elements such as buttons, menus, text fields, etc. To show a frame you need to follow the three steps:

1- Create the frame object by a call to new2- Optionally, position the frame on the user’s screen, using the setLocation methods. By default, the frame will be placed in the top- left corner. 3- Call the show method to make the frame visible and to bring it to the front if it is behind another window.

There is one problem with this little program; you will find it hard to end the program. To properly close this graphics program, add the following event handler to the class:

Object Oriented Programming in Java 130

Page 131: Java for C++ programers

Graphics Programming 4addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e){System.exit(0);

}});

This is an event handler; which listens for the event of closing the frame. Event handlers will be discussed later.

To change how your frames look like, you can use inherited methods from the JFrame and its parent classes. The most common layout methods are the following:- setIconImage method to set an icon for your frames- setTitle method to set some text in the title bar- setResizable method determine if a frame will be resizable by the user- setLocation method to set the position for your frame

Object Oriented Programming in Java 131

Page 132: Java for C++ programers

Graphics Programming 5

This next example will create a frame with an area one-forth that of the whole screen and is positioned in the middle of the screen. For this example, we need to obtain the screen resolution:

import javax.swing.*;import java.awt.event.*;import java.awt.*;class myFrame2 extends JFrame{

public myFrame2(){setTitle("Centered Frame");setResizable(false);addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){

System.exit(0); }}); //event listener

Object Oriented Programming in Java 132

Page 133: Java for C++ programers

Graphics Programming 6Toolkit tk=Toolkit.getDefaultToolkit();Dimension d=tk.getScreenSize();int sHeight=d.height; //get screen heightint sWidth=d.width; //get screen width

setSize(sWidth/2,sHeight/2);setLocation(sWidth/4,sHeight/4);Image img=tk.getImage("icon.gif");//window iconsetIconImage(img);

}public static void main(String[] a){

JFrame frame=new myFrame2();frame.show();

}}

Java uses the Toolkit class to access system-dependent information.

Object Oriented Programming in Java 133

Page 134: Java for C++ programers

Graphics Programming 7The Toolkit class has a method called getScreenSize() which returns the screen size as a dimension object. A Dimension object stores both the height and width of the screen.

We also need to interact with the operating system to obtain an image stored in the file-system using the Toolkit class method getImage:Image img=tk.getImage(“icon.gif”);You could specify long paths, e.g. “D:/Pictures/icon.gif”

The output from this program is the following frame:Of course, the frame here has been resized tofit this slide. It will be placed in the middle ofYour screen and its area will be one-forth that of the screen size. Also note the user-specifiedIcon in the title bar and the inactive maximizeIcon.

Object Oriented Programming in Java 134

Page 135: Java for C++ programers

Graphics Programming 8Now will see how we can add text to our frames. Remember, a frame is a container object which you can add other elements to it. To add some text to a frame for example:1- create a class that extends the JPanel class (this can be used to draw graphics and text)2- Override the paintComponent method in that class3- add an object of this class to the content pane of the frame:

The following example demonstrates these steps:class HelloWorldPanel extends JPanel {

public void paintComponent(Graphics g){super.paintComponent(g);g.drawString(“Hello World, 75, 100);}

class HelloWorldFrame extends JFrame {public HelloWorldFrame(){

Object Oriented Programming in Java 135

Page 136: Java for C++ programers

Graphics Programming 9setTitle(“Hello World”); setSize(300,200);addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){System.exit(0); }});Container contentPane=getContentPane();//get content panecontentPane.add(new HelloWorldPanel()); //on the fly

} //add panel component to the content pane}public class HelloWorld{

public static void main(String[] args){JFrame frame=new HelloWorldFrame();frame.show();}

}

Object Oriented Programming in Java 136

Page 137: Java for C++ programers

Graphics Programming 10To display text, you must first select a font. To select a font, you must first create an object of class Font. The following example will create three fonts and display text using each font in turn:class HelloWorldPanel2 extends JPanel {

public void paintComponent(Graphics g){ super.paintComponent(g); f=new Font("SansSerif", Font.BOLD, 14); f1=new Font("Trebusbi", Font.PLAIN, 24); f2=new Font("Verdana",Font.BOLD+Font.ITALIC, 22); g.setFont(f); g.drawString("Hello World", 75, 50); g.setFont(f1); g.drawString("Hello World", 75, 75); g.setFont(f2); g.drawString("Hello World", 75, 100);}

Object Oriented Programming in Java 137

Page 138: Java for C++ programers

Graphics Programming 11private Font f, f1,f2;

}

For brevity, the rest of the program has been omitted. This was the panel class definition. You can just add this panel to the frame from the last example and it should work.

In this example, we declare three font objects f, f1 and f2. Before drawing the string, the fonts are applied to the graphics object. You can use any font available on your machine. But you should be aware that not all machines have the same fonts installed.

A Font object takes 3 parameters: theFirst is the font-family, the second is theFont style and the third is the font point size.Font style are: PLAIN, BOLD, ITALIC andCombinations of BOLD and ITALIC

Object Oriented Programming in Java 138

Page 139: Java for C++ programers

Graphics Programming 12The setColor method of the java.awt.Graphics class lets you select a color that is used for the subsequent drawing operations on the graphics context or component. To draw in multiple colors, select a color, draw, then select another color and draw again.

Java supports 13 standard colors: black, blue, cyan, darkGray, gray, green, lightGreen, magneta, orange, pink, red, white, yellow.

Or you can create a Color object and then specify its color by specifying its red, green and blue components: Color(byte redness, byte greenness, byte blueness)

To set the color for the graphics object:g.setColor(Color.red); org.setColor(new Color(0, 100,122);

Object Oriented Programming in Java 139

Page 140: Java for C++ programers

Graphics Programming 13You can use the drawLine, drawArc, drawPolyLine and drawPolygon methods in java.awt.Graphics to draw straight and curved lines on a graphics object. This example draws a number of shapes:

class ShapesPanel extends JPanel {public void paintComponent(Graphics g){

super.paintComponent(g);g.setColor(Color.red);//draw a triangleg.drawLine(20,20,20,100);g.drawLine(20,100, 120,20);g.drawLine(120,20,20,20);//draw a circleg.drawArc(220,20, 100, 100, 0,360);}

Object Oriented Programming in Java 140

Page 141: Java for C++ programers

Graphics Programming 14 //draw a 5-sided polugon

Polygon p=new Polygon();p.addPoint(60,150);p.addPoint(70,170);p.addPoint(150,160);p.addPoint(140,70);p.addPoint(70,115);g.drawPolygon(p);

}}

This would output:

Using a combination of lines,Arcs and polygons, you can drawAny shape you like.

Object Oriented Programming in Java 141

Page 142: Java for C++ programers

Graphics Programming 15Add this panel object to the your frame. This example used a number of drawing methods. For straight lines:

drawLine( int x1, int y1, int x2, int y2);draw line from (x1,y1) to (x2, y2)

To draw an arc: drawArc(int x, int y, int width, int height, int startAngle, int arcAngle);

This will draw an arc bounded by rectangle [x,y,width, height] and with start angle and span angle. For a circle the start angle would be 0 and the span angle would be 360.

You can also use drawRect, drawRoundRect draw3DRect and drawOval to draw rectangles and ellipses. See the example on the next slide.

Object Oriented Programming in Java 142

Page 143: Java for C++ programers

Graphics Programming 16This example draws some more shapes:class ShapesPanel extends JPanel {

public void paintComponent(Graphics g){ super.paintComponent(g);g.drawRect(10,10,80,40);g.drawRoundRect(100,10, 100,50, 30,30);g.drawOval(10,100, 80,30);g.drawOval(100,100, 80,80);//cirlceg.draw3DRect(200,100,80,40,true);int thinkness=4;for(int i=0; i<thinkness; i++)g.draw3DRect(230-i, 10-i, 80+2 * i, 40+2*i,true);g.setColor(Color.blue);g.fillRoundRect(300,100, 80,40,20,20);}

}

Object Oriented Programming in Java 143

Page 144: Java for C++ programers

Graphics Programming 17The output from this panel would be:

Note the draw3Drect; this methodDraws a 3-d rectangle but since theBorder is only 1 pixel thick, youCannot see a 3-d rectangle. Hence The for-loop to draw several Rectangles.

The last method draws and fills a round rectangle at the same time. You can also use fillRect, fill3DRect, fillOval ,fillPolygon, fillArc to draw other filled shapes.

Object Oriented Programming in Java 144

Page 145: Java for C++ programers

Event HandlingAny operating system that supports graphical user interfaces must constantly be monitoring the environment for events such as key stokes or mouse clicks. The operating system then passes these events to the programs which are running. It is then up to the programs to decide what to do in response to these events.

In Java, there are event sources and event listeners. Event sources have methods that let you register event listeners with them. When events occur on an event source (a button) the event source sends a notification of that event to all the listener objects that are registered for that event. The information about an event is encapsulated in an event object.

In summary, this is how event handling works:

• a listener object is an instance of a class that implements a special interface called a listener interface

Object Oriented Programming in Java 145

Page 146: Java for C++ programers

Event Handling 2• An event source is an object that can register listener objects and send them event objects.

• The event source sends out event objects to all registered listeners when that event occurs

• the listener objects will then use the information in the event object to determine their reaction to the event.

For example:MyPanel panel=new MyPanel();JButton button= new JButton(“OK”);Button.addActionListener(panel);

The panel object is notified whenever an action event occurs in the button. For button, an action event is a button click.

Object Oriented Programming in Java 146

Page 147: Java for C++ programers

Event Handling 3The following example includes a panel with some buttons on the panel. The panel is the listener object that registers itself with the buttons so that it can listen to them.import javax.swing.*;import java.awt.event.*;import java.awt.*;class ButtonPanel extends JPanel implements ActionListener{

public ButtonPanel(){yellowButton=new JButton("Yellow");blueButton=new JButton("Blue");//create buttonsredButton=new JButton("Red");add(redButton); //add buttons to paneladd(yellowButton);add(blueButton);yellowButton.addActionListener(this);//register

Object Oriented Programming in Java 147

Page 148: Java for C++ programers

Event Handling 4redButton.addActionListener(this);blueButton.addActionListener(this);

}public void actionPerformed(ActionEvent evt){

Object source =evt.getSource();//event sourceColor color=getBackground();if(source==yellowButton) color=Color.white;else if (source==redButton) color=Color.red;else if (source==blueButton) color=Color.blue;setBackground(color);repaint(); //make the panel color change

}private JButton yellowButton;private JButton redButton;private JButton blueButton;

}

Object Oriented Programming in Java 148

Page 149: Java for C++ programers

Event Handling 5What this program does is summarized: first, a panel which is an event listener is created; then some button objects are created and added to the panel. Since the buttons will be our event sources, we need to register them with event listeners, in this case they are all registered with the panel object. Being an event listener, the panel must provide a definition for the methods of the ActionListener interface, the actionPerformed method. It is this method which is invoked when a button fires an event.

The method actionPerformed first obtains a reference to the object which initiated the event (the event source) using the method getSource(); and then uses this reference to determine which button initiated the event.

You can also create buttons which have an icon or image:JButton button=new JButton(new

ImageIcon(“icon.gif”);

Object Oriented Programming in Java 149

Page 150: Java for C++ programers

Event Handling 6The three parts of a GUI application are the following:

1- GUI components (frames, panels, buttons, menus…)2- Listener methods (which receive events and respond to them)3- Application methods (do useful work for the user)

We have already seen a few examples of the first part; we have even seen some involving part; application methods are methods to do useful work in the program.

An event listener is an object that "listens" for events from a specific GUI component (which is also an object.) An event in Java is represented as an object. When the user generates an event, the Java system creates an event object. The event object is then sent to the listener that has been registered for the GUI component.

Object Oriented Programming in Java 150

Page 151: Java for C++ programers

Event Handling 7When an event is generated by the GUI component, a method in the listener object is invoked to respond to the event. In order to respond to events, your program must have done two things:

1- It must create an event listener object for the type of event. 2- It must register the listener object with the GUI component that generates the event (or with a component that contains it.)

In the next example, we will write a GUI program which responds to mouse clicks; when the use clicks the mouse on the main panel, a circle is drawn at the location of the mouse clicks:

class MouseClicks extends JPanel{private int x, y, i, count;Point[] circles=new Point[100];public final int DIAMETER=10;

Object Oriented Programming in Java 151

Page 152: Java for C++ programers

Event Handling 8public MouseClicks(){

setBackground(Color.red);addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent evt){

count++;x=evt.getX();y=evt.getY();Point temp=new Point();temp.x=x;temp.y=y;circles[i++]=temp;repaint();

}}); //or: count++;

// circles[i++]=evt.getPoint()} // repaint()

Object Oriented Programming in Java 152

Page 153: Java for C++ programers

Event Handling 9public void paintComponent(Graphics g) {

super.paintComponent(g);for(int j=0; j<count; j++)

g.fillOval(circles[j].x,circles[j].y,10,10);}}

class myFrame extends JFrame {public myFrame(){

setTitle("Mouse Clicks");setSize(600,400);addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){

System.exit(0); } });

Container contentPane=getContentPane();contentPane.add(new MouseClicks()); }

}

Object Oriented Programming in Java 153

Page 154: Java for C++ programers

Event Handling 10public class ButtonTest2{

public static void main(String[] a){myFrame f=new myFrame();f.show();}

}

This is what the program does:First we create a panel which we will use for drawing; clicking the panel will generate mouse click events so we register this panel with an event listener that can respond to mouse clicks. Here, we create an anonymous class which of and make the event listener for our panel. The anonymous class defines the mouseClicked method which responds to mouse clicks.

The listener method registers mouse click locations, saves this information in an array of Points and then causes the panel’s paintComponent() method to be invoked by calling the repaint() method.

Object Oriented Programming in Java 154

Page 155: Java for C++ programers

Event Handling 11Then we override the paintComponent method to do the actual drawing for us. This method is called by Java every time the panel needs repainting (resizing the panel, maximizing the panel, moving the panel,…) This method is also called when as a response to a mouse click event. It then draws the circles in the array.

Then we define a frame and add our panel to this frame. Every time the user clicks the mouse a small circles will be drawn at the location of the mouse click (up to 100 circles) This program demonstrated the mouseClicked event; MouseListener interface has more events: mousePressed, mouseReleased,

mouseEntered, mouseExited. Java has another interface that deals with mouse events called MouseMotionListener which has the following methods: mouseDragged and mouseMoved. This interface is mainly used for writing drawing (with mouse) applications. We will have more on event handling after we look at some more GUI components.

Object Oriented Programming in Java 155

Page 156: Java for C++ programers

GUI ComponentsWe have already looked at a few GUI components such as JFrame, JPanel and JButton. In the next few slides we will see more of them.

But first let’s look at Java’s Layout ManagementWith layout management one can control how GUI components are arranged inside a frame. Look back at the program in which we placed three buttons on a panel. What happens if we add more buttons to that panel? This is what happens:As you can see, the buttons are centered in a row and when there isn’t more room, then a new row is started. And if the user resizes theframe, the buttons will still be centeredin the panel. This is flow layout, the default layout manager for panels.

Object Oriented Programming in Java 156

Page 157: Java for C++ programers

GUI Components 2The flow layout manager lines the components horizontally until there is no more room and then starts a new row of components. You can choose how you want to arrange the components in a row; the default is to center them in the container. You can also align then to the left or to the right:

setLayout(new FlowLayout(FlowLayout.LEFT); //left alignedsetLayout(new FlowLayout(FlowLayout.RIGHT); //right aligned

But except for the simplest programs, flow layout manager is not very appealing. Another layout manager is called the border layout manager. This layout manager lets you control choose where you want to place each component: center, north, south, east or west. For example:class ButtonPanel extends JPanel{

public ButtonPanel(){yellowButton=new JButton("Yellow");blueButton=new JButton("Blue");

Object Oriented Programming in Java 157

Page 158: Java for C++ programers

GUI Components 3redButton=new JButton("Red");orangeButton=new JButton("Oragne");greenButton=new JButton("Green");setLayout(new BorderLayout());add(redButton,"North");add(yellowButton, "South");add(blueButton,"East");add(greenButton, "West");add(orangeButton, "Center");

}}

But the problem with border layout is that itgrows the components (buttons) so that they fill all the available space (unlike theflow layout which preserves the components’ size.

Object Oriented Programming in Java 158

Page 159: Java for C++ programers

GUI Components 4One solution to this is using multiple panels: remember panels are containers for GUI components and can themselves be arranged inside a larger panel under the control of a layout manager (We will see more layout managers later). For example:class MyFrame extends JFrame{

public MyFrame(){Container contentPane=getContentPane();JPanel panel=new JPanel();panel.add(yellowButton);panel.add(redButton);panel.add(blueButton);contentPane.add(panel,“South”);} //more code

}

Here, a panel is placed at the south of The frame. (frames have border layout by default)

Object Oriented Programming in Java 159

Page 160: Java for C++ programers

GUI Components 557. Write a Java application which will display the following window on the screen:The frame (window) has 4 buttonsOn the edges of the frame and 12Buttons in the middle. You can use Panels and frames for this exercise.If a button is pressed, the value of That button should be displayed on The screen.

Use an array to hold the buttons in the middle of the frame. RecallThat frames have border layout byDefault. (See next slide)

Object Oriented Programming in Java 160

Page 161: Java for C++ programers

GUI Components 6Use the GridLayout manager for the buttons in the middles:

setLayout(new GridLayout(r,c,20,20));This statement will create an r rows by c columns grid and where the space

(horizontal and vertical) is 20 pixels.

Now back to GUI programming.Most GUI-based programs consist of three main parts.

1- The GUI itself. This is a front end for the program. It is what the user sees, containing buttons and other interfaces for the user to provide input, and various displays for the output.

2- The underlying data. Most programs are ultimately concerned with manipulating data of some kind, be it name and address information, web pages, data recording the state of your simulated city, or what have you.

Object Oriented Programming in Java 161

Page 162: Java for C++ programers

GUI Components 73- The code which manipulates the data. This code sits between the GUI and the data. When the user presses a button, some code might run and perform some operations on the data, perhaps updating some of the output displays as a result.

This three-tier program architecture is referred to as the model-view-controller architecture: the model is the computer representation of the information being manipulated; the view is the GUI which displays this data; and the controller is the code which manipulates the data.

In Java two components are used to get text input: text fields and text areas. Text fields take one line of text only while text areas can take multiple lines of text. JTextField for text fields and JTextArea for text areas are available in Java. These two classes have a parent class called JTextComponent. Many methods are inherited from this class.

Object Oriented Programming in Java 162

Page 163: Java for C++ programers

GUI Components 8For example the following three methods are defined in JTextComponent:

void setText(String t); //changes the text of the componentString getText(); //returns the text contained in the componentVoid setEditable(boolean); //whether the user can edit the text

TextFieldsYou can create a new TextField object like this:JTextField t=new JTextField(20); //20 columnsOrJTextField t=new JTextField(“Enter text”, 20);//initial value

JLabel class defines labels which can be used to write textual information inside components. The next example will use JButtons, JTextFields andJLabels to create a small application that can add two numbers:

Object Oriented Programming in Java 163

Page 164: Java for C++ programers

GUI Components 9public class Calcu extends JFrame{

public JButton addB;private JTextField textField1,textField2, textResult;private JLabel text1, text2, textLabel;public Calcu(){

super("Adding two numbers");Container c=getContentPane();

addB=new JButton("Add");c.add(addB, "South");

JPanel panel=new JPanel();

textField1=new JTextField(15);textField2=new JTextField(15);textResult=new JTextField(18);

Object Oriented Programming in Java 164

Page 165: Java for C++ programers

GUI Components 10text1=new JLabel("First Num:");text2=new JLabel("Second Num:");textLabel=new JLabel("Result:");panel.setLayout(new FlowLayout(FlowLayout.RIGHT));panel.add(text1);panel.add(textField1);panel.add(text2);panel.add(textField2);panel.add(textLabel);panel.add(textResult);

c.add(panel, "Center");ButtonHandler handler=new ButtonHandler();addB.addActionListener(handler);setSize(300,200);}

Object Oriented Programming in Java 165

Page 166: Java for C++ programers

GUI Components 11public static void main(String[] a){

Calcu f=new Calcu();f.show();

}class ButtonHandler implements ActionListener{ public void actionPerformed(ActionEvent e){ int num1, num2, result; num1=Integer.parseInt(textField1.getText().trim()); num2=Integer.parseInt(textField2.getText().trim()); result=num1+num2; String str=""+ result; textResult.setText(str.trim());}

}}

The program output:

Object Oriented Programming in Java 166

Page 167: Java for C++ programers

GUI Components 12The program in now summarized: The program consists of a frame; inside the frame we create 3 text fields and three labels to identify the text fields. A button is also created and added to the bottom section of the frame’s pane. We register this button with a user-defined listener. We then create a panel and add all the remaining components to it. The panel is then placed inside the center section of the frame’s pane.

The ButtonHandler which acts as the listener for our button component defines the actionPerformed method; this method obtains the text fields’ strings and converts them to integer and then adds the two numbers.

This simple program can add integer numbers only; it cannot even handle doubles. What’s more, there is no text validation which will cause serious problems for your program. To make your program robust, you must consider input validation. This will be discussed later.

Object Oriented Programming in Java 167

Page 168: Java for C++ programers

GUI Components 1358. Change the class Calcu (on slide 164):

a- create two top-level classes (a frame and a panel); the panel will contain all the components. Event handling should be handled in a separate class (inner class or separate class)

b- the buttons and labels are arranged more appropriately. Use layout managements you have seen to achieve this.

c- Also make sure that the Add button at the bottom looks like a button and does not fill the whole bottom section of the frame.

d- add another button to the frame next to the “Add” button so that when it is clicked the program is gracefully ended.

e- add yet another button, again next to the previous two, called “Clear” which will clear the 3 text fields.

Object Oriented Programming in Java 168

Page 169: Java for C++ programers

GUI Components 14Swing has another class called JPasswordField which is similar to text fields except that typed characters inside the field are represented by echo characters, typically an asterisk (*).

You create a password field like this:JPasswordField passField(null, 15);

This will create a password field that is 15 columns long (you can store more than 15 characters inside it). The first parameter is of type String and if supplied, will set the field to a default password.

To set a different echo character than the asterisk:Void setEchoCharacter(char echo);

The following method returns the text contained in the password field:char[] getPassword(); //not a string?

Object Oriented Programming in Java 169

Page 170: Java for C++ programers

GUI Components 15Text areas can hold multiple lines of text. JTextArea is used to create text area components:JTextArea textArea=new JTextArea(6,60);

This will create a text area 6 lines of 60 columns each. An example follows:

import java.awt.*;import java.awt.event.*;import javax.swing.*;class TextAreaFrame extends JFrame implements ActionListener{ public TextAreaFrame() { JPanel p = new JPanel(); insertButton = new JButton("Insert"); p.add(insertButton); insertButton.addActionListener(this);

Object Oriented Programming in Java 170

Page 171: Java for C++ programers

GUI Components 16 wrapButton = new JButton("Wrap"); p.add(wrapButton); wrapButton.addActionListener(this);

noWrapButton = new JButton("No wrap"); p.add(noWrapButton); noWrapButton.addActionListener(this);

getContentPane().add(p, "South");

textArea = new JTextArea(8, 40); scrollPane = new JScrollPane(textArea); getContentPane().add(scrollPane, "Center");

setTitle("TextAreaTest"); setSize(300, 300); addWindowListener(new WindowAdapter()}

Object Oriented Programming in Java 171

Page 172: Java for C++ programers

GUI Components 17{ public void windowClosing(WindowEvent e)

{ System.exit(0); } } );

public void actionPerformed(ActionEvent evt) { Object source = evt.getSource(); if (source == insertButton) textArea.append("This is some text in the

text area component "); else if (source == wrapButton) { textArea.setLineWrap(true); scrollPane.validate(); } else if (source == noWrapButton) { textArea.setLineWrap(false); scrollPane.validate();

Object Oriented Programming in Java 172

Page 173: Java for C++ programers

GUI Components 18}

} private JButton insertButton; private JButton wrapButton; private JButton noWrapButton; private JTextArea textArea; private JScrollPane scrollPane;}public class TextAreaTest { public static void main(String[] args) { JFrame f = new TextAreaFrame(); f.show(); }

}

Object Oriented Programming in Java 173

Page 174: Java for C++ programers

Java I/OWe briefly looked at reading input from the keyboard at the beginning of this course. There we used a third-party package to read input. Now we will digress briefly from GUI programming and look more closely at how I/O is performed in Java.

Like C++, Java has no built-in support for I/O; IO operations are very complicated, both at the software level and at the electronic level. Part of the problem is that the way in which data is organized outside the computer is different from the way it is organized inside the computer. A standard I/O package is available called java.io which is used to do input and output.

There are two main IO streams connected to your programs:System.in: Input streamSystem.out: output stream

Object Oriented Programming in Java 174