O slideshow foi denunciado.
Seu SlideShare está sendo baixado. ×

Java for C++ programers

Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Próximos SlideShares
Grade 8: Introduction To Java
Grade 8: Introduction To Java
Carregando em…3
×

Confira estes a seguir

1 de 174 Anúncio
Anúncio

Mais Conteúdo rRelacionado

Diapositivos para si (20)

Quem viu também gostou (20)

Anúncio

Semelhante a Java for C++ programers (20)

Anúncio

Mais recentes (20)

Java for C++ programers

  1. 1. Object Oriented Programming in Java Third Year University of Salahaddin-Erbil College of Engineering Department of Software Engineering Karim Zebari 2002-2003
  2. 2. 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
  3. 3. 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
  4. 4. 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
  5. 5. About this course 4 Programming 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 Homepage 4) 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
  6. 6. 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
  7. 7. 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
  8. 8. 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
  9. 9. 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
  10. 10. 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
  11. 11. 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
  12. 12. Java 6 underlying 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
  13. 13. 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
  14. 14. 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
  15. 15. 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.java 4- Executing the bytecode file: java filename [parameters] Object Oriented Programming in Java 15
  16. 16. The “Hello World” Program As 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 //2 class 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
  17. 17. 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
  18. 18. 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
  19. 19. 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
  20. 20. 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
  21. 21. 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
  22. 22. 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
  23. 23. 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,647 short 2 bytes -32,768 to 32,767 long 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
  24. 24. 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
  25. 25. 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
  26. 26. Assignment, Initialization, Constants… 2 You 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
  27. 27. 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 6 int 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
  28. 28. Assignment, Initialization, Constants… 3 It 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 Increasingprecedence
  29. 29. 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
  30. 30. 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
  31. 31. Strings 3 Java 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-0 char[] ca=s.toCharArray(); //convert string to //array of characters String s2=s.toLowerCase();//change to lowercase boolean b=s.endsWith(“t”); //true int 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
  32. 32. Strings 4 As 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’); //Nello b.append(‘w’); //Nellow b.append(“text”); //Nellowtext b.insert(4, “ing”); b.delete(5, 9); //Nello b.setCharAt(0, ‘H’); //Hello b.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
  33. 33. 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
  34. 34. 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
  35. 35. 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
  36. 36. 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
  37. 37. 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 n readData: while(…) { …… for(…){ if (n<0) break readData; …… } } if (n<0) …… //deal with bad situation else …… // proceed normally The goto statement is used in C++ to have a similar effect. Object Oriented Programming in Java 37
  38. 38. Conditional Statements and Loops 4 A 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
  39. 39. 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
  40. 40. Methods 2 We 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 myMethod myMethod(); } 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
  41. 41. Methods 3 Now 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
  42. 42. 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
  43. 43. Arrays 2 Once you create an array, you cannot change its size; this is the case with C/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
  44. 44. 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 memory int 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
  45. 45. 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 4 3 0 1
  46. 46. Arrays 5 The 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 101 1 after copy is 102 2 after copy is 103 3 after copy is 5 4 after copy is 7 5 after copy is 11 6 after copy is 13 A 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
  47. 47. 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
  48. 48. Arrays 7 public 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
  49. 49. 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
  50. 50. 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 dice Between 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
  51. 51. 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
  52. 52. 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 arguments num1=0; num2=0; //unlike C++ } else { num1=Integer.parseInt(args[0]);//parse to num2=Integer.parseInt(args[1]);//integer } System.out.println(num1+num2); } }Object Oriented Programming in Java 52
  53. 53. 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
  54. 54. 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: Arrays Enter second word: 126 Arrays…………………126 This could be used as part of an indexing system for a book. Object Oriented Programming in Java 54
  55. 55. 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
  56. 56. Exercises 9) 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
  57. 57. 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
  58. 58. 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/action ob.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
  59. 59. 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
  60. 60. OO programming 3 return rads * 180 / PI; } //an instance field public double r; //two instance methods public 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
  61. 61. 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
  62. 62. 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
  63. 63. 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 line When 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
  64. 64. 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
  65. 65. 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
  66. 66. OO programming 9 The 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
  67. 67. OO programming (finalize) 10 Constructors 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
  68. 68. 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 collection System.gc(); //suggest that GC be called System.exit(0); } } Object Oriented Programming in Java 68
  69. 69. OO programming (finalize) 12 class 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 public but 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
  70. 70. 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
  71. 71. 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
  72. 72. 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
  73. 73. 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
  74. 74. OO programming (Inheritance) 17 import 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 point output+=“nCircle c (via pointRef): “ + pointRef.toString(); circleRef=(Circle) pointRef;//downcast //see next page… Object Oriented Programming in Java 74
  75. 75. OO programming (Inheritance) 18 output+=“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
  76. 76. 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
  77. 77. 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
  78. 78. OO programming (Inheritance) 21 public 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
  79. 79. OO programming (Inheritance) 22 public 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
  80. 80. 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.0 Circle Cons: Center=[72, 29]; Radius=4.5 Point Cons Center=[5, 5]; Radius=0.0 Circle Cons: Center=[5, 5]; Radius=10.0 Circle finalize: Center=[72, 29]; Radius=4. Point finalize: Center=[72, 29]; Radius=4.5 Circle finalize: Center=[5, 5]; Radius=10.0 Point finalize: Center=[5, 5]; Radius=10.0 Object Oriented Programming in Java 80
  81. 81. 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’s garbage collector be called with the call System.gc(). Java guarantees that 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
  82. 82. 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
  83. 83. 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
  84. 84. OO programming (Polymorphism) 27 In 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
  85. 85. 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
  86. 86. 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
  87. 87. OO programming (Polymorphism) 30 public 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
  88. 88. OO programming (Polymorphism) 31 objects, 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
  89. 89. 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
  90. 90. 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
  91. 91. 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
  92. 92. 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
  93. 93. 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
  94. 94. OO programming (Interfaces) 37 A 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
  95. 95. 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
  96. 96. 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
  97. 97. 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
  98. 98. 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
  99. 99. OO programming (Interfaces) 42 import 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
  100. 100. OO programming (Interfaces) 43 DecimalFormat precision2 = new DecimalFormat( "0.00" ); for ( int i = 0; i < arrayOfShapes.length; i++ ) { output += "nn" + 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
  101. 101. OO programming (Interfaces) 44 Abstract 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
  102. 102. OO programming (Interfaces) 45 Here 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
  103. 103. OO programming (Interfaces) 46 interface 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
  104. 104. OO programming (Interfaces) 47 public 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
  105. 105. OO programming (Interfaces) 48 class 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
  106. 106. 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
  107. 107. 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
  108. 108. 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
  109. 109. 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? 100 How much money was given? 72 The cashier should return: 2 10-Dinars 1 5-Dinars 3 Dinars Object Oriented Programming in Java 109
  110. 110. 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
  111. 111. 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
  112. 112. Exercises Public 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
  113. 113. 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
  114. 114. 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
  115. 115. Exercises a. 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
  116. 116. Exercises a. 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
  117. 117. 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
  118. 118. Exercises c. 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
  119. 119. Exercises b. 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
  120. 120. 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
  121. 121. 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
  122. 122. Exercises happy.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
  123. 123. 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
  124. 124. 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
  125. 125. Exercises c. 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
  126. 126. Exercises crd = 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
  127. 127. Exercises a. 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
  128. 128. 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
  129. 129. 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 a system menu to perform the above operations (click the top left-hand corner Icon) Most of this behaviour is Inherited from parent classes. Object Oriented Programming in Java 129
  130. 130. 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 new 2- 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
  131. 131. Graphics Programming 4 addWindowListener(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
  132. 132. 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
  133. 133. Graphics Programming 6 Toolkit tk=Toolkit.getDefaultToolkit(); Dimension d=tk.getScreenSize(); int sHeight=d.height; //get screen height int sWidth=d.width; //get screen width setSize(sWidth/2,sHeight/2); setLocation(sWidth/4,sHeight/4); Image img=tk.getImage("icon.gif");//window icon setIconImage(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
  134. 134. Graphics Programming 7 The 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 to fit this slide. It will be placed in the middle of Your screen and its area will be one-forth that of the screen size. Also note the user-specified Icon in the title bar and the inactive maximize Icon. Object Oriented Programming in Java 134
  135. 135. Graphics Programming 8 Now 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 class 3- 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
  136. 136. Graphics Programming 9 setTitle(“Hello World”); setSize(300,200); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); Container contentPane=getContentPane();//get content pane contentPane.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
  137. 137. Graphics Programming 10 To 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
  138. 138. Graphics Programming 11 private 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: the First is the font-family, the second is the Font style and the third is the font point size. Font style are: PLAIN, BOLD, ITALIC and Combinations of BOLD and ITALIC Object Oriented Programming in Java 138

×