1CMSC433, Spring 2004 Programming Language Technology andParadigms Java ReviewJeff FosterFeburary 3, 200433Administrivia• Reading: Liskov, ch 4, optional Eckel, ch 8, 9• Project 1 posted– Part 2 was revised Friday to make it better, easier– A few subsequent small clarifications since then– Important: Must change WebServer to use -Dport=...• Class accounts e-mailed out– Contact me if you didn’t get one34Demo• Running basic web server– Finding hostname of machine– Connecting with web browser• Telnet to a web server35Objects and Variables• Variables of a primitive type contain values– e.g., byte, char, int, ...– int i = 6;– Uninitialized values contain 0– Assignment copies values• Variables of other types contain references to the heap– int[] a = new int[3];– Objects are allocated with new– Uninitialized object references are null– Assignment copies references, not the objects themselves36Exampleint i = 6;int j; // uninitializedint [] a = {1, 3, 5, 7, 9};int [] b = new int[3];String s = “abcdef”;String t = null;37Example: Assignmentsj = i;b = a;t = s;238Garbage Collection• What happens to array [0, 0, 0] in previousexample?– It is no longer accessible– When Java performs garbage collection (GC) it willautomatically reclaim the memory it uses• Notice: No free() or delete in Java– Makes it much easier to write correct programs– Most of the time, very efficient39Mutability• An object is mutable if its state can change– Example: Arrays are mutable• An object is immutable if its state never changes– Once its been initialized– Example: Strings in Java are not mutable• There are no methods to change the state of a string40Example: Mutabilitya[1] = 0;// also changes b[1]• Moral: Always becareful when you havealiasing– Multiple references to thesame object41Method Invocation• Syntaxo.m(arg1, arg2, ..., argn);– Run the m method of object o with argumentsarg1...argn• Two ways to reuse method names:– Methods can be overridden– Methods can be overloaded42Overriding• Define a method also defined by a superclassclass Parent { int cost; void add(int x) { cost += x; }}class Child extends Parent { void add(int x) { if (x > 0) cost += x; }}43Overriding (cont’d)• Method with same name and argument types inchild class overrides method in parent class• Arguments and result types must be identical– otherwise you are overloading the method• Must raise the same or fewer exceptions• Can override/hide instance variables– both variables will exist, but don’t do it344Declared vs. Actual Types• The actual type of an object is its allocated type– Integer o = new Integer(1);• A declared type is a type at which an object isbeing viewed– Object o = new Integer(1);– void m(Object o) { ... }• Each object always has one actual type, but canhave many declared types45Method Dispatch• Consider againo.m(arg1, arg2, ..., argn);• Only compiles if o’s declared type contains anappropriate m method• Method corresponding to o’s actual type is what isinvoked46Dynamic Dispatch Examplepublic class A { String f() { return “I’m an A! “; }}public class B extends A { String f() { return “I’m a B! “; } public static void main(String args[]) { A a = new B(); B b = new B(); System.out.println(a.f() + b.f()); }}Prints I’m a B! I’m a B!47Self Reference• this refers to the object the method is invoked on– Thus can access fields of this object as this.x or this.y– But more concise to omit• super refers to the same object as this– But used to access methods/variables in superclass48Example of super• Call a superclass method from a subclassclass Parent { int cost; void add(int x) { cost += x; }}class Child extends Parent { void add(int x) { if (x > 0) super.add(x); }}49Overloading• Methods with the same name, but differentparameters (count or types) are overloaded– Invocation determined by name and types of params– Not return value or exceptions• Resolved at compile-time, based on declared types• Be careful: Easy to inadvertently overload insteadof override!450Overloading Exampleclass Parent { int cost; void add(int x) { cost += x; } void add(Object s) throws NumberFormatException { cost += Integer.parseInt((String)s); }}class Child extends Parent { void add(String s) throws NumberFormatException { if (x > 0) cost += Integer.parseInt(s); }}Child c = new Child();c.add((Object)“-1”);System.out.println(c.cost);Prints -151Static Fields and Methods• static – stored “with the class”– Static fields allocated once, no matter how manyobjects created– Static methods are not specific to any class instance, socannot refer to this or super• Can reference class variables and methods througheither class name or an object ref– Clearer to reference via the class name52Static Field Exampleint fooint fooint fooFooint bar;Public class Foo { int foo; static int bar;}Class definitionClass implementationObjects of class Foo53Some Static Fields and Methods• public static void main(String args[]) { … }• public class Math { public final static PI = 3.14159…; }• public class System { public static PrintStream out = …; }54Actual type BDeclared type AStatic Method Dispatch• Let B be a subclass of A, and suppose we haveA a = new B();• Then– Class (static) methods invoked on a will get the methods forthe declared type A• Invoking class methods via objects strongly discouraged• Instead, invoke through class– A.m() instead of a.m()55Static Method Dispatch Examplepublic class A { static String g() { return “This is A! “; }}public class B extends A { static String g() { return “This is B! “; } public static void main(String args[]) { A a = new B(); B b = new B(); System.out.println(a.g() + b.g()); }}Prints This is A! This is B!556Better Use of Static Methodspublic class A { static String g() { return “This is A! “; }}public class B extends A { static String g() { return “This is B! “; } public static void main(String args[]) { System.out.println(A.g() + B.g()); }}Prints This is A! This is B!57Other Field Modifiers• final – can’t be changed– Must be initialized in declaration or in constructor• transient, volatile– Will cover later• public, private, protected, package (default)– Respectively, visible everywhere, only within
View Full Document