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
:: INT304 :: Programming Syntax & Semantics Rules About Overridden Methods Notes Must have a return type that is identical to the method it overrides Cannot be less accessible than the method it overrides Cannot throw more exceptions than the method it overrides If the keyword super is not explicitly used, the superclass's default constructor is automatically invoked. If a superclass defines constructors other than a default constructor, the subclass cannot use the default constructor of the superclass. public class Employee{ // public Employee (String name){ public Employee (){ System.out.println(“Employee constructed”); } } public class Manager extends Employee{ public Manager(){ System.out.println(“Manager constructed”); } } public class Test { public static void main(String args[]) { Manager m1 = new Manager() ; } } public class Parent { int i = 10 ; public void f1() { System.out.println(“I am Parent”); } } public class Child extends Parent{ String i = “I love you !!” ; private void f1() { System.out.println(“I am Child”); } } public class UseBoth { public static void main(String args[]){ Parent p1 = new Parent(); Parent p2 = new Child(); p1.method(); p2.method(); System.out.println(p2.i); } } © Copyright Khaitong-2-5-0-9. 2003 :: INT304 :: Programming Syntax & Semantics Page: 1 of 19 © Copyright Khaitong-2-5-0-9. 2003 Page: 2 of 19 :: INT304 :: Programming Syntax & Semantics Grouping Classes Packages ~ Package declaration must be specified at the beginning of the source file ~ Only one package declaration is permitted per source file Directory Layout and the CLASSPATH Environment Variable Packages are stored in a directory tree containing the package name. package abc.financedept; public class Employee { ... // Class Employee of the Finance // department for the ABC company package abc.financedept; public class Employee { } :: INT304 :: Programming Syntax & Semantics } javac –d . Employee.java ... What is directory path for Employee.class ? <current-directory>/abc/financedept ~ Package names are hierarchical and separated by dots. The import Statement The roots of package trees to search for class files are in the CLASSPATH Example ~ Tells the compiler where to find classes to use javac–d /java/mylib/mypackages Employee.java Employee.class stored in ~ Must precede all class declarations import abc.financedept.*; public class Manager extends Employee{ String department; /java/mylib/mypackages/abc/financedept CLASSPATH = /java/mylib/mypackages Employee[] subordinates; } © Copyright Khaitong-2-5-0-9. 2003 Page: 3 of 19 © Copyright Khaitong-2-5-0-9. 2003 Page: 4 of 19 :: INT304 :: Programming Syntax & Semantics :: INT304 :: Programming Syntax & Semantics Static Initialize The Final Keyword A class can contain code in a static block that does not exist within a method body. Static block code executes only once, when the class is loaded. public class StaticInitDemo{ static int i=5; static { System.out.println(“Static code i= “+ i++); } } public class Test{ public static void main(String args[]){ System.out.println(“Main code: I = “ + } A final class cannot be subclassed. A final method cannot be overridden. A final variable is a constant. Note: If you mark a variable of reference type as final, that variable cannot refer to any other object. It is however possible to change the object’s contents, as only the reference itself is final StaticInitDemo.i); } © Copyright Khaitong-2-5-0-9. 2003 Page: 5 of 19 © Copyright Khaitong-2-5-0-9. 2003 Page: 6 of 19 :: INT304 :: Programming Syntax & Semantics Abstract Classes :: INT304 :: Programming Syntax & Semantics Interfaces A class which declares the existence of methods but not the implementation is called an abstract class. A class can be declared as abstract by marking it with the abstract keyword. public abstract class Drawing{ public abstract void drawDot(int x, int y); public void drawLine(int x1,int y1,int x2,int y2){ //draw using the drawDot() method repeatedly. } } An abstract class can contain non-abstract methods and variables. An interface is a variation on the idea of an abstract class. In an interface, all the methods are abstract. Multiple inheritance can be achieved by implementing such interfaces. The syntax is public interface Stack { public static final int EMPTY = -1; public void push(Object item) ; public Object pop () ; public int size() ; } Note: We cannot create an instance from an abstract class using the new operator, but an abstract class can be used as a data type. Therefore, the following statement, which creates an array whose elements are of Drawing type, is correct. class PCDrawing extends Drawing { public void drawDot(int x, int y) { } } Drawing dx = new PCDrawing() ; Drawing d1[] = new Drawing[10] ; © Copyright Khaitong-2-5-0-9. 2003 Page: 7 of 19 © Copyright Khaitong-2-5-0-9. 2003 Page: 8 of 19 :: INT304 :: Programming Syntax & Semantics Interfaces (2) Interfaces are useful for ~ Declaring methods that one or more classes are expected to implement ~ Determining an object’s programming interface without revealing the actual body of the class ~ Capturing similarities between unrelated classes without forcing a class relationship ~ Describing “function-like” objects that can be passed as parameters to methods invoked on other objects :: INT304 :: Programming Syntax & Semantics The Cloneable Interfaces Marker Interface: An empty interface. A marker interface does not contain constants or methods, but it has a special meaning to the Java system. The Java system requires a class to implement the Cloneable interface to become cloneable. class Student implements Cloneable { ... } ... ... Student st1 = new Student(); Student st2 = (Student) st1.clone(); public interface Comparable { public int compareTo(Object o) ; } class Student implements Comparable { public int compareTo(Object o){. . .} } ... ... Student st1 = new Student(); Student st2 = (Student) st1.clone(); boolean b1 = st1.compareTo(st2) ; © Copyright Khaitong-2-5-0-9. 2003 Page: 9 of 19 © Copyright Khaitong-2-5-0-9. 2003 Page: 10 of 19 :: INT304 :: Programming Syntax & Semantics Advanced Access Control Modifier :: INT304 :: Programming Syntax & Semantics Deprecation Same Class Same Package Subclass Universe public yes yes yes yes protected yes yes Yes X default yes Yes X X private Yes X X X Deprecation is the obsoleting of class constructors and method calls. Obsoleted methods and constructors are replaced by methods with a more standardized naming convention. When migrating code, compile the code with the -deprecation flag: javac –deprecation MyFile.java pacakge p1 class C1 protected int x class C3 C1 c1; c1.x can be read or modified © Copyright Khaitong-2-5-0-9. 2003 pacakge p2 class C2 extends C1 x can be read or modified in C2 class C4 C1 c1; c1.x cannot be read nor modified Page: 11 of 19 © Copyright Khaitong-2-5-0-9. 2003 Page: 12 of 19 :: INT304 :: Programming Syntax & Semantics The == Operator Versus equals() Method :: INT304 :: Programming Syntax & Semantics Inner Classes The equals() and == methods determine if reference values refer to the same object. Allow a class definition to be placed inside another class definition The equals() method is overridden in classes in order to return true if the contents and type of two separate objects match. Group classes that logically belong together public class Student { private int id ; private String name ; . . . public boolean equals(Object stObj) throws ClassMismatchException { if ( !(stObj instanceof Student) ) throw new ClassMismatchException(); if (id == stObj.id && name.equals(stObj.name) ) return true; return false; } } Have access to their enclosing class’s scope import java.awt.*; import java.awt.event.*; public class MyFrame extends Frame { Button myButton; TextArea myTextArea; int count; public MyFrame() { super("Inner Class Frame"); myButton = new Button("click me"); myTextArea = new TextArea(); add(myButton, BorderLayout.CENTER); add(myTextArea, BorderLayout.NORTH); ButtonListener bList = new ButtonListener(); myButton.addActionListener(bList); } class ButtonListener implements ActionListener { public void actionPerformed (ActionEvent e) { count++; myTextArea.setText("clicked: "+ count+ "times"); } } // end of innerclass ButtonListener public static void main(String args[]) { MyFrame f = new MyFrame(); f.setSize(300, 300); f.setVisible(true); } }// end of class MyFrame © Copyright Khaitong-2-5-0-9. 2003 Page: 13 of 19 © Copyright Khaitong-2-5-0-9. 2003 Page: 14 of 19 :: INT304 :: Programming Syntax & Semantics Collection API :: INT304 :: Programming Syntax & Semantics The Vector class A collection (or a container) is a single object representing a group of objects, known as its elements. The Vector or class provides methods for working with dynamic arrays of varied element types. Collection classes Vector, Bits, Stack, Hashtable, LinkedList, and so on are supported. The Collections API contains interfaces which maintain objects as a ~ Collection – A group of objects with no specific ordering ~ Set – A group of objects with no duplication ~ List – A group of ordered objects; duplication is permitted Synopsis ~ Each vector maintains a capacity and capacityIncrement. ~ As elements are added, storage for the vector increases in chunks up to the size of the capacityIncrement variable. ~ Constructors public Vector() public Vector(int initialCapacity) public Vector(int initialCapacity, int capacityIncrement) ~ Variables protected int capacityIncrement protected int elementCount protected Object elementData[ ] ~ Methods public final int size() - Returns the number of elementsin the vector. (This is not the same as the vector’s capacity.) public final boolean contains (Object elem) - Returns true if the specified object is a value of the collection. © Copyright Khaitong-2-5-0-9. 2003 Page: 15 of 19 © Copyright Khaitong-2-5-0-9. 2003 Page: 16 of 19 :: INT304 :: Programming Syntax & Semantics Example : Using the Vector Synopsis public final int indexOf (Object elem) – Searches for the specified object starting from the first position, and returns an index to it (or -1 if the element is not found). It uses the object’s equals() method, so if this object does not override Object’s equals() method, it will only compare object references, not object contents. public final synchronized Object elementAt (int index) - Returns the element at the specified index. It throws ArrayIndexOutOfBoundsException if index is invalid. public final synchronized void setElementAt (Object obj, int index) - Replaces the element at the specified index with the specified object. It throws ArrayIndexOutOfBoundsException if indexis invalid. public final synchronized void removeElementAt (int index) - Deletes the element at the specified index. It throws ArrayIndexOutOfBoundsException if index is invalid public final synchronized void addElement (Object obj) - Adds the specified object as the last element of the vector. public final synchronized void insertElementAt (Object obj, int index) - Inserts the specified object as an element at the specified index, shifting up all elements with equal or greater index. It throws ArrayIndexOutOfBoundsException if index is invalid © Copyright Khaitong-2-5-0-9. 2003 :: INT304 :: Programming Syntax & Semantics Page: 17 of 19 import java.util.*; public class MyVector extends Vector { public MyVector() { super(1, 1); //storage capacity & capacityIncrement } public void addInt(int i) { addElement(new Student(i)); // addElement requires object arg } public void addFloat(float f) { addElement(new Float(f)); } public void addString(String s) { addElement(s); } public void addCharArray(char a[]) { addElement(a); } public void printVector() { Object o; int length = size(); //compare with capacity() System.out.println("Number of vector elements is " + length + " and they are: "); for (int i = 0; i < length; i++) { o = elementAt(i); if (o instanceof char[ ]) { // An array's toString() method does not print what we want. System.out.println(String.copyValueOf((char[ ]) o)); } else System.out.println(o.toString()); } } © Copyright Khaitong-2-5-0-9. 2003 Page: 18 of 19 :: INT304 :: Programming Syntax & Semantics public static void main(String args[]) { MyVector v = new MyVector(); int digit = 5; float real = 3.14f; char letters[] = {'a', 'b', 'c', 'd'}; String s = new String ("Hi there!"); v.addInt(digit); v.addFloat(real); v.addString(s); v.addCharArray(letters); v.printVector(); } } JPanel DescPanel - jtaTextDesc: JTextArea - jlblTitle: JLabel - jlblImage: JLabel + setTitle(title: String): void + setIcon(icon: ImageIcon): void + setTextDesc(text: String): void + getMinSize(): Dimension © Copyright Khaitong-2-5-0-9. 2003 JFrame 1 TextAreaDemo ActionListener WindowListener Page: 19 of 19