06/27/02 Amir Kamil Topic: Running a Program, Scope, "this", Parameter Passing, Control Structures, Arrays, Lists, Inheritance Homework: - Some students have wanted to write problem 1b using the answer to 1c (i.e. converting both DigitLists to ints, adding the ints, converting back to a DigitList). However, there is an important case in which this won't work. So don't do it. - Remember, homework is due midnight on Sunday. Running a Program: - Java programs are run from the command line. First you must compile your code (e.g. javac -g Foo.java) in order to get its .class file. Then you run the program by typing "java " (e.g. java Foo) at the command line. There are a few requirements in order to run a program: 1. You must have a method defined with the following prototype: public static void main(String[] args) The accessor does not necessarily have to public, however, and the parameter name can be anything. 2. The class that contains the above method must be defined in a file with the same name as the class. For example, you cannot run Foo.main() if you defined Foo in Bar.java. When you run the program from the command line, the Java machine runs the code in the above method. Command line arguments are placed in the String[] parameter. - Example: public class Computer { ... // variables and methods public static void main(String[] args) { Computer comp = new Computer("Unix"); comp.turnOn(); comp.boot(); System.out.println("state = " + comp.state); return; } } Scope: - Variable names refer to the variable of that name in the inner-most scope: public class Computer { String os; public Computer(String os) { /* Here, "os" would refer to the object passed in as the * argument */ } } - Inner variables need not be of the same type as outer variables of the same name: public class Computer { int os; public Computer(String os) { // this works fine ... } } "this": - The keyword "this" refers to the current object. It can be used to refer to instance variables when their names are obscured by scoping rules. In the above example, "this.os" in the body of the constructor would refer to the instance variable "os". - As you saw in lab, you can also call constructors using "this(...)". However, you can only do so from another constructor, and only as the first statement in the body of the constructor: public Computer(String os) { this(); // works this.os = os; } public Computer(String os) { this.os = os; this(); // doesn't work } Parameter Passing: - Parameter passing is ALWAYS pass-by-value. Remember that containers for primitive types contain values of their respective types, while containers for objects contain values that are references to objects. The value of this container is what is passed when a method is called. Control Structures: - if statement: if () { } ==OR== if () { } else { } If a clause is only one statement, braces surrounding it can be omitted. Cascaded if: if (...) { ... } else if (...) { ... } else { ... } - while loop: while () { } Execution starts by checking the condition. The body is evaluated if the condition is true, and the process is repeated. This continues until the condition evaluates to false, in which case execution proceeds to the next statement after the loop. - do while loop: do { } while (); This is similar to the while loop, except the condition is checked at the end of each iteration. As a result, the body will execute at least once. Equivalent: while () { } - for loop: for (; ; ) { } The init statement is run first, then the condition is checked. If it is true, the body is executed, the update statement is executed, and the condition is rechecked. This continues until the condition is false. Note that the init statement is only run once. Equivalent: while () { } Arrays: - The first data structure you have learned. - Declaration: [] ; Examples: int[] numbers; String[] sentences; - Creation: new [] Examples: int[] numbers = new int[4]; String[] sentences = new String[18]; Another way: int[] numbers = {1, 2, 3}; This creates an int array of size three with the above elements. - Access: To access the nth element in an array: [n] Example: numbers[2] = 4; - As shown above, array elements can be assigned to. - Array indexing starts at 0, i.e. the first element of numbers is numbers[0]. - Legal array access is limited to n between 0 and one less than the size of the array, inclusive. To get the size of numbers, use numbers.length. - Arrays are objects and therefore have methods and fields. They inherit all methods and fields from the Object class. - Primitive arrays (e.g. int[]) store values of their respective types, while object arrays (e.g. Computer[]) store references to objects of their respective types. - Diagram on board. Lists: - If you have started the homework, then you have seen lists already. - We will divide a list into two parts: the overall list container and the individual nodes. - Nodes: public class ListNode { public ListNode next; // the next node in the list public int data; public ListNode(int data, List next) { this.data = data; this.next = next; } } - List container: public class SList { public ListNode head; public SList() { head = null; } // insert a value at the front of the list public void insertFront(int value) { head = new ListNode(value, head); } // remove the front of the list, return its value public int removeFront() { int value = head.value; head = head.next; return value; } } Inheritance: - Every class has a parent class, except the built-in Object class. For classes that you define without specifying a parent, its parent is assumed to be the Object class. - Java only allows a single parent for each class. - The class heirarchy forms a tree, with Object at its root. (Diagram on board). - All methods and fields in the parent class are inherited by the child. So calling a method defined in a parent class from a child class is perfectly fine. - Children can "override" parents' methods by redefining them. Then calling the overridden method in the child will use the child's version of the method. Overridden methods must retain the same return type. - Inheritance in Java: public class Laptop extends Computer {..} "extends" keyword used to declare parent. In this case, you are defining a Laptop class with Computer as its parent. - Example: public class Laptop extends Computer { int battery; // charge remaining on battery, in minutes /* Override turnOn() method to check battery charge */ public void turnOn() { if (battery <= 5) { System.out.println("Battery Low"); } else { state = 1; boot(); } } /* Add charge method */ public void charge(int time) { battery += time; } } Next Time: More Inheritance (Conformity, Abstract Classes, Interfaces), Modifiers, Exceptions