TM Java by Example copyright 2000 2003 Lars
TM Java by Example © copyright 2000 -2003, Lars Fastrup (www. fastrup. dk) An introduction to the Java programming language and the basic concepts of object oriented programming. 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 1
Contents Lesson 1 - Introduction to Java Lesson 2 - Hello World! Lesson 3 - Basic Java Syntax. Lesson 4 - Basic Objects. Lesson 5 - More Java Syntax. Lesson 6 - Exception Handling. Lesson 7 - Advanced Objects. Lesson 8 - Java Beans. 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 2
Lesson 1 Introduction to Java This lesson will introduce you to the Java programming language, and equip you with the knowledge needed to compile and run your first Java program. 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 3
What is Java? • • • • 1/30/2022 A free programming language from Sun Microsystems Inc. It is platform independent (Write Once Run Everywhere). A platform for application development. An object oriented programming language. Has an easy syntax. (Not as complex as C++) Has automatic garbage collection (Makes it hard to cause memory leaks. ) Is a typesafe language. Has built-in multithreading support. Has built-in error handling. Is designed for TCP/IP networking (internet). Comes with a huge class library. Is dynamically linked at run-time. Supports development of standalone, client-server or browser-enabled applications. Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 4
Java Terms Java Virtual Machine (JVM) Essentially a software microprocessor that works as an abstraction over the hardware microprocessor. The JVM is what makes the Java platform independent, as it is available for all major platforms, and it interfaces uniformly to the Java application on all these platforms. Class files Compiled Java files that can be executed by the Java VM. A class file contains the instructions, a. k. a. byte-code that the JVM translates into corresponding native CPU instructions. Classpath Tells the JVM where to look for class files. Analogous to the DOS/WIN PATH that tells DOS/WIN where to look for executable files. The classpath may point to directories or Zip/Jar files Essentially the same as a ZIP file. The JVM can look for class files directly in Jar or Zip files, provided they are listed in the classpath. Makes it easier to group, maintain and distribute Java class files. 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 5
Java Development Tools Command line tools • SUN JDK - Java Development Kit from Sun Microsystems themselves. • IBM JDK - Equivalent from IBM but with IBM’s own VM. Some Integrated Development Environments (IDE’s) • Eclipse, www. eclipse. org • Intelli. J IDEA, www. intellij. com • Borland JBuilder, www. borland. com We shall in this tutorial use the SUN JDK 1. 4 that you can download free-of-charge from java. sun. com 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 6
SUN JDK Installation Download and install it from http: //java. sun. com/j 2 se Afterwards you will need to add the JDK bin directory to your standard path. I suggest that you modify your environment variables like this: SET JAVA_HOME=C: JDK 1. 4 (Or where ever you installed it. ) SET PATH=%JAVA_HOME%bin; %PATH% SET CLASSPATH=. ; %JAVA_HOME%libtools. jar Important JDK files java. exe javac. exe javadoc. exe appletviewer. exe jar. exe 1/30/2022 The Java. TM Virtual Machine (JVM). Compiler for the Java. TM programming language. API documentation generator. Run and debug applets without a web browser. Manage Java Archive (JAR) files. Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 7
Java Resources on the Internet The Java Tutorial http: //java. sun. com/tutorial A very good place to start if you are new to the Java programming language. Also covers more advanced topics for the experienced developer. Java 2 SDK Documentation http: //developer. java. sun. com/developer/infodocs/ Complete online documentation to the Java platform. Cafe au Lait Java FAQs http: //metalab. unc. edu/javafaq Very good online Java resource from Metalab. Thinking in Java 3 rd edition by Bruce Eckel. Very good book that introduces you to Java and object oriented programming techniques. C++ programmers should definitely read appendix B: Comparing C++ and Java. You can also download the book here: http: //www. bruceeckel. com 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 8
Lesson 2 Hello World! This lesson will show you how to write a simple Java program, how to compile it, and how to execute it. 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 9
Hello World Example The following file Hello. World. java is one of the simplest Java programs that you can possibly write. public class Hello. World { public static void main(String[] args) { System. out. println("Hello world!"); } } You may enter the program in any text editor, just make sure to save it as Hello. World. java, because Java requires the filename to be identical to the class name including the case since Java is a fully case sensitive language. While we are at it; Java will also only allow you to define one public class per compilation unit (file). Now compile and run the program using the SUN JDK from the command line like this: javac Hello. World. java Hello. World 1/30/2022 (Compiles the program as Hello. World. class) (Executes Hello. World. class) Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 10
Hello World II Example Let us try and extend the example a bit by adding a method to the Hello. World class. This method, which we will call print. Message, simply prints the string passed to it through the parameter msg as shown in the code example below. public class Hello. World { public void print. Message(String msg) { System. out. println(msg); } public static void main(String[] args) { Hello. World hello. World. Instance = new Hello. World(); hello. World. Instance. print. Message("Hello world!"); } } Note that we have not at all changed the functionality of the program, it still prints “Hello World!” on the screen. We have just changed the way to do it. In the first line of the main method, we define an object hello. World. Instance of type Hello. World and assign a new instance of the Hello. World class to it. In the second line we call the method print. Message on the newly allocated Hello. World object, and as you can see we do not care about cleaning up any memory. This is taken care of by the garbage collector in the Java Virtual machine. 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 11
Lesson 3 Basic Java Syntax This lesson will introduce you to the basics of the Java syntax, which is actually very similar to the C++ syntax. 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 12
Java Keywords The following words are reserved by the Java language as keywords and cannot be used as identifiers. abstract boolean break byte case catch char class const continue default do double else extends finally float for goto if implements import instanceof interface long native new package private protected public return short static super switch synchronized this throws transient try void volatile while The keywords const and goto are reserved as keywords, even though they are not currently used in Java. This may allow a Java compiler to produce better error messages if these C++ keywords incorrectly appear in Java programs. 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 13
Primitive Types The following list shows the predefined data types and their value range in the Java language, and they are all named by their reserved keyword. boolean byte short int long char float double void true or false 8 -bit, from -128 to 127 16 -bit, from -32768 to 32767 32 -bit, from -231 to 231 -1 64 -bit, from -263 to 263 -1 16 -bit, from 0 to 65535 32 -bit, IEEE 754 floating point number. 64 -bit, IEEE 754 floating point number. has no value. Did you wonder why the char data type is 16 -bit and not 8 -bit? In Java the char data type represents Unicode characters and not just ASCII characters. Finally you should also notice that Java does not have an unsigned identifier like C/C++ has. 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 14
Operators The following 37 tokens are the Java operators, and almost all of them work with primitives only. The exceptions are ‘=‘, ‘==‘ and ‘!=‘, which work with all objects. The String class is a special case in the sense that it also supports ‘+‘ and ‘+=‘. Note, Operator overloading is not possible in Java! = > < ! ~ ? : == <= >= != && || ++ -+ * / Assignment. Greater than. Less than. Logical NOT Bitwise NOT Ternary if-else Equivalent to. Less than or equal to. Greater than or equal to. Not equivalent to. Logical AND. Logical OR. Auto increment. Auto decrement. Addition. Subtraction and unary minus. Multiplication. Division. 1/30/2022 & | ^ % << >> >>> += -= *= /= &= |= ^= %= <<= >>>= Bitwise AND Bitwise OR Bitwise XOR Modulus Bitwise left-shift. Bitwise right-shift. Bitwise unsigned right-shift. Addition then assignment. Subtraction then assignment. Multiplication then assignment. Division then assignment. Bitwise AND then assignment. Bitwise OR then assignment. Bitwise XOR then assignment. Modulus then assignment. left-shift then assignment. right-shift then assignment. U. right-shift then assignment. Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 15
Execution Control Java uses all of C‘s execution control statements, if-else, while, do-while, for, and switch. Below is some snippets of sample Java code that demostrates each control structure. if (a == b) { // do something } else { // do something else } // do 10 iterations. for (int i=0; i<10; i++) { // do something. } public void vowels. And. Consonants(char c) { switch (c) { case `a`: case `e`: case `i`: case `o`: case `u`: System. out. println(“vowel”); break; case `y`: case `w`: System. out. println(“Sometimes a vowel”); break; default: System. out. println(“consonant”); } } 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) while (a < b) { // 0 or more // iterations. } do { // 1 or more // iterations. } while (a < b); 16
Lesson 4 Basic Objects This lesson will show you how to work with objects in Java, the very essence of Java and any other OO language for that matter. 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 17
The Class Definition An object is an instance in the memory of a Java class that is defined by the reserved word class. The two examples below defines two empty classes Shape and Line where Line is derived from Shape, i. e. it inherits the properties of Shape is again derived from the class Object, although this is not very obvious. But Java enforces a singly-rooted class hierarchy, i. e. all classes are ultimately inherited from a single base class, simply called Object in Java. As previously mentioned Java only allows one public class definition per compilation unit (file). Note. Multiple inheritance is not possible in Java. // A class Shape, which is derived from Object. public class Shape { } // A class Line derived from Shape. public class Line extends Shape { } 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 18
Access Specifiers Class attributes, methods and constructors can all be prefixed with one of three access specifiers; public, protected and private, with the following effects: • public: Member is part of the class interface and is thus visible to everyone. • protected: Member is only visible to the owning class and derived classes. • private: Member is only visible to the owning class. An access specifier may also be omitted to make the element “package private” which is the default access. Such elements are only visible to classes with the same package. // Class can either be public or package private. public class Foo { int w; // Package private int x; // Visible only to Foo itself. protected int y; // Visible to Foo and any subclass. public int z; // Visible to everyone. void method. A() {. . . } private void method. B() {. . . } protected void method. C() {. . . } public void method. D() {. . . } // // Package Visible private. only to Foo itself. to Foo and any subclass. to everyone. } 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 19
Object Initialization Java guarantees object initialization with a special class method known as a constructor. It is defined by having the same name as the class itself, and is called automatically when a new instance of the class is created on the heap, and object initialization is therefore a guaranteed event. You are not forced to provide any constructers, and if you don’t, the Java compiler will add a default constructor for you. Constructors may have parameters but not return values. Note. Destructors are not supported in Java because of the automatic garbage collector. // Class Foo 1 is empty but has a default constructor anyway. public class Foo 1 {} // Class Foo 2 doing some work in the default constructor. public class Foo 2 { private int x; // Private attribute that defaults to 0 public Foo 2() { x = 1; } // Default constructor that init. x to 1 } // Class Foo 3 does not have a default constructor. public class Foo 3 { private int x; // Private attribute that defaults to 0 public Foo 3(int y) { x = y; } // Constructor that initializes x with y. } 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 20
Object References There are no C like pointers in Java, only object references or object handles if you like, through which you can manipulate objects. Take a look at the first line String s 1; in the main function of the example below. Here we just create a handle, not an object. If you decided to send a message to s 1 at this point, you’ll get an error (at run-time) because s 1 isn’t actually attached to any String object yet. In the next two lines we define two new String handles s 2 and s 3, and we also initialize them. public class The. Alphabet { public void static print. Msg(String s) { System. out. println(s); } public static void main(String[] args) { String s 1; // null reference, i. e. refers to no String object yet. String s 2 = “abcdefghijklm”; String s 3 = new String(“nopqrstuvwxyz”); // Concatenate s 3 to the end of s 2 and assign the resulting string to s 1 = s 2. concat(s 3); // same as s 1 = s 2 + s 3; // Use the public method print. Msg of The. Alphabet to print the alphabet. The. Alphabet. print. Msg(“Alphabet : “ + s 1); } } 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 21
Method Overloading Java also supports method and constructor overloading like other OO languages. The Java compiler not only distinguishes methods and constructors by their name but also by their parameter list. Consider the following example with two constructors and three methods named print. public class Print. Demo { private int x; public Print. Demo() { x = 1; } public Print. Demo(int i) { x = i; } // Default constructor. // Overloaded constructor. public void print() { System. out. println(“hello”); } public void print(int i) { System. out. println(“x+i = “ + (x+i)); } public void print(String s) { System. out. println(“s = ” + s); } public static void main(String[] args) Print. Demo pd = new Print. Demo(); pd. print(42); pd. print(“abcd”); pd = new Print. Demo(5); } { // // // use default constructor. Calls print() Calls print(int i) Calls print(String s) use overloaded constructor. } 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 22
Lesson 5 More Java Syntax More features in the Java language. 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 23
Arrays An array in Java is either a sequence of primitives or object references, and it is a first-class object. The arrays a 1, a 2 and a 3 in the example below are actually object references to a true object that is created on the heap. The array object has a read-only length member that tells you how many elements can be stored in that array object. Arrays are also safe in Java; initialization is guaranteed, and you cannot write outside the array and produce unpredictable results like in C. public class Array. Demo { static void print(String s) { System. out. println(s); } // Command line arguments are passed to the main function // as an array of String object references. public static void main(String[] args) { int[] a 1 = { 1, 2, 3, 4, 5 }; // Allocate and initialize an array. int[] a 2; // A reference to an array. int[] a 3 = new int[5]; // Allocate a new 0 initialized array. a 2 = a 1; // Make a 2 reference to a 1. for (int i = 0; i < a 2. length; i++) { a 3[i] = a 1[i]; // Copy a 1 element to a 3. a 2[i]++; // Increment element in a 1 array. } for (int i = 0; i < a 1. length; i++) print(“a 1[“ + i + “] = “ + a 1[i] + “, a 3[“ + i + “] = “ + a 3[i]); } } 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 24
The this Keyword The this keyword can be used within methods as an object handle to the current object. Consider the following example that demonstrates three different uses of the keyword. public class This. Demo { private int x = 0; public This. Demo(int x) { this. x = x; } // Overloaded constructor. public This. Demo() { this(4); // Call overloaded constructor to set x = 4. } public This. Demo increment() { x++; return this; } public void print() { System. out. println(“x = “ + x); } public static void main(String[] args) { This. Demo demo = new This. Demo(); demo. increment(). print(); } } 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 25
The static Keyword You can make attributes and methods “global” for a class, using the static keyword. A static method can always be called, also without an object. A static class attribute is shared by all instances of a class, i. e. modifying an attribute x in one instance will also affect x in all other instances. Consider the following example that implements the GOF Singleton pattern, which is a class that only allows one instance of itself to exist at any time. // Singleton class, only one instance alive at all times. public class Singleton { // The one and only instance of the Singleton class. private static Singleton instance = new Singleton(); // Private constructor! Prevents others from using new on the Singleton. private Singleton() {} public static Singleton get. Instance() { return instance; } // Test code. public static void main(String[] args) { Singleton s 1 = Singleton. get. Instance(); Singleton s 2 = Singleton. get. Instance(); // s 1 and s 2 refer to the same instance of Singleton. } } 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 26
The final Keyword The final keyword can be used for data, methods, arguments and classes. • Final data members are constant values that can not be changed at run-time. • Final methods are locked against being overridden by any inheriting class. • Final arguments are constant and cannot be changed by the method. • Final classes cannot be subclassed. Consider the following example class that demonstrates the above situations. We have done some moonlighting here by declaring the do. That method final. This is not necessary as the class itself is declared final implicitly making all methods final. public final class Final. Demo { private final int i = 1; private final int j; public static final int the. Ultimate. Answer = 42; public Final. Demo() { j = 1; } // Initialized final. // Blank final. // Public constant. // Initialize blank final (REQUIRED) public void do. It(final String s) { // Method with a final argument. // You cannot change what s points to here. } final public void do. That() { /* Do THAT */ } // A final method. } 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 27
Java Packages The Java package concept enables you to logically group classes. A package is in Java also a directory in the file system, i. e. if you create a package test, all classes belonging to this package must also reside in directory test relative to the root of your Java sources. A common convention for package names is to use your internet domain name in reverse order. E. g. my internet domain is fastrup. dk, so I always use dk. fastrup as my root package. Consider the following two classes located in two different packages, the latter class uses the first class and therefore needs to import it. package dk. fastrup. tools; public class My. Tool { // A lot of delicious stuff here. } package dk. fastrup. demos; import java. util. *; // Imports all classes from the java. util package. import dk. fastrup. tools. My. Tool; // Import the My. Tool class. public class Demo. App { public static void main(String[] args) { My. Tool tool = new My. Tool(); // Do some work here. } } 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 28
Lesson 6 Exception Handling This lesson will show you how to deal with error situations in Java. 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 29
Catching An Exception handling is enforced by the Java compiler, meaning that you must deal with exceptions thrown by any method used in your code. Java provides the two keywords try and catch for catching exceptions. The try keyword is used for delimiting a block of code where an exception might occur, and the catch keyword is used for defining one or more exception handlers after the try-block. The try -catch structure looks like this in Java: try { // Code that might generate exceptions } catch (Type 1 id 1) { // Handle exceptions of Type 1 } catch (Type 2 id 2) { // Handle exceptions of Type 2 } catch (Type 3 id 3) { // Handle exceptions of Type 3 } 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 30
A try – catch Example Consider the following example that prints a text file line-by-line on the screen. The file operations are wrapped into a try-block because we will receive an exception, if a file operation fails. The File. Input. Stream constructor throws an exception of type File. Not. Found. Exception if the specified file cannot be found, and the read. Line method throws an IOException if it fails to read from the file. import java. io. *; // Import this package because we use Java IO classes. public class Printfile { public static void main(String[] args) { try { Buffered. Reader in = new Buffered. Reader( new Input. Stream. Reader( new File. Input. Stream(args[0]))); while (in. ready()) { System. out. println(in. read. Line()); // Read and print a line. } } catch (File. Not. Found. Exception e) { System. err. println("Error! File not found. "); } catch (IOException e) { System. err. println("Unexpected IO error encountered. "); } } } 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 31
Throwing an Exception Java has two more keywords related to the exception mechanism, namely throw and throws. Let us take a look at the first keyword, which is used for generating an exception. It stops the current path of execution and winds up the stack from the try statement. Program execution is resumed at the catch statement (exception handler) that intercept the exception. An exception is also a Java object, so you must also create an exception object with the new operator as shown below. if (t == null) throw new Null. Pointer. Exception(“t = null”); The next keyword, throws, informs the client programmer, who calls your method, of the exceptions that might be thrown from your method. This throws clause is not voluntary, it is enforced by the Java compiler, which only allows you to declare exactly those exceptions that you might actually throw within the method. So a method that throws exceptions is defined like this: void f() throws too. Big, too. Small, div. Zero { //. . . } 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 32
A throw(s) Example Consider the following example that defines a custom exception type that is thrown by the method f() in the My. Exception. Demo class. We are forced to declare the exception in the throws clause of method f(), because we throw the exception outside a try statement. class My. Exception extends Exception { // Exception is a standard Java class. public My. Exception() {} // Default constructor. public My. Exception(String msg) { // Overloaded constructor. super(msg); // Pass msg up to constructor of the super class. } } public class My. Exception. Demo { public static void f() throws My. Exception { throw new My. Exception(“Error message. ”); } // Note throws clause. public static void main(String[] args) { try { f(); } catch (My. Exception e) { e. print. Stack. Trace(); } } } 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 33
Lesson 7 Advanced Objects This lesson will introduce you to some more important parts of object oriented programming, namely abstract classes (interface), method overriding and polymorphism all integral parts of the Java language. 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 34
Abstract Classes An abstract class is a class that cannot be instantiated, which is a useful feature when objects of that class have no meaning. That is, the abstract class is meant to express an interface, and not a particular implementation. Only subclasses that supply an implementation for all abstract methods can be instantiated. Java provides the keyword abstract for declaring a class and/or methods abstract as shown below. // Abstract class that cannot be instantiated. public abstract class Instrument { public abstract void play(); // Abstract methods have no implementation. } An abstract class may consist of both abstract methods that have no implementation, and normal methods with an implementation. The latter methods can also be regarded as interface methods but with a default behavior instead of none. 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 35
Interfaces An interface is a kind of “pure” abstract class, because it cannot include any implementation. It merely defines a communication protocol for classes that implement the interface, i. e. provides a method body for all methods defined in the interface. An interface is defined by replacing the class keyword with the interface keyword like in the code snippet below. public interface Instrument { void play(); } // Automatically public. Classes can conform to an interface by implementing it using the implements keyword as shown below. A class may implement more than one interface, which solves many problems associated with abstract class interfaces and the Java single inheritance policy. // Class that implements the Instrument interface public class Piano implements Instrument { public void play() { // Must be declared public. // Play some piano tunes. } } 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 36
Polymorphism is a very essential feature of OOP and is about decoupling interface from implementation. This is realized by using late method binding instead of early binding. Binding is about connecting a method call to a method body, which is done at compile time in the case of early binding. But polymorphic method calls can first be bound at run-time, which the following example should help clarify. It plays some tunes from a Flute, a Piano and a Guitar, where each instrument is modeled as a subclass of the abstract class Instrument. The class Instrument. Demo creates an array referencing one instance of each instrument, but notice that it only holds handles to objects of type Instrument not type Flute, Piano or Guitar. But when calling the play method, polymorphism surfaces and calls the appropriate play method on the true object type. public class Instrument. Demo { public static void main(String[] args) { // Array with handles to 3 instruments. Instrument[] inst = { new Flute(), new Piano(), new Guitar() } for (int i=0; i<inst. length; i++) inst[i]. play(); // Polymorphic method. } } 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 37
Lesson 8 Java Beans Reusable software components. 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 38
What is a Bean? A Java Bean is a reusable and self-contained software component. It is basically a standard Java class that follows certain naming conventions to expose properties and events for manipulation in visual builder tools. (Note! The Java event mechanism is not covered by this tutorial). Bean naming conventions: • Bean properties are exposed through getter and setter methods that have the same name as the property itself plus the prefix “get” and “set” respectively. E. g. a property named color is accompanied by the getter method get. Color and the setter method set. Color. • For a boolean property it is also valid to use the “is” prefix instead of “get”. • A bean may also include ordinary methods that does not conform to the above conventions. • A bean must always provide a default constructor. Otherwise visual builder tools cannot create an instance of the bean for visual manipulation. • For events, you use the “listener” approach. E. g. if your bean is able to generate an Action. Event then it should provide two public methods; add. Action. Listener and remove. Action. Listener that lets a client add/remove himself as a listener to the event. See the Java documentation for a more detailed explanation on Java events and listener interfaces. 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 39
A Simple Bean Consider the following example of a GUI button written as a Java Bean. The bean has only one property (label), which represents the button text. The text can be read/changed through the corresponding getter/setter methods, also by a visual builder tool. The bean also generates an Action. Event upon pressing the button, and clients can receive this event by adding themselves as event listeners using the add. Action. Listener method. The paint method overrides the paint method in the java. awt. component class, and is called by the system when the button needs to redraw itself. // Simple bean that exposes two properties. public class Button extends java. awt. component { private String label; // Bean attribute exposed through get&set methods public Button() { label = new String(“Ok”); } public Button(String label) { this. label = label; } // Default construtor // Overloaded constr. public String get. Label() { return label; } public void set. Label(String label) { this. label = label; } // Getter // Setter public void add. Action. Listener(Action. Listener l) { /*. . . */ } public void remove. Action. Listener(Action. Listener l) { /*. . . */ } public void paint(java. awt. Graphics g) { /* draw the button */ } } 1/30/2022 Java by Example, © 2000 -2003 Lars Fastrup (www. fastrup. dk) 40
- Slides: 40