Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Welcome Back!!! Advanced Java Programming CSE 7345/5345/ NTU 531 Session 4 Liang, Oreilly, Herbert Schildt, Joseph O’Neil Office Hours: by appt 3:30pm-4:30pm SIC 353 Chantale Laurent-Rice Welcome Back!!! [email protected] [email protected] Liang, Oreilly, Herbert Schildt, Joseph O’Neil What value is printed out at line 6? • // Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Simon Roberts • • • • • • • • • • • • • • • 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. class Checking{ public static void main(String args[]) { Holder h = new Holder(); h.held = 100; h.bump(h); System.out.println(h.held); } } class Holder{ public int held; public void bump(Holder theHolder) { theHolder.held++; } } Liang, Oreilly, Herbert Schildt, Joseph O’Neil Input/output selection • Introducing Java's Control Statements • The if Statement • The if statement is one of Java's selection statements (sometimes called conditional statements). • Its operation is government by one of the outcome of a conditional test that evaluates to either true or false. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Example • if (10 > 9) System.out.println("true"); // Input/output selection public class IfDemo { public static void main(String[] args) { if (args.length == 0) System.out.println("You must have command line argument"); } } Liang, Oreilly, Herbert Schildt, Joseph O’Neil Remember • Remember, a number is not a boolean. Therefore, it is not valid to have an if statement such as the following: if (count + 1) System.out.println("Not Zero"); Such a line generates a compiler error. Liang, Oreilly, Herbert Schildt, Joseph O’Neil If-else statement public class IfDemo { public static void main(String[] args) { if (args.length = = 0) System.out.println("You must have command line argument"); else System.out.prinltn(“not good”); } } Liang, Oreilly, Herbert Schildt, Joseph O’Neil The for statement • The for loop is one of Java's three loop statements. • It allows one or more statements to be repeated and is considered by many Java programmers to be its most flexible loop. • The for loop is used to repeat a statement or block of statements a specified number of times. Its general form for repeating a single statement is as followed: for(initialization; test; increment) statement; Liang, Oreilly, Herbert Schildt, Joseph O’Neil Example • public class ForLoop { public static void main(String[] args) { for (int num = 1; num < 11; num = num + 1) System.out.print(num + " "); System.out.println("terminating"); } } Liang, Oreilly, Herbert Schildt, Joseph O’Neil The Increment operators • public class ForLoopIncr { public static void main(String[] args) { for (int num = 1; num < 11; num ++) System.out.print(num + " "); System.out.println("terminating"); } } Liang, Oreilly, Herbert Schildt, Joseph O’Neil The decrement operators public class ForLoopDecr { public static void main(String[] args) { for (int num = 1; num >= 11; num --) System.out.print(num + " "); System.out.println("terminating"); } } Liang, Oreilly, Herbert Schildt, Joseph O’Neil • • • • • • • • • • • • • • • • What value is printed out at line 6? // Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Simon Roberts 1. class DecMe{ 2. public static void main(String args[]) { 3. double d = 12.3; 4. Decrementer dec = new Decrementer(); 5. dec.decrement(d); 6. System.out.println(d); 7. } 8. } 9. 10. class Decrementer{ 11. public void decrement(double decMe){ 12. decMe = decMe -1.0; 13. 14. } 15. } Liang, Oreilly, Herbert Schildt, Joseph O’Neil Introduction • Chapter 6 con’t – Objects and classes Liang, Oreilly, Herbert Schildt, Joseph O’Neil In this chapter • Object-Oriented Programming • • • • Introducing classes and objects Class methods Input and output methods Objects and garbage collection Liang, Oreilly, Herbert Schildt, Joseph O’Neil Object and classes • Overloading Method Names • Overloading is the reuse of a method name in the one class or subclass for a different method. • Overloading methods are effectively independent, and there are no constraints on the accessibility, return type, or exceptions that may be thrown. Changing parameter names is not sufficient to count as overloading. • public void oMethod(String s){ } • public void oMethod() { } • public void oMethod(int i, String s) { } • public void oMethod(String s, int i) { } Liang, Oreilly, Herbert Schildt, Joseph O’Neil 1. 2. 3. 4. Consider this code public class ConsideringIt{ public float oMethod(float a, float b){ } } Which of the following methods would be legal if added (individually) at line 4? a. public int oMethod(int a, int b) { } b. public float oMethod(float a, float b) { } c. public float oMethod(float a, float b, int c ) throws Exception { } d. public float oMethod(float c, float d) { } e. private float oMethod(int a, int b, int c) { } Liang, Oreilly, Herbert Schildt, Joseph O’Neil Class • The keyword class indicates that a class names clsName is being declared. • This name must follow the Java naming conventions for identifiers. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Class (con’t) • Constructors always have the same name as the class. They do not have return values. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Declaring classes • A class begins with the class keyword followed by braces that delimit the class’s content: – class AnyClass –{ • ………. –} Liang, Oreilly, Herbert Schildt, Joseph O’Neil Declaring classes • Most classes have one or more methods, such as main(), which is found in all standalone Java applications. – Class AnyClass – { • public static void main(String[] args) • { – //statements inside main( ) • } – } Liang, Oreilly, Herbert Schildt, Joseph O’Neil Declaring classes • You can also create other methods and call them from main() and from other places. class AnyClass { public static void main(String args[]) { HiThere(); // Call HiThere( ) method } public static void HiThere() { System.out.println("Hi There!"); } } Liang, Oreilly, Herbert Schildt, Joseph O’Neil Class Name • Class names are usually capitalized. • Variables and methods begin with lowercase letters. • These conventions are not requirements, but help make program clearer to read and understand. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Class Bag class Bag { boolean flag; int i, j =2, k = 3, l, m; double array[] = { -3.4, 8.8e100, 09.2e-100}; String s1, s2 = new String(“Hello”); } Liang, Oreilly, Herbert Schildt, Joseph O’Neil Class Bag class BagTest { public static void main(String[] args) { Bag bag = new Bag(); System.out.println(bag.flag); System.out.println(bag.i); System.out.println(bag.j); System.out.println(bag.k); System.out.println(bag.l); System.out.println(bag.m); for(int i =0; i < bag.array.length; i++) System.out.println(bag.array[i]); System.out.println(bag.s1); System.out.println(bag.s2); } } Liang, Oreilly, Herbert Schildt, Joseph O’Neil Object-oriented key concepts: • In Java, object-oriented programming revolves around a few concepts: • classes • objects • data members • methods • and inheritance Liang, Oreilly, Herbert Schildt, Joseph O’Neil Questions to consider…. • • • • • • What are those terms mean: classes, objects, data members, methods, and inheritance. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Consider this code • • • • • • • • • • • • • • • • 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. class HasStatic { private static int x =100; } public static void main(String args[]) { HasStatic has1 = new HasStatic(); has1.x++; HasStatic has2 = new HasStatic(); has2.x++; has1 = new HasStatic(); has1.x++; HasStatic.x++; System.out.println("x = " + x); } Which one statement is true about this code? a. Line 8 will not compile, it is static reference to a private variable b. line 13 will not compile, because it is a static reference to a private variable c. The program compiles, and the output is x = 102. d. The program compiles, and the output is x = 103. e. The program compiles, and the output is x = 104. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Creating an object • To create a object, you call a class’s constructor, which is a method with the same name as the class itself. • This constructor creates a new object of the class. • You call an instance of a class an object. • An object is a variable. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Creating an object • An object occupies space in memory, and it must be initialized. Liang, Oreilly, Herbert Schildt, Joseph O’Neil The new Operator • Up to this point, you have been creating objects indirectly, such as through the use of some Java’s static methods. • It is now time to learn how to create an object directly. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Objects • Objects are created using the new operator. • Or, put differently, the new operator creates an instance of a class. • It is invoked as follows: – clsName ObjRef = new clsName(args); Liang, Oreilly, Herbert Schildt, Joseph O’Neil Creating objects • clsName is the name of the class to be instantiated. • Instantiated means to create an instance of that class. • A reference to the new object is assigned to a variable name objRef. • Notice the expression immediately to the right of the keyword new. – clsName ObjRef = new clsName(args); • This is known as a constructor. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Constructor • A constructor creates an instance of a class. It has the same name as the class and may optionally have an argument list args. • The next slide illustrates the relationship between objects and object reference variables. • In the diagram, the variable named varA refers to one object. • Variables named varB and varC both refer to a second object. • The third object is referred to by the variable named varD. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Objects and object references • • Here, i is a simple int value and s is a String object. Notice that the second form of the constructor can throw an exception if the constructor argument is not correctly formatted. The first form of the constructor cannot throw an exception because any int can be used to create an Integer object. varA Object varB Object varC varD Liang, Oreilly, Herbert Schildt, Joseph O’Neil Object Keypoint • A key point to understand is that the variable is distinct from the object. • In effect, a variable that serves as an object reference has an implicit pointer to the object. • However, a Java programmer cannot directly access the pointer. • Also note that multiple variables may refer to the same object. Liang, Oreilly, Herbert Schildt, Joseph O’Neil The symbol null • The symbol null has a special meaning in Java. • It represents the value of an object reference variable when that variable does not reference any object. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Again Classes and Objects • Classes and objects form the building blocks of any Java program. Therefore, a basic understanding of them is necessary. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Constructor Modifiers These are three modifiers that may precede the declaration of a constructor. These are summarized in the following table: Keyword Meaning Private Can be invoked only by code in the same class Protected Can be invoked only by code in a subclass or the same package Public Can be invoked by any other class Liang, Oreilly, Herbert Schildt, Joseph O’Neil Constructor Modifiers • These modifiers are mutually exclusive. • If none is specified • The default is that only code in the same package may access that • constructor. Liang, Oreilly, Herbert Schildt, Joseph O’Neil class Person { // declare variable; String name; int age; public Person(String name, int age) { this.name = name; this.age = age; } } private Person() { } Liang, Oreilly, Herbert Schildt, Joseph O’Neil Example: Example class PrivateConstructor { public static void main(String[] agrs) { // Public constructor may be invoked Person p1 = new Person(“John”, 30); System.out.println(p1.name); System.out.println(p1.age); //Private constructor may not be invoked //Person p2 = new Person(); } } Liang, Oreilly, Herbert Schildt, Joseph O’Neil Method Modifiers • There are eight possible modifiers that may precede the declaration of a method. • These are summarized in the following table: Liang, Oreilly, Herbert Schildt, Joseph O’Neil Method Modifiers Keyword Abstract Meaning Is not implement by this class Final May not be overridden Native The method is implemented in the machine Code used by the host CPU, not using Java bytecodes. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Method Modifiers Private Can be invoked only by code in the same class Protected Can be invoked only by code in a subclass. Or the same package Public Can be invoked by any other class Static Is not an instance variable Synchronized Acquires a lock when it begins execution. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Meanings If a class contains an abstract method, that class itself must also be declared abstract. Otherwise, the Java compiler issues an error message. The public, protected, and private modifiers are mutually exclusive. The synchronized modifier is very important in multithreaded programming. The native modifier is beyond the scope of programming. If none of these modifiers are specified, the method is assumed to be a non-abstract, non-final, non-native, nonsynchronized method. It may be accessed only by code in the same package. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Example • The class JetPlane declares one abstract method named numEngines(). • Therefore, the class itself must also be declared abstract. • There are two concrete subclasses named DC8 and DC10. Each of these provided a different implementation of numEngines() method. • The main() method instantiates each of these classes and invoke its numEngines method. • This is an excellent example of run-time polymorphism. • Each subclass provides a different form of the method. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Example abstract class JetPlane { abstract int numEngines(); } class DC8 extends JetPlane { int numEngines() { return 4; } } class DC10 extends JetPlane { int numEngines() { return 3; } } Liang, Oreilly, Herbert Schildt, Joseph O’Neil Example cont class JetPlanes { public static void main(String[] args) { System.out.println(new DC8().numEngines()); System.out.println(new DC10().numEngines()); } } Liang, Oreilly, Herbert Schildt, Joseph O’Neil Chapter 7 The StringBuffer Class • There is no way to change the character sequence encapsulated by String object after it is created. • The StringBuffer class also encapsulates a sequence of characters. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Its constructor has the following forms: • /* This form of the constructor initializes the buffer size to 16 character*/ StringBuffer( ) • /*This form explicitly sets the buffer capacity to size characters*/ StringBuffer(int size) • /*This form initializes the buffer with the contents of s and also reserves another 16 characters for expansion*/ StringBuffer String s Liang, Oreilly, Herbert Schildt, Joseph O’Neil Create StringBuffer objects • This example creates StringBuffer objects by using the three form of constructors and displays their current capacity and sizes. Liang, Oreilly, Herbert Schildt, Joseph O’Neil public class StringBufferExample { public static void main(String[] args) { StringBuffer sb1 = new StringBuffer( ); StringBuffer sb2 = new StringBuffer(30 ); StringBuffer sb3 = new StringBuffer("abcde" ); System.out.println("sb1.capacity = " + Example sb1.capacity( )); System.out.println("sb2.capacity = " + sb2.capacity( )); System.out.println("sb3.capacity = " + sb3.capacity( )); } } System.out.println("sb3.length = " Liang, Oreilly, Herbert Schildt, Joseph O’Neil + sb3.length( )); Read / Work With (Course Links) • • • • Liang, Nutshell Chapter 7-9 Life Cycle of Applets List Of Basic Tags Try It Editor Liang, Oreilly, Herbert Schildt, Joseph O’Neil Creating Strings //Creating a String object: public class StringObject { public static void main(String[] args) { String s1 = "Hello from Java"; String s2; String s3 = new String(); s2 = "Hello from s2 Java"; //s3 = new String(); s3 = "Hello from s3 Java!"; System.out.println(s1); System.out.println(s2); System.out.println(s3); } } Liang, Oreilly, Herbert Schildt, Joseph O’Neil Question • 1. Can you change a String object at runtime? Why?Why not? • 2. What is the default constructor of a String class? • 3. Is a class an object? • 4. What are the Java’s String class constructors? Liang, Oreilly, Herbert Schildt, Joseph O’Neil String: • String: use this one for fixed length strings that will not change at runtime. A String object is immutable. • StringBuffer: use this class for variable-length strings that might change at runtime. A StringBuffer object is mutable. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Getting String Length public class StringLength { public static void main(String[] args) { String s1 = "Hello from Java!"; System.out.println("\"" + s1 + "\"" + "is " + s1.length() + " characters long."); } } Liang, Oreilly, Herbert Schildt, Joseph O’Neil • Concatenating Strings Concatenating strings means joining them together. // Concatenating strings means joining them together. public class Concatenating { public static void main(String[] args) { String s1 = "Hello!"; String s2 = s1 + "from"; String s3 = s2 + "Java"; String s4 = s1.concat("from"); String s5 = s4.concat(" Java!"); System.out.println(s3); System.out.println(s5); } Liang, Oreilly, Herbert Schildt, Joseph O’Neil Getting Characters and Substring public class GettingChar { public static void main(String[] args) { String s1 = "Hello from Java!"; char c1 = s1.charAt(0); System.out.println("The first character of \"" + s1 + "\" is " + c1); } } Liang, Oreilly, Herbert Schildt, Joseph O’Neil Converting a String object into a char array //Using toCharArray and getChars public class GettingCharArray { public static void main(String[] args) { String s1 = "Hello from Java!"; char c1 = s1.charAt(0); System.out.println("The first character of \"" + s1 + "\" is " + c1); char chars1[] = s1.toCharArray(); System.out.println("The second character of \"" + s1 + "\" is " + chars1[1]); char chars2[] = new char[5]; s1.getChars(0, 5, chars2, 0); System.out.println("The first five character of \"" + s1 + "\" are " + new String(chars2)); } Liang, Oreilly, Herbert Schildt, Joseph O’Neil } Searching for and replacing Strings // Using indexOf, lastIndexOf public class IndexOf { public static void main(String[] args) { String s1 = "I have drawn a nice drawing!"; System.out.println("The first position of draw is " + s1.indexOf("draw")); System.out.println("The last position of draw is at location " + s1.lastIndexOf("draw")); String s2 = "Edna, you're hired!"; System.out.println(s2.replace('h', 'f')); } } Liang, Oreilly, Herbert Schildt, Joseph O’Neil Changing Case in Strings //Using toLowerCase, toUpperCase public class LowerUpperCase { public static void main(String[] args) { System.out.println("Hello from Java!".toLowerCase()); System.out.println("Hello from Java!".toUpperCase()); } } Liang, Oreilly, Herbert Schildt, Joseph O’Neil Formatting Numbers in Strings //Formatting import java.text.*; public class Formatting { public static void main(String[] args) { double value = 1.23456789; NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMaximumFractionDigits(6); String s = nf.format(value); System.out.println(s); } } Liang, Oreilly, Herbert Schildt, Joseph O’Neil The String class • • • The String class provides several good examples of instance methods. You may declare a variable of type String and initialize it with a string. Example: – String s = “Enter an integer value: “; • • • After this statement executes, s contains the string “Enter an integer value:.”. You can use it anywhere. (see Table 2-2) Liang, Oreilly, Herbert Schildt, Joseph O’Neil Example Class First10Chars { public static void main(String args[]) { String s = “One Two Three Four Five Six Seven”; String substring = s. substring(0, 10); System.out.println(substring); } } Liang, Oreilly, Herbert Schildt, Joseph O’Neil Output • One Two Th • It s=displays the substring formed by the first 10 characters of string Liang, Oreilly, Herbert Schildt, Joseph O’Neil Integer Class • Integer is one of the commonly used classes in the Java class libraries. • An integer object encapsulates a simple int value. • In other words, • Integer is a wrapper class for int. • Integer is an excellent example of a class that provides both static and instance methods. Liang, Oreilly, Herbert Schildt, Joseph O’Neil The Integer MAX_VALUE • The Integer class defined MAX_VALUE and MIN_VALUE as two of its static variables. • These contain the maximum and minimum values that can be accommodate by the 32 bits of a simple int type. (See table 2-3, 2-4) Liang, Oreilly, Herbert Schildt, Joseph O’Neil Table 2-3, 2-4 • Table 2-3 summarizes some of the most commonly used static methods of this class. • Notice that some of these methods can generate an exception if their string argument is not correctly formatted. • Table 2-4 summarizes some of the most commonly used instance methods of this class. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Example The following program illustrates how some of the Integer static and instance methods can be used. } public class StringToInt { public static void main(String[] args) { //Declare variables String s = “125”; Integer obj = Integer.valueOf(s); int i = obj.intValue(); i += 10; System.out.println(i); } Liang, Oreilly, Herbert Schildt, Joseph O’Neil Explain please…. • The main() method begins by assigning a string literal to variable s. • The static method valueOf() accepts this String object as an argument. • It creates a new Integer object that encapsulates the value represented by s and returns this object. • This object is assigned to the variable obj. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Keep explaining… • The instance method named intValue() is then used to obtain a simple int equivalent to the value encapsulated by obj. • The value returned by this method is assigned to the variable i. • The variable i is incremented by 10 and displayed by println(). Liang, Oreilly, Herbert Schildt, Joseph O’Neil Output • The output is 135 Liang, Oreilly, Herbert Schildt, Joseph O’Neil Chapt 8 con’t Inheritance • Inheritance and variables • The class inherits the state and behavior defined by all of its superclasses. • State is determined by variables; • Behavior is determined by methods. • Therefore, an object has one copy of every instance variable defined not only by its class but also by every superclass of its class. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Inheritance and Variables • A static or instance variable in a subclass may have the same name as a superclass variable. • In that case, the variable hides the superclass variable. • These two variables may have the same type or different types. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Inheritance and variables • The following application demonstrates a class inheritance hierarchy. • Class W extends Object and has one instance variable of type float. • Class X extends W and has one instance variable of type StringBuffer. • Class Y extends X and has one instance variable of type String. • Class Z extends Y and has one instance variable of type Integer. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Inheritance and Variable con’t • An object of class Z has the instance variables that are defined in all of the superclasses. • The main() method instantiates class Z with the new operator, initializes the instance variables, and displays their values. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Example: Inheritance and variables • Class W { float f; } class X extends W { StringBuffer sb; } class Y extends X { String s; } class Z extends Y { Integer i; } Liang, Oreilly, Herbert Schildt, Joseph O’Neil Example: Inheritance and Variables • Class Wxyz { public static void main(String[] args) { Z z = new Z(); z.f = 4.567f; z.sb = new StringBuffer(“abcde”); z.s = “ Learning this Inheritance Stuff”; z.i = new Integer(41); System.out.println(“z.f = “ + z.f); System.out.println(“z.sb = “ + z.sb); System.out.println(“z.s = “ + z.s); System.out.println(“z.i = “ + z.i); } } Liang, Oreilly, Herbert Schildt, Joseph O’Neil Final The following application illustrates how the final keyword can be used in a class modifier. This program does no compile because • the declaration of V2 attempts to extend V1, • which is declared as a final class • • • • Final cannot be extended. classes are sometimes declared in this manner so the methods implemented by that class cannot be overridden. Liang, Oreilly, Herbert Schildt, Joseph O’Neil final con’t • One of the common uses of final is to create named constants. • For example, the following application illustrates this use of final. • It creates a variable x whose value cannot be changed. Liang, Oreilly, Herbert Schildt, Joseph O’Neil final con’t • One of the common uses of final is to create named constants. • For example, the following application illustrates this use of final. • It creates a variable x whose value cannot be changed. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Example: Final final class V1 { } class V2 extends V1 { } class FinalClass { public static void main(String args[]) { V1 obj = new V1(); } } //Will not compile because cannot inherit from final V1 //class V2 extends V1 // cannot inherit from final V1 //class V2 extends V1 because final cannot be extended Liang, Oreilly, Herbert Schildt, Joseph O’Neil Example: final class L { static final int x = 5; } class FinalVariable { public static void main(String[] args) { System.out.println(L.x); } } Liang, Oreilly, Herbert Schildt, Joseph O’Neil Constructor Modifiers These are three modifiers that may precede the declaration of A constructor. These are summarized in the following table: Keyword Meaning Private Can be invoked only by code in the same class Protected Can be invoked only by code in a subclass Or the same package Public Can be invoked by any other class Liang, Oreilly, Herbert Schildt, Joseph O’Neil Example • The class JetPlane declares one abstract method named numEngines(). • Therefore, the class itself must also be declared abstract. • There are two concrete subclasses named DC8 and DC10. Each of these provided a different implementation of numEngines() method. • The main() method instantiates each of these classes and invoke its numEngines method. • This is an excellent example of run-time polymorphism. • Each subclass provides a different form of the method. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Example abstract class JetPlane { abstract int numEngines(); } class DC8 extends JetPlane { int numEngines() { return 4; } } Liang, Oreilly, Herbert Schildt, Joseph O’Neil Example cont class DC10 extends JetPlane { int numEngines() { return 3; } } Liang, Oreilly, Herbert Schildt, Joseph O’Neil Example cont class JetPlanes { public static void main(String[] args) { System.out.println(new DC8().numEngines()); System.out.println(new DC10().numEngines()); } } Liang, Oreilly, Herbert Schildt, Joseph O’Neil Chapt 9 Applets • How applets and Applications Are Different? • Java applications are standalone Java programs that can be run by using just the Java interpreter. • Java applets, however, are from inside a WWW browser. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Creating applets • To create an applet, you create a subclass of the class Applet. • The applet class, part of the java.applet package provides much of the behavior your applet needs to work inside a java-enabled browser. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Creating applets con’t • Applets also take strong advantage of Java’s Abstract Windowing Toolkit and applications: drawing to the screen: creating windows, menu bars, buttons, check boxes, and other UI elements; and managing user input such as mouse clicks and keypresses. • The AWT classes are part of the java.awt.package. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Major applet activities • To create a basic Java application, your class has to have one method, main() method, with a specific signature. • Then, when your application runs, main() is found and executed, and from main() you can set up the behavior that your program needs to run. Liang, Oreilly, Herbert Schildt, Joseph O’Neil Creating applets con’t • Applets are similar but more complicated - and in facts, applets don’t need a main() method at all. • Applets have many different activities that correspond to various major events in the life cycle of the applet. For example, initialization, painting, and mouse events. Each activities has a corresponding method, so when an event occurs, the browser or other Javaenabled tool calls those specific methods. Liang, Oreilly, Herbert Schildt, Joseph O’Neil 5 important Applets methods Initialization- occurs when the applet is first loaded or reloaded, similar to the main() method. public void init(){... } Starting- start the applet (can happen many different times during an applet’s lifetime. public void start(){... } Liang, Oreilly, Herbert Schildt, Joseph O’Neil 5 important Applets methods • Painting- is the way the applet actually draws something on the screen, be it text, a line, a colored background, or an image. – public void paint(Graphics g){…..} Liang, Oreilly, Herbert Schildt, Joseph O’Neil 5 important applets methods Stopping- goes hand in hand with starting. Stopping occurs when the reader leaves the page that contains a currently running applet, or you can stop the applet yourself by calling stop(). public void stop(){….} • Destroying- enables the applet to clean up after itself just before it is freed or the browser exits. – public void destroy(){…. } Liang, Oreilly, Herbert Schildt, Joseph O’Neil The keyword “super” • It is possible to access a hidden variable by using the super keyword, as follows: super.VarName Here, varName is the name of the variable in the superclass. This syntax may be use to read or write the hidden variable. Liang, Oreilly, Herbert Schildt, Joseph O’Neil