King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS201 Lecture 1 : Inheritance I Slides prepared by Rose Williams, Binghamton University Introduction to Inheritance Inheritance is one of the main techniques of object-oriented programming (OOP) Using this technique, a very general form of a class is first defined and compiled, and then more specialized versions of the class are defined by adding instance variables and methods The specialized classes are said to inherit the methods and instance variables of the general class Base Class Derived Class Employee Example Employee Example Employee HourlyEmployee SalariedEmployee Employee Example Introduction to Inheritance Inheritance is the process by which a new class is created from another class The new class is called a derived class The original class is called the base class A derived class automatically has all the instance variables and methods that the base class has, and it can have additional methods and/or instance variables as well Inheritance is especially advantageous because it allows code to be reused, without having to copy it into the definitions of the derived classes Derived Classes Since an hourly employee is an employee, it is defined as a derived class of the class Employee A derived class is defined by adding instance variables and methods to an existing class The existing class that the derived class is built upon is called the base class The phrase extends BaseClass must be added to the derived class definition: public class HourlyEmployee extends Employee The derived class inherits all the public methods, all the public and private instance variables, and all the public and private static variables from the base class The derived class can add more instance variables, static variables, and/or methods Inherited Members A derived class automatically has all the instance variables, all the static variables, and all the public methods of the base class Members from the base class are said to be inherited Definitions for the inherited variables and methods do not appear in the derived class The code is reused without having to explicitly copy it, unless the creator of the derived class redefines one or more of the base class methods Parent and Child Classes A base class is often called the parent class A derived class is then called a child class These relationships are often extended such that a class that is a parent of a parent . . . of another class is called an ancestor class If class A is an ancestor of class B, then class B can be called a descendent of class A Overriding a Method Definition Although a derived class inherits methods from the base class, it can change or override an inherited method if necessary In order to override a method definition, a new definition of the method is simply placed in the class definition, just like any other method that is added to the derived class Employee Example Changing the Return Type of an Overridden Method Ordinarily, the type returned may not be changed when overriding a method However, if it is a class type, then the returned type may be changed to that of any descendent class of the returned type This is known as a covariant return type Covariant return types are new in Java 5.0; they are not allowed in earlier versions of Java Covariant Return Type Given the following base class: public class BaseClass { . . . public Employee getSomeone(int someKey) . . . The following is allowed in Java 5.0: public class DerivedClass extends BaseClass { . . . public HourlyEmployee getSomeone(int someKey) . . . Changing the Access Permission of an Overridden Method The access permission of an overridden method can be changed from private in the base class to public (or some other more permissive access) in the derived class However, the access permission of an overridden method can not be changed from public in the base class to a more restricted access permission in the derived class Changing the Access Permission of an Overridden Method (Example) Given the following method header in a base case: private void doSomething() The following method header is valid in a derived class: public void doSomething() However, the opposite is not valid Given the following method header in a base case: public void doSomething() The following method header is not valid in a derived class: private void doSomething() Pitfall: Overriding Versus Overloading Do not confuse overriding a method in a derived class with overloading a method name When a method is overridden, the new method definition given in the derived class has the exact same number and types of parameters as in the base class When a method in a derived class has a different signature from the method in the base class, that is overloading Note that when the derived class overloads the original method, it still inherits the original method from the base class as well The final Modifier If the modifier final is placed before the definition of a method, then that method may not be redefined in a derived class It the modifier final is placed before the definition of a class, then that class may not be used as a base class to derive other classes The end King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS201 Lecture 2 : Inheritance II Slides prepared by Rose Williams, Binghamton University The super Constructor A derived class uses a constructor from the base class to initialize all the data inherited from the base class. In order to invoke a constructor from the base class, it uses a special syntax: public derivedClass(int p1, int p2, double p3) { super(p1, p2); instanceVariable = p3; } In the above example, super(p1, p2); is a call to the base class constructor The super Constructor A call to the base class constructor can never use the name of the base class, but uses the keyword super instead A call to super must always be the first action taken in a constructor definition An instance variable cannot be used as an argument to super If a derived class constructor does not include an invocation of super, then the no-argument constructor of the base class will automatically be invoked. The this Constructor Within the definition of a constructor for a class, this can be used as a name for invoking another constructor in the same class. If it is necessary to include a call to both super and this, the call using this must be made first, and then the constructor that is called must call super as its first action The this Constructor Often, a no-argument constructor uses this to invoke an explicit-value constructor A no-argument constructor public ClassName() { this(argument1, argument2); } Explicit-value constructor (receives default values): public ClassName(type1 param1, type2 param2) { . . . } The this Constructor (example) public HourlyEmployee() { this("No name", new Date(), 0, 0); } The above constructor will cause the constructor with the following heading to be invoked: public HourlyEmployee(String theName, Date theDate, double theWageRate, double theHours) Important: An Object of a Derived Class Has More than One Type An object of a derived class has the type of the derived class, and it also has the type of the base class. More generally, an object of a derived class has the type of every one of its ancestor classes Therefore, an object of a derived class can be assigned to a variable of any ancestor type An object of a derived class can be plugged in as a parameter in place of any of its ancestor classes In fact, a derived class object can be used anyplace that an object of any of its ancestor types can be used Note, however, that this relationship does not go the other way An ancestor type can never be used in place of one of its derived types Important: An Object of a Derived Class Has More than One Type Encapsulation and Inheritance Pitfall: Use of Private Instance Variables from the Base Class An instance variable that is private in a base class is not accessible by name in the definition of a method in any other class, not even in a method definition of a derived class Encapsulation and Inheritance Pitfall: Use of Private Instance Variables from the Base Class Instead, a private instance variable of the base class can only be accessed by the public accessor and mutator methods defined in that class Pitfall: Private Methods Are Effectively Not Inherited The private methods of the base class are like private variables in terms of not being directly available However, a private method is completely unavailable, unless invoked indirectly This is possible only if an object of a derived class invokes a public method of the base class that happens to invoke the private method protected and package Access If a method or instance variable is modified by protected (rather than public or private), then it can be accessed by name : Inside its own class definition Inside any class derived from it In the definition of any class in the same package Instance variables or methods having package access can be accessed by name inside the definition of any class in the same package However, neither can be accessed outside the package The default access If the access modifier is omitted : public class Movie { public String title; int nbrOscars; …… } Then, the access will be : package Access Modifiers Pitfall: Forgetting About the Default Package When considering package access, do not forget the default package All classes in the current directory (not belonging to some other package) belong to an unnamed package called the default package If a class in the current directory is not in any other package, then it is in the default package If an instance variable or method has package access, it can be accessed by name in the definition of any other class in the default package Pitfall: A Restriction on Protected Access If a class B is derived from class A, and class A has a protected instance variable n, but the classes A and B are in different packages, then the following is true: A method in class B can access n by name (n is inherited from class A) A method in class B can create a local object of itself, which can access n by name (again, n is inherited from class A) Pitfall: A Restriction on Protected Access However, if a method in class B creates an object of class A, it can not access n by name A class knows about its own inherited variables and methods However, it cannot directly access any instance variable or method of an ancestor class unless they are public Therefore, B can access n whenever it is used as an instance variable of B, but B cannot access n when it is used as an instance variable of A This is true if A and B are not in the same package If they were in the same package there would be no problem, because protected access implies package access The end King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS201 Lecture 3 : Inheritance III Slides prepared by Rose Williams, Binghamton University Access Modifiers [review] Tip: "Is a" Versus "Has a" A derived class demonstrates an "is a" relationship between it and its base class For example, an HourlyEmployee "is an" Employee HourlyEmployee is a more complex class compared to the more general Employee class Tip: "Is a" Versus "Has a" Another way to make a more complex class out of a simpler class is through a "has a" relationship This type of relationship, called composition, occurs when a class contains an instance variable of a class type The Employee class contains an instance variable, hireDate, of the class Date, so therefore, an Employee "has a" Date then HourlyEmployee "is an" Employee and "has a" Date Tip: Static Variables Are Inherited Static variables in a base class are inherited by any of its derived classes The modifiers public, private, and protected, and package access have the same meaning for static variables as they do for instance variables Access to a Redefined Base Method Within the definition of a method of a derived class, the base class version of an overridden method of the base class can still be invoked Simply preface the method name with super and a dot : public class HourlyEmployee extends Employee { …… public String toString() { return (super.toString() + "$" + wageRate); } } You Cannot Use Multiple supers It is only valid to use super to invoke a method from a direct parent Repeating super will not invoke a method from some other ancestor class For example, if the Employee class were derived from the class Person, and the HourlyEmployee class were derived form the class Employee , it would not be possible to invoke the toString method of the Person class within a method of the HourlyEmployee class super.super.toString() // ILLEGAL! The Class “Object” In Java, every class is a descendent of the class Object Every class has Object as its ancestor Every object of every class is of type Object, as well as being of the type of its own class If a class is defined that is not explicitly a derived class of another class, it is still automatically a derived class of the class Object The Class “Object” The class Object is in the package java.lang which is always imported automatically Having an Object class enables methods to be written with a parameter of type Object A parameter of type Object can be replaced by an object of any class whatsoever The class Object has some methods that every Java class inherits (e.g. the equals and toString methods) Every object inherits these methods from some ancestor class Either the class Object itself, or a class that itself inherited these methods (ultimately) from the class Object However, these inherited methods should be overridden with definitions more appropriate to a given class The Right Way to Define equals Since the equals method is always inherited from the class Object, methods like the following simply overload it: public boolean equals(Employee otherEmployee) { . . . } public boolean equals(Object otherObject) { . . . } Defined in the current class Inherited from class Object However, the method inherited from class Object should be overridden, not just overloaded. Why ?? .. See next slide The Right Way to Define equals public boolean equals(Object otherObject) { . . . } The parameter otherObject of type Object must be type cast to the given class (e.g., Employee) However, the new method should only do this if otherObject really is an object of that class, and if otherObject is not equal to null Finally, it should compare each of the instance variables of both objects A Better equals Method for the Class Employee To check that the public boolean equals(Object otherObject) object is not null { if(otherObject == null) return false; else if(getClass( ) != otherObject.getClass( )) To check that the return false; object is of the else right class { Employee otherEmployee = (Employee)otherObject; return (name.equals(otherEmployee.name) && hireDate.equals(otherEmployee.hireDate)); } Check the equality } of instance variables one by one Tip: getClass Versus instanceof Many authors suggest using the instanceof operator in the definition of equals The instanceof operator will return true if the object being tested is a member of the class for which it is being tested Instead of the getClass() method However, it will return true if it is a descendent of that class as well It is possible (and especially disturbing), for the equals method to behave inconsistently given this scenario Tip: getClass Versus instanceof Here is an example using the class Employee . . . //excerpt from bad equals method else if(!(OtherObject instanceof Employee)) return false; . . . Now consider the following: Employee e = new Employee("Joe", new Date()); HourlyEmployee h = new HourlyEmployee("Joe", new Date(),8.5, 40); boolean testH = e.equals(h); boolean testE = h.equals(e); e and h are created from different classes. So both testH and testE should be false. However, .. Tip: getClass Versus instanceof testH will be true, because h is an Employee with the same name and hire date as e However, testE will be false, because e is not an HourlyEmployee, and cannot be compared to h Note that this problem would not occur if the getClass() method were used instead, as in the previous equals method example The instanceof Operator The instanceof operator checks if an object is of the type given as its second argument Object instanceof ClassName This will return true if Object is of type ClassName, and otherwise return false Note that this means it will return true if Object is the type of any descendent class of ClassName The getClass() Method Every object inherits the same getClass() method from the Object class An invocation of getClass() on an object returns a representation only of the class that was used with new to create the object The results of any two such invocations can be compared with == or != to determine whether or not they represent the exact same class (object1.getClass() == object2.getClass()) The end King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS201 Lecture 4 : Polymorphism Slides prepared by Rose Williams, Binghamton University Introductory example to Polymorphism Which bill() version ? Which bill() version ? Which bill() versions ? Introduction to Polymorphism There are three main programming mechanisms that constitute object-oriented programming (OOP) Encapsulation Inheritance Polymorphism Polymorphism is the ability to associate many meanings to one method name It does this through a special mechanism known as late binding or dynamic binding Encapsulation Late Binding The process of associating a method definition with a method invocation is called binding If the method definition is associated with its invocation when the code is compiled, that is called early binding If the method definition is associated with its invocation when the method is invoked (at run time), that is called late binding or dynamic binding Java uses late binding for all methods (except private, final, and static methods). Introductory example in more details The Sale class contains two instance variables name: the name of an item (String) price: the price of an item (double) It contains three constructors A no-argument constructor that sets name to "No name yet", and price to 0.0 A two-parameter constructor that takes in a String (for name) and a double (for price) A copy constructor that takes in a Sale object as a parameter The Sale and DiscountSale Classes The Sale class also has a set of accessors (getName, getPrice), mutators (setName, setPrice), overridden equals and toString methods, and a static announcement method The Sale class has a method bill, that determines the bill for a sale, which simply returns the price of the item It has two methods, equalDeals and lessThan, each of which compares two sale objects by comparing their bills and returns a boolean value The Sale and DiscountSale Classes The DiscountSale class inherits the instance variables and methods from the Sale class In addition, it has its own instance variable, discount (a percent of the price), and its own suitable constructor methods, accessor method (getDiscount), mutator method (setDiscount), overriden toString method, and static announcement method The DiscountSale class has its own bill method which computes the bill as a function of the discount and the price The Sale and DiscountSale Classes The Sale class lessThan method Note the bill() method invocations: public boolean lessThan (Sale otherSale) { if (otherSale == null) { System.out.println("Error: null object"); System.exit(0); } return (bill( ) < otherSale.bill( )); } The Sale and DiscountSale Classes The Sale class bill() method: public double bill( ) { return price; } The DiscountSale class bill() method: public double bill( ) { double fraction = discount/100; return (1 - fraction) * getPrice( ); } The Sale and DiscountSale Classes Given the following in a program: . . . Sale simple = new sale("floor mat", 10.00); DiscountSale discount = new DiscountSale("floor mat", 11.00, 10); . . . if (discount.lessThan(simple)) System.out.println("$" + discount.bill() + " < " + "$" + simple.bill() + " because late-binding works!"); . . . Output would be: $9.90 < $10 because late-binding works! The Sale and DiscountSale Classes In the previous example, the boolean expression in the if statement returns true As the output indicates, when the lessThan method in the Sale class is executed, it knows which bill() method to invoke The DiscountSale class bill() method for discount, and the Sale class bill() method for simple Note that when the Sale class was created and compiled, the DiscountSale class and its bill() method did not yet exist These results are made possible by late-binding Pitfall: No Late Binding for Static Methods When the decision of which definition of a method to use is made at compile time, that is called static binding This decision is made based on the type of the variable naming the object Java uses static, not late, binding with private, final, and static methods In the case of private and final methods, late binding would serve no purpose However, in the case of a static method invoked using a calling object, it does make a difference Pitfall: No Late Binding for Static Methods The Sale class announcement() method: public static void announcement( ) { System.out.println("Sale class"); } The DiscountSale class announcement() method: public static void announcement( ) { System.out.println("DiscountSale class"); } Pitfall: No Late Binding for Static Methods In the previous example, the simple (Sale class) and discount (DiscountClass) objects were created Given the following assignment: simple = discount; Now the two variables point to the same object In particular, a Sale class variable names a DiscountClass object Pitfall: No Late Binding for Static Methods Given the invocation: simple.announcement(); The output is: Sale class Note that here, announcement is a static method invoked by a calling object (instead of its class name) Therefore the type of simple is determined by its variable name, not the object that it references Upcasting and Downcasting Upcasting is when an object of a derived class is assigned to a variable of a base class (or any ancestor class) Sale saleVariable; //Base class DiscountSale discountVariable = new DiscountSale("paint", 15,10); //Derived class saleVariable = discountVariable; //Upcasting System.out.println(saleVariable.toString()); Because of late binding, toString above uses the definition given in the DiscountSale class Upcasting and Downcasting Downcasting is when a type cast is performed from a base class to a derived class (or from any ancestor class to any descendent class) Downcasting has to be done very carefully In many cases it doesn't make sense, or is illegal: discountVariable = //will produce (DiscountSale)saleVariable;//run-time error discountVariable = saleVariable //will produce //compiler error There are times, however, when downcasting is necessary, e.g., inside the equals method for a class: Sale otherSale = (Sale)otherObject;//downcasting Be careful with downcasting because Java does not check it at compile time A First Look at the clone Method Every object inherits a method named clone from the class Object The method clone has no parameters It is supposed to return a deep copy of the calling object However, the inherited version of the method was not designed to be used as is Instead, each class is expected to override it with a more appropriate version A First Look at the clone Method If a class has a copy constructor, the clone method for that class can use the copy constructor to create the copy returned by the clone method public Sale clone() { return new Sale(this); } and another example: public DiscountSale clone() { return new DiscountSale(this); } Pitfall: Limitations of Copy Constructors Although the copy constructor and clone method for a class appear to do the same thing, there are cases where only a clone will work For example, given a method badcopy in the class Sale that copies an array of sales If this array of sales contains objects from a derived class of Sale(i.e., DiscountSale), then the copy will be a plain sale, not a true copy b[i] = new Sale(a[i]); //plain Sale object Pitfall: Limitations of Copy Constructors However, if the clone method is used instead of the copy constructor, then (because of late binding) a true copy is made, even from objects of a derived class (e.g., DiscountSale): b[i] = (a[i].clone());//DiscountSale object The reason this works is because the method clone has the same name in all classes, and polymorphism works with method names The copy constructors named Sale and DiscountSale have different names, and polymorphism doesn't work with methods of different names The end King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS201 Lecture 5 : Polymorphism II Slides prepared by Rose Williams, Binghamton University Late Binding with toString Late Binding with toString If an appropriate toString method is defined for a class, then an object of that class can be output using System.out.println Sale aSale = new Sale("tire gauge", 9.95); System.out.println(aSale); Output produced: tire gauge Price and total cost = $9.95 This works because of late binding Late Binding with toString One definition of the method println takes a single argument of type Object: public void println(Object theObject) { System.out.println(theObject.toString()); } In turn, It invokes the version of println that takes a String argument Note that the println method was defined before the Sale class existed Yet, because of late binding, the toString method from the Sale class is used, not the toString from the Object class An Object knows the Definitions of its Methods The type of a class variable determines which method names can be used with the variable However, the object named by the variable determines which definition with the same method name is used Example The end Important to do at home : - read chapter 8 pages 487-489 King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS201 Lecture 6 : Abstract Classes Slides prepared by Rose Williams, Binghamton University Introduction to abstract classes Introduction to abstract classes Suppose the method samePay is added : Is there any problem ? Introduction to Abstract Classes There are several problems with this method: The getPay method is invoked in the samePay method There are getPay methods in each of the derived classes There is no getPay method in the Employee class, nor is there any way to define it reasonably without knowing whether the employee is hourly or salaried Introduction to Abstract Classes The ideal situation would be if there were a way to Postpone the definition of a getPay method until the type of the employee were known (i.e., in the derived classes) Leave some kind of note in the Employee class to indicate that it was accounted for Surprisingly, Java allows this using abstract classes and methods Introduction to Abstract Classes In order to postpone the definition of a method, Java allows an abstract method to be declared An abstract method has a heading, but no method body The body of the method is defined in the derived classes The class that contains an abstract method is called an abstract class Abstract Method An abstract method is like a placeholder for a method that will be fully defined in a descendent class It has a complete method heading, to which has been added the modifier abstract It cannot be private It has no method body, and ends with a semicolon in place of its body public abstract double getPay(); public abstract void doIt(int count); Abstract Class A class that has at least one abstract method is called an abstract class An abstract class must have the modifier abstract included in its class heading: public abstract class Employee { private instanceVariables; . . . public abstract double getPay(); . . . } Correct version Abstract Class An abstract class can have any number of abstract and/or fully defined methods If a derived class of an abstract class adds to or does not define all of the abstract methods, then it is abstract also, and must add abstract to its modifier A class that has no abstract methods is called a concrete class Pitfall: You Cannot Create Instances of an Abstract Class An abstract class can only be used to derive more specialized classes While it may be useful to discuss employees in general, in reality an employee must be a salaried worker or an hourly worker An abstract class constructor cannot be used to create an object of the abstract class However, a derived class constructor will include an invocation of the abstract class constructor in the form of super Tip: An Abstract Class Is a Type Although an object of an abstract class cannot be created, it is perfectly fine to have a parameter of an abstract class type This makes it possible to plug in an object of any of its descendent classes It is also fine to use a variable of an abstract class type, as long is it names objects of its concrete descendent classes only The end King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS201 Lecture 7 : Interfaces Slides prepared by Rose Williams, Binghamton University Single Vs Multiple Inheritance Single Inheritance Base_Class_1 Derived_Class_1 Derived_Class_2 Derived_Class_3 Single Vs Multiple Inheritance Multiple Inheritance : when a class inherits from two or more different base classes : Base_Class_2 Base_Class_1 Derived_Class_1 Derived_Class_2 Derived_Class_3 Multiple inheritance can create significant complications because the implementations that are inherited could be conflicting Difficulty with Multiple Inheritance Person getHours() Student String name Employee getHours() StudentEmployee How many name will be in StudentEmployee? Which version of getHours() will be used in StudentEmployee? Multiple Inheritance in Java Multiple inheritance is not allowed for classes. Multiple inheritance is allowed only for interfaces. An interface can be seen as a class without any implementation. So Interfaces are Java’s way of approximating multiple inheritance. What is an interface? next slide … Interfaces An interface is something like an extreme case of an abstract class Except the word interface is used in place of class An interface specifies a set of methods that any class that implements the interface must have It is a type that can be satisfied by any class that implements the interface The syntax for defining an interface is similar to that of defining a class However, an interface is not a class It contains method headings and constant definitions only It contains no instance variables nor any complete method definitions An interface and all of its method headings should be declared public They cannot be given private, protected, or package access The Ordered Interface Interfaces To implement an interface, a concrete class must do two things: It must include the phrase implements Interface_Name at the start of the class definition (If more than one interface is implemented, each is listed, separated by commas) The class must implement all the method headings listed in the definition(s) of the interface(s) Implementation of an Interface Implementation of an Interface Abstract Classes Implementing Interfaces Abstract classes may implement one or more interfaces Any method headings given in the interface that are not given definitions are made into abstract methods A concrete class must give definitions for all the method headings given in the abstract class and the interface An Abstract Class Implementing an Interface Derived Interfaces Like classes, an interface may be derived from a base interface This is called extending the interface The derived interface must include the phrase extends BaseInterfaceName A concrete class that implements a derived interface must have definitions for any methods in the derived interface as well as any methods in the base interface Extending an Interface Defined Constants in Interfaces An interface can contain defined constants in addition to or instead of method headings Any variables defined in an interface must be public, static, and final Because this is understood, Java allows these modifiers to be omitted Any class that implements the interface has access to these defined constants Pitfall: Inconsistent Interfaces When a class implements two interfaces: One type of inconsistency will occur if the interfaces have constants with the same name, but with different values In this case, the class will be compiled correctly but when any of the constants is accessed via a reference of the class type, a compilation error will occur. If the reference is up-casted to one of the interfaces, the constant from that interface will be used without any error Another type of inconsistency will occur if the interfaces contain methods with the same name but different return types This is an error, the class will not compile The end King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS201 Lecture 8 : Inner-classes Slides prepared by Rose Williams, Binghamton University Introductory Example Inner class inside Person Inner Classes So far, every class should be defined in a separate file having the same name as the class. Inner (or nested) classes are classes defined within other classes The class that includes the inner class is called the outer class There are four categories of inner classes in Java: 1. Inner classes (non-static) 2. Static inner classes 3. Local classes (defined inside a block of Java code) 4. Anonymous classes (defined inside a block of Java code) Inner Classes An inner class definition is a member of the outer class in the same way that the instance variables and methods of the outer class are members An inner class is local to the outer class definition The name of an inner class may be reused for something else outside the outer class definition If the inner class is private, then the inner class cannot be accessed by name outside the definition of the outer class Why Inner Classes? There are two main advantages to inner classes They can make the outer class more self-contained since they are defined inside a class Both of their methods have access to each other's private methods and instance variables Using an inner class as a helping class is one of the most useful applications of inner classes If used as a helping class, an inner class should be marked private Tip: Inner and Outer Classes Have Access to Each Other's Private Members Within the definition of a method of an inner class: It is legal to reference a private instance variable of the outer class It is legal to invoke a private method of the outer class Within the definition of a method of the outer class It is legal to reference a private instance variable of the inner class on an object of the inner class It is legal to invoke a (nonstatic) method of the inner class as long as an object of the inner class is used as a calling object Within the definition of the inner or outer classes, the modifiers public and private are equivalent Class with an Inner Class Class with an Inner Class Class with an Inner Class The .class File for an Inner Class Compiling any class in Java produces a .class file named ClassName.class Compiling a class with one (or more) inner classes causes both (or more) classes to be compiled, and produces two (or more) .class files : ClassName.class ClassName$InnerClassName.class Static Inner Classes A normal inner class has a connection between its objects and the outer class object that created the inner class object There are certain situations, however, when an inner class must be static This allows an inner class definition to reference an instance variable, or invoke a method of the outer class If an object of the inner class is created within a static method of the outer class If the inner class must have static members Since a static inner class has no connection to an object of the outer class, within an inner class method Instance variables of the outer class cannot be referenced Nonstatic methods of the outer class cannot be invoked Public Inner Classes If an inner class is marked public, then it can be used outside of the outer class An inner class must be created using an object of the outer class : Person p1 = new Person(…); Person.ArabicDate ad1 = p1.new ArabicDate(…); Note that the prefix p1. must come before new Referring to a Method of the Outer Class If a method is invoked in an inner class If the inner class has no such method, then it is assumed to be an invocation of the method of that name in the outer class If both the inner and outer class have a method with the same name, then it is assumed to be an invocation of the method in the inner class If both the inner and outer class have a method with the same name, and the intent is to invoke the method in the outer class, then the following invocation must be used: OuterClassName.this.methodName() using this inside an inner class refers to the object of the inner class Issues about Inner classes Nesting Inner Classes : It is legal to nest inner classes within inner classes The rules are the same as before, but the names get longer Given class A, which has public inner class B, which has public inner class C, then the following is valid: A aObject = new A(); A.B bObject = aObject.new B(); A.B.C cObject = bObject.new C(); Inner Classes and inheritance : Given an OuterClass that has an InnerClass Any DerivedClass of OuterClass will automatically have InnerClass as an inner class In this case, the DerivedClass cannot override the InnerClass Local Classes A local class is defined within a block of Java code. Local classes are completely hidden in their containing block. When a class name is used only within a block it can be defined locally. A local class can access instance variables of the outer class and only the final local variables of the enclosing block. Local Classes: Example Anonymous Classes It is a local class without a name If only one object has to be created from a class, and there is no need to name the class, then an anonymous class definition can be used The class definition is embedded inside the expression with the new operator Anonymous class has no constructors It is either derived from a class, or implements an interface. Like: AnInterface i = new AnInterface ( ) { // methods defs. … } ASuperclass c = new ASuperclass(…) { // methods defs. … } Anonymous Classes Anonymous Classes Anonymous Classes The end King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS201 Lecture 9 : Exception Handling Slides prepared by Rose Williams, Binghamton University Introduction to Exception Handling Introduction to Exception Handling Throw instruction try block catch block Introduction to Exception Handling An exception is an indication of a problem that occurs during a program’s execution. Exception handling enables programmers to create applications that can resolve (or handle) exceptions. Problems during execution Error-handling code Exception handling - Intermix program logic with error-handling logic - Allows to remove error-handling code from the main line of the program - Makes the program difficult to read, modify, maintain, and debug - Improves program clarity and enhances modifiability When no exceptions occur, exception-handling code incurs little or no performance penalties. Exception handling should be used only for problems that occur infrequently try-throw-catch Mechanism throw new ExceptionClassName(PossiblySomeArguments); When an exception is thrown, the execution of the surrounding try block is stopped Normally, the flow of control is transferred to another portion of code known as the catch block The value thrown is the argument to the throw operator, and is always an object of some exception class The execution of a throw statement is called throwing an exception try-throw-catch Mechanism A throw statement is similar to a method call: throw new ExceptionClassName(SomeString); In the above example, the object of class ExceptionClassName is created using a string as its argument This object, which is an argument to the throw operator, is the exception object thrown Instead of calling a method, a throw statement calls a catch block Exception Classes There are two kinds of exceptions in Java Predefined exception classes in the Java libraries (API) New exception classes can be defined like any other class Exception Classes from Standard Packages Numerous predefined exception classes are included in the standard packages that come with Java For example: IOException NoSuchMethodException FileNotFoundException Many exception classes must be imported in order to use them import java.io.IOException; All predefined exception classes have the following properties: There is a constructor that takes a single argument of type String The class has an accessor method getMessage that can recover the string given as an argument to the constructor when the exception object was created. Exception Classes from Standard Packages The predefined exception class Exception is the root class for all exceptions Every exception class is a descendent class of the class Exception Although the Exception class can be used directly in a class or program, it is most often used to define a derived class The class Exception is in the java.lang package, and so requires no import statement Using the getMessage Method Every exception has a String instance variable that contains some message This string typically identifies the reason for the exception The method call e.getMessage() returns this string . . . // method code try { . . . throw new Exception(StringArgument); . . . } catch(Exception e) { String message = e.getMessage(); System.out.println(message); System.exit(0); } . . . Defining Exception Classes A throw statement can throw an exception object of any exception class Instead of using a predefined class, exception classes can be programmer-defined These can be tailored to carry the precise kinds of information needed in the catch block A different type of exception can be defined to identify each different exceptional situation Every exception class to be defined must be a derived class of some already defined exception class A Programmer-Defined Exception Class A Programmer-Defined Exception Class Programmer-Defined Exception Class Guidelines Exception classes may be programmer-defined, but every such class must be a derived class of an already existing exception class The class Exception can be used as the base class, unless another exception class would be more suitable At least two constructors should be defined, sometimes more The exception class should allow for the fact that the method getMessage is inherited Preserve getMessage For all predefined exception classes, getMessage returns the string that is passed to its constructor as an argument Or it will return a default string if no argument is used with the constructor This behavior must be preserved in all programmer-defined exception class A constructor must be included having a string parameter whose body begins with a call to super The call to super must use the parameter as its argument A no-argument constructor must also be included whose body begins with a call to super This call to super must use a default string as its argument Multiple catch Blocks A try block can potentially throw any number of exception values, and they can be of differing types In any one execution of a try block, at most one exception can be thrown (since a throw statement ends the execution of the try block) However, different types of exception values can be thrown on different executions of the try block Different types of exceptions can be caught by placing more than one catch block after a try block Any number of catch blocks can be included, but they must be placed in the correct order Multiple catch Blocks Catch the More Specific Exception First When catching multiple exceptions, the order of the catch blocks is important When an exception is thrown in a try block, the catch blocks are examined in order The first one that matches the type of the exception thrown is the one that is executed catch { . . catch { . . Because a NegativeNumberException is a type of Exception, all NegativeNumberExceptions will be caught by the first catch block before ever reaching the second block (Exception e) . } (NegativeNumberException e) . } The catch block for NegativeNumberException will never be used! For the correct ordering, simply reverse the two blocks Throwing an Exception in a Method Throwing an Exception in a Method Sometimes it makes sense to throw an exception in a method, but not catch it in the same method Some programs that use a method should just end if an exception is thrown, and other programs should do something else In such cases, the program using the method should enclose the method invocation in a try block, and catch the exception in a catch block that follows In this case, the method itself would not include try and catch blocks However, it would have to include a throws clause Declaring Exceptions in a throws Clause If a method can throw more than one type of exception, then separate the exception types by commas public void aMethod() throws AnException, AnotherException If a method throws an exception and does not catch it, then the method invocation ends immediately The Catch or Declare Rule Most ordinary exceptions that might be thrown within a method must be accounted for in one of two ways: 1. 2. The code that can throw an exception is placed within a try block, and the possible exception is caught in a catch block within the same method The possible exception can be declared at the start of the method definition by placing the exception class name in a throws clause Checked and Unchecked Exceptions Exceptions that are subject to the catch or declare rule are called checked exceptions The compiler checks to see if they are accounted for with either a catch block or a throws clause The classes Throwable, Exception, and all descendants of the class Exception are checked exceptions All other exceptions are unchecked exceptions The class Error and all its descendant classes are called error classes Error classes are not subject to the Catch or Declare Rule Hierarchy of Throwable Objects The end King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS201 Lecture 10 : Introduction to Java Virtual Machine Slides prepared by Rose Williams, Binghamton University Outline Java Language, Java Virtual Machine and Java Platform Organization of Java Virtual Machine Garbage Collection Interpreter and Just-In-Time Compiler Why Java ? Currently, Java is the most popular language in the world ! Classical compilation model Hello.c gcc for Win Hello Windows X86 gcc for Mac Hello Mac PowerPC gcc for Linux Hello Hello Linux X86 Java Compilation Model Hello.java javac Hello.class Hello Windows X86 Hello Mac PowerPC Hello Hello Linux X86 The Big Picture A.java B.java C.java Java Language Specification Java Compiler A.class B.class C.class Java Virtual Machine Java Virtual Machine Specification Java Platforms (1) A Java Platform consists Java Virtual Machine CPU A set of standard classes API JVM in all platforms must satisfy JVM spec. Standard classes can be tailored according to the resource constraints Three levels of Java platforms: J2EE, J2SE and J2ME Java Platforms (2) From KVM White Paper (Sun Microsystem) What Is in the JVM Spec? Bytecodes – the instruction set for Java Virtual Machine Class File Format – The platform independent representation of Java binary code Verification Rules – the algorithm for identifying programs that cannot compromise the integrity of the JVM Organization of JVM Class Area Class Information Constant Pool Heap Stack Native Stack Method Area Internet *.class File System *.class Class Loader PC, FP, SP Registers Execution Engine Native Interface Native Methods Class Loader Loading: finding and importing the binary data for a class Linking: 1. 2. • • • 3. Verification: ensuring the correctness of the imported type Preparation: allocating memory for class variables and initializing the memory to default values Resolution: transforming symbolic references from the type into direct references. Initialization: invoking Java code that initializes class variables to their proper starting values Class Area Class Information Internal representation of Java classes Information about the superclass and implemented interfaces Information about the fields and methods Constant Pool Method Area Contains the bytecodes of the methods of the loaded classes Organization of JVM Class Area Class Information Constant Pool Heap Stack Native Stack Method Area Internet *.class File System *.class Class Loader PC, FP, SP Registers Execution Engine Native Interface Native Methods Stack The Java stack is composed of frames JVM has no registers; it uses the operand stack for storage of intermediate data values A frame contains the state of one Java method invocation Logically, a frame has two parts: local variable array and operand stack to keep the JVM's instruction set compact to facilitate implementation on architectures with limited number of general purpose registers Each Java thread has its own stack and cannot access the stack of other threads Stack Frame public class A { ... ... void f(int x) { int i; for(i=0; i<x; i++) { ... ... } ... ... } SP InterMediate Data Values Operand Stack i x Local Variable Array Caller’s SP Caller’s FP FP Return PC Example a = (b + c) 2 Bytecode iload_2 (load variable b) iload_3 (load variable c) iadd (addition) iconst_2 (load constant value 2) imul (multiplication) istore_1 (save the value of a) Stack – Each Thread Has its own Stack Heap Thread 1 Thread 2 Thread 3 Frame Frame Frame Frame Frame Frame Frame Frame Stack Organization of JVM Class Area Class Information Constant Pool Heap Stack Native Stack Method Area Internet *.class File System *.class Class Loader PC, FP, SP Registers Execution Engine Native Interface Native Methods Heap All Java objects are allocated in the heap Java applications cannot explicitly free an object The Garbage Collector is invoked from time to time automatically to reclaim the objects that are no longer needed by the application The heap is shared by all Java threads Java Objects in the Heap clazz Fields 1 Fields 2 class Object class A …… Fields n clazz class B …… Class Area clazz …… Heap Garbage Collector Roots: internally defined by the JVM implementation Live Objects: reachable from the roots Garbage (Dead Objects): not reachable from the roots, not accessible to the application root A C B E D G F Mark / Sweep / Compaction root root A B C D E F G A B C D E F G Before GC Live After Mark Garbage root root B B E G E G After Sweep After Compact Unknown Free Organization of JVM Class Area Class Information Constant Pool Heap Stack Native Stack Method Area Internet *.class File System *.class Class Loader PC, FP, SP Registers Execution Engine Native Interface Native Methods Execution Engine Executes Java bytecodes either using interpreter or Just-In-Time compiler Registers: PC: Program Counter FP: Frame Pointer SP: Operand Stack Top Pointer Interpreter vs Just-In-Time Compiler Bytecode Bytecode Interpreter CPU Interpretation Native Code JIT Compiler CPU JIT Compilation Interpretation a = (b + c) 2 Bytecode iload_2 (load variable b) iload_3 (load variable c) iadd (addition) iconst_2 (load constant value 2) imul (multiplication) istore_1 (save the value of a) Bytecode Interpreter (1) while(program not end ) { fetch next bytecode => b switch(b) { case ILOAD: load an integer from the local variable array and push on top of current operand stack; case ISTORE: pop an integer from the top of current operand stack and store it into the local variable array; case ALOAD: ... ... } // end of switch } // end of while Bytecode interpreter (2) Advantage Ease to implement Does not need extra memory to store compiled code Disadvantage Very Slow: 10 ~ 100 times slower than execution of native code Just-In-Time Compiler Dynamically compiles bytecode into native code at runtime, usually in method granularity Execution of native code is much faster than interpretation of bytecode Compilation is time consuming and may slow down the application Tradeoffs between execution time and compilation time Adaptive Compiler Observation: less than 20% of the methods account for more than 80% of execution time Methods contains loop with large number of iteration; Methods that are frequently invoked Idea 1: only compile the methods where the application spends a lot of time Idea 2: perform advanced compiler optimization for the hottest methods, simple or no compiler optimization for less hot methods How Adaptive Compiler Works Set three thresholds T1, T2 (T1<T2) Each method has a counter that is initialized to 0. Whenever the method is invoked, increase its counter by 1 The methods with counter lower than T1 are executed using interpreter When a method’s counter reaches T1, compile this method with simple optimizations When a method’s counter reaches T2, recompile this method with advanced optimizations The end King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS201 Lecture 11 : Gentle Introduction to Computer Graphics Based Slides on: prepared by Rose Williams, Binghamton University David Brogan’s “Introduction to Computer Graphics” Course Slides, University of Virginia Jack van Wijk’s “Computer Graphics” Course Slides, University of Eindhoven. Outline Graphics Applications What is Computer Graphics Representations in Graphics Supporting Disciplines Graphics Applications Entertainment: Cinema A Bug’s Life (Pixar) Pixar: Monster’s Inc. Graphics Applications Medical Visualization The Visible Human Project MIT: Image-Guided Surgery Project Graphics Applications Scientific Visualization Graphics Applications Computer Aided Design (CAD) Graphics Applications Training Designing Effective Step-By-Step Assembly Instructions (Maneesh Agrawala et. al) Graphics Applications Games GT Racer 3 Polyphony Digital: Gran Turismo 3, A Spec Graphics Applications Games Circus Atari (Atari) Graphics Applications The major application that we will be dealing with extensively in the next coming lectures is that of developing graphical user interfaces Windows Menus Buttons Textboxes ... What is Computer Graphics? Computer graphics: generating 2D images of a 3D world represented in a computer. Main tasks: modeling: (shape) creating and representing the geometry of objects in the 3D world rendering: (light, perspective) generating 2D images of the objects animation: (movement) describing how objects change in time Representations in graphics Vector Graphics Image is represented by continuous geometric objects: lines, curves, etc. Raster Graphics Image is represented as a rectangular grid of colored pixels PIXEL = PIcture ELement Raster graphics Generic Image processing techniques Geometric Transformation: loss of information Relatively high processing time in terms of the number of pixels Realistic images, textures, ... Examples: Paint, PhotoShop, ... Sample Image Processing Techniques Edge Detection Image Denoising Vector graphics Graphics objects: geometry + color Relatively low processing time in terms of the number of graphic objects Geometric transformation possible without loss of information (zoom, rotate, …) Examples: PowerPoint, CorelDraw, SVG, ... Scalable Vector Graphics (SVG) <?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg width="12cm" height="4cm" viewBox="0 0 1200 400" xmlns="http://www.w3.org/2000/svg" version="1.1"> <desc>Example polygon01 - star and hexagon</desc> <!-- Show outline of canvas using 'rect' element --> <rect x="1" y="1" width="1198" height="398" fill="none" stroke="blue" stroke-width="2" /> <polygon fill="red" stroke="blue" stroke-width="10" points="350,75 379,161 469,161 397,215 423,301 350,250 277,301 303,215 231,161 321,161" /> <polygon fill="lime" stroke="blue" stroke-width="10" points="850,75 958,137.5 958,262.5 850,325 742,262.6 742,137.5" /> </svg> In Summary Image Analysis Math. Model (pattern recognition) Image Image Synthesis (Rendering) Modeling Image processing Supporting Disciplines Computer science (algorithms, data structures, software engineering, …) Mathematics (geometry, numerical, …) Physics (Optics, mechanics, …) Psychology (Colour, perception) Art and design The end King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS201 Lecture 12 : Gentle Introduction to Computer Graphics II Based Slides on: prepared by Rose Williams, Binghamton University David Brogan’s “Introduction to Computer Graphics” Course Slides, University of Virginia Jack van Wijk’s “Computer Graphics” Course Slides, University of Eindhoven. Outline Introduction to 2D Modeling Transformations Matrix Representations Linear Transformations Introduction to Modeling Transformations Specify transformations for objects Allows definitions of objects in own coordinate systems Allows use of object definition multiple times in a scene 2D Modeling Transformations Modeling Coordinates y Scale Translate x Scale Rotate Translate World Coordinates Scaling Scaling a coordinate means multiplying each of its components by a scalar Uniform scaling means this scalar is the same for all components: 2 Scaling Non-uniform scaling: different scalars per component: X 2, Y 0.5 How can we represent this in matrix form? Scaling Scaling operation: Or, in matrix form: x' ax y ' by x ' a 0 x y ' 0 b y scaling matrix 2-D Rotation (x’, y’) (x, y) x’ = x cos() - y sin() y’ = x sin() + y cos() 2-D Rotation This is easy to capture in matrix form: x' cos sin x y ' sin cos y Even though sin() and cos() are nonlinear functions of , x’ is a linear combination of x and y y’ is a linear combination of x and y 2-D Translation (x’, y’) ty (x, y) tx x’ = x + tx y’ = y + ty The end King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS201 Lecture 13 : Swing I Slides prepared by Rose Williams, Binghamton University Swing I Reading: Pages 920 – 933 Outline Events and Listeners A simple window Buttons Action Listeners and Action Events Introductory Example Introduction to Swing The Java AWT (Abstract Window Toolkit) package is the original Java package for doing GUIs A GUI (graphical user interface) is a windowing system that interacts with the user The Swing package is an improved version of the AWT However, it does not completely replace the AWT Some AWT classes are replaced by Swing classes, but other AWT classes are needed when using Swing Swing GUIs are designed using a form of objectoriented programming known as event-driven programming Events Event-driven programming is a programming style that uses a signal-and-response approach to programming An event is an object that acts as a signal to another object know as a listener The sending of an event is called firing the event The object that fires the event is often a GUI component, such as a button that has been clicked Listeners A listener object performs some action in response to the event A given component may have any number of listeners Each listener may respond to a different kind of event, or multiple listeners might may respond to the same events Event Handlers A listener object has methods that specify what will happen when events of various kinds are received by it These methods are called event handlers The programmer using the listener object will define or redefine these event-handler methods Event Firing and an Event Listener Example Event-Driven Programming Event-driven programming is very different from most programming seen up until now So far, programs have consisted of a list of statements executed in order When that order changed, whether or not to perform certain actions (such as repeat statements in a loop, branch to another statement, or invoke a method) was controlled by the logic of the program In event-driven programming, objects are created that can fire events, and listener objects are created that can react to the events The program itself no longer determines the order in which things can happen Instead, the events determine the order A Simple Window A simple window can consist of an object of the JFrame class A JFrame object includes a border and the usual three buttons for minimizing, changing the size of, and closing the window The JFrame class is found in the javax.swing package JFrame firstWindow = new JFrame(); A JFrame can have components added to it, such as buttons, menus, and text labels These components can be programmed for action firstWindow.add(endButton); It can be made visible using the setVisible method firstWindow.setVisible(true); A First Swing Demonstration FirstSwingDemo.java EndingListener.java A First Swing Demonstration (Part 4 of 4) Some Methods in the Class JFrame (Part 1 of 3) Some Methods in the Class JFrame (Part 1 of 3) Some Methods in the Class JFrame (Part 3 of 3) Pixels and the Relationship between Resolution and Size A pixel is the smallest unit of space on a screen A high-resolution screen of fixed size has many pixels Therefore, each one is very small A low-resolution screen of fixed size has fewer pixels Both the size and position of Swing objects are measured in pixels The more pixels on a screen, the greater the screen resolution Therefore, each one is much larger Therefore, a two-pixel figure on a low-resolution screen will look larger than a two-pixel figure on a high-resolution screen Pitfall: Forgetting to Program the Close-Window Button The following lines from the FirstSwingDemo program ensure that when the user clicks the close-window button, nothing happens firstWindow.setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE); If this were not set, the default action would be JFrame.HIDE_ON_CLOSE This would make the window invisible and inaccessible, but would not end the program Therefore, given this scenario, there would be no way to click the "Click to end program" button Note that the close-window and other two accompanying buttons are part of the JFrame object, and not separate buttons Buttons A button object is created from the class JButton and can be added to a JFrame The argument to the JButton constructor is the string that appears on the button when it is displayed JButton endButton = new JButton("Click to end program."); firstWindow.add(endButton); Action Listeners and Action Events Clicking a button fires an event The event object is "sent" to another object called a listener This means that a method in the listener object is invoked automatically Furthermore, it is invoked with the event object as its argument In order to set up this relationship, a GUI program must do two things 1. 2. It must specify, for each button, what objects are its listeners, i.e., it must register the listeners It must define the methods that will be invoked automatically when the event is sent to the listener Action Listeners and Action Events EndingListener buttonEar = new EndingListener()); endButton.addActionListener(buttonEar); Above, a listener object named buttonEar is created and registered as a listener for the button named endButton Note that a button fires events known as action events, which are handled by listeners known as action listeners Action Listeners and Action Events Different kinds of components require different kinds of listener classes to handle the events they fire An action listener is an object whose class implements the ActionListener interface The ActionListener interface has one method heading that must be implemented public void actionPerformed(ActionEvent e) Action Listeners and Action Events public void actionPerformed(ActionEvent e) { System.exit(0); } The EndingListener class defines its actionPerformed method as above When the user clicks the endButton, an action event is sent to the action listener for that button The EndingListener object buttonEar is the action listener for endButton The action listener buttonEar receives the action event as the parameter e to its actionPerformed method, which is automatically invoked Note that e must be received, even if it is not used Pitfall: Changing the Heading for actionPerformed When the actionPerformed method is implemented in an action listener, its header must be the one specified in the ActionListener interface It is already determined, and may not be changed Not even a throws clause may be added public void actionPerformed(ActionEvent e) The only thing that can be changed is the name of the parameter, since it is just a placeholder Whether it is called e or something else does not matter, as long as it is used consistently within the body of the method Tip: Ending a Swing Program GUI programs are often based on a kind of infinite loop The windowing system normally stays on the screen until the user indicates that it should go away If the user never asks the windowing system to go away, it will never go away In order to end a GUI program, System.exit must be used when the user asks to end the program It must be explicitly invoked, or included in some library code that is executed Otherwise, a Swing program will not end after it has executed all the code in the program The end King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS201 Lecture 14 : Swing II Slides prepared by Rose Williams, Binghamton University Swing I: (2/4) Reading: Pages 934 – 952 Outline A Better Version of Our First Swing GUI Labels Colors Layout Managers: Border, Flow & Grid The Normal Way to Define a JFrame A Better Version of Our First Swing GUI A better version of FirstWindow makes it a derived class of the class JFrame The constructor in the new FirstWindow class starts by calling the constructor for the parent class using super(); This is the normal way to define a windowing interface This ensures that any initialization that is normally done for all objects of type JFrame will be done Almost all initialization for the window FirstWindow is placed in the constructor for the class Note that this time, an anonymous object is used as the action listener for the endButton Old and New Versions The normal way to define a JFrame New Old Labels A label is an object of the class JLabel Text can be added to a JFrame using a label The text for the label is given as an argument when the JLabel is created The label can then be added to a JFrame JLabel greeting = new JLabel("Hello"); add(greeting); Color In Java, a color is an object of the class Color The class Color is found in the java.awt package There are constants in the Color class that represent a number of basic colors A JFrame can not be colored directly Instead, a program must color something called the content pane of the JFrame Since the content pane is the "inside" of a JFrame, coloring the content pane has the effect of coloring the inside of the JFrame Therefore, the background color of a JFrame can be set using the following code: getContentPane().setBackground(Color); The Color Constants A JFrame with Color ColoredWindow.java DemoColoredWindow.java A JFrame with Color Containers and Layout Managers Multiple components can be added to the content pane of a JFrame using the add method However, the add method does not specify how these components are to be arranged To describe how multiple components are to be arranged, a layout manager is used There are a number of layout manager classes such as BorderLayout, FlowLayout, and GridLayout If a layout manager is not specified, a default layout manager is used Border Layout Managers A BorderLayout manager places the components that are added to a JFrame object into five regions These regions are: BorderLayout.NORTH, BorderLayout.SOUTH, BorderLayout.EAST, BorderLayout.WEST, and BorderLayout.Center A BorderLayout manager is added to a JFrame using the setLayout method For example: setLayout(new BorderLayout()); Border Layout Manager (Example) Border Layout Managers The previous diagram shows the arrangement of the five border layout regions Note: None of the lines in the diagram are normally visible When using a BorderLayout manager, the location of the component being added is given as a second argument to the add method add(label1, BorderLayout.NORTH); Components can be added in any order since their location is specified Flow Layout Managers The FlowLayout manager is the simplest layout manager setLayout(new FlowLayout()); It arranges components one after the other, going from left to right Components are arranged in the order in which they are added Since a location is not specified, the add method has only one argument when using the FlowLayoutManager add.(label1); Grid Layout Managers A GridLayout manager arranges components in a two-dimensional grid with some number of rows and columns setLayout(new GridLayout(rows, columns)); Each entry is the same size The two numbers given as arguments specify the number of rows and columns Each component is stretched so that it completely fills its grid position Note: None of the lines in the diagram are normally visible Grid Layout Managers When using the GridLayout class, the method add has only one argument add(label1); Items are placed in the grid from left to right The top row is filled first, then the second, and so forth Grid positions may not be skipped Note the use of a main method in the GUI class itself in the following example This is often a convenient way of demonstrating a class Grid Layout Managers Some Layout Managers The end King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS201 Lecture 15 : Swing III Slides prepared by Rose Williams, Binghamton University Swing III: Reading: Pages 953 – 968 Outline Panels Container Class Menu Bars, Menus & Menu Items Nested Menus Panels A GUI is often organized in a hierarchical fashion, with containers called panels inside other containers A panel is an object of the JPanel class that serves as a simple container It is used to group smaller objects into a larger component (the panel) One of the main functions of a JPanel object is to subdivide a JFrame or other container Panels Both a JFrame and each panel in a JFrame can use different layout managers Additional panels can be added to each panel, and each panel can have its own layout manager This enables almost any kind of overall layout to be used in a GUI setLayout(new BorderLayout()); JPanel somePanel = new JPanel(); somePanel.setLayout(new FlowLayout()); Note in the following example that panel and button objects are given color using the setBackground method without invoking getContentPane The getContentPane method is only used when adding color to a JFrame Using Panels (Part 1 of 4) Using Panels (Part 2 of 4) Using Panels (Part 3 of 4) Using Panels (Part 4 of 4) Using Panels The Container Class Any class that is a descendent class of the class Container is considered to be a container class The Container class is found in the java.awt package, not in the Swing library Any object that belongs to a class derived from the Container class (or its descendents) can have components added to it The classes JFrame and JPanel are descendent classes of the class Container Therefore they and any of their descendents can serve as a container The JComponent Class Any descendent class of the class JComponent is called a component class Any JComponent object or component can be added to any container class object Because it is derived from the class Container, a JComponent can also be added to another JComponent Objects in a Typical GUI Almost every GUI built using Swing container classes will be made up of three kinds of objects: 1. 2. 3. The container itself, probably a panel or window-like object The components added to the container such as labels, buttons, and panels A layout manager to position the components inside the container Hierarchy of Swing and AWT Classes Code a GUI's Look and Actions Separately The task of designing a Swing GUI can be divided into two main subtasks: 1. 2. Designing and coding the appearance of the GUI on the screen Designing and coding the actions performed in response to user actions In particular, it is useful to implement the actionPerformed method as a stub, until the GUI looks the way it should public void actionPerformed(ActionEvent e) {} This philosophy is at the heart of the technique used by the Model-View-Controller pattern Menu Bars, Menus, and Menu Items A menu is an object of the class JMenu A choice on a menu is called a menu item, and is an object of the class JMenuItem A menu can contain any number of menu items A menu item is identified by the string that labels it, and is displayed in the order to which it was added to the menu The add method is used to add a menu item to a menu in the same way that a component is added to a container object Menu Bars, Menus, and Menu Items The following creates a new menu, and then adds a menu item to it JMenu diner = new JMenu("Daily Specials"); JMenuItem lunch = new JMenuItem("Lunch Specials"); lunch.addActionListener(this); diner.add(lunch); Note that the this parameter has been registered as an action listener for the menu item Nested Menus The class JMenu is a descendent of the JMenuItem class Every JMenu can be a menu item in another menu Therefore, menus can be nested Menus can be added to other menus in the same way as menu items Menu Bars and JFrame A menu bar is a container for menus, typically placed near the top of a windowing interface The add method is used to add a menu to a menu bar in the same way that menu items are added to a menu JMenuBar bar = new JMenuBar(); bar.add(diner); The menu bar can be added to a JFrame in two different ways 1. Using the setJMenuBar method setJMenuBar(bar); 2. Using the add method – which can be used to add a menu bar to a JFrame or any other container Menu Example Menu Example Menu Example (Part 1 of 4) Menu Example (Part 2 of 4) Menu Example (Part 3 of 4) Menu Example (Part 4 of 4) Text field and Text area Text field and Text area TextField Example TextField Example TextField Example TextField Example Other Components JCheckBox (Also JCheckBoxMenuItem) JRadioButton (Also JRadioButtonMenuItem) Other Components JComboBox JTree Other Components JList JPasswordField JSlider Reference (Important) The Swing Java tutorial examples : http://java.sun.com/docs/books/tutorial/uiswing/examples/components/index.html The end King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS201 Lecture 16 : Swing VI Graphics Slides prepared by Rose Williams, Binghamton University The Graphics Class Coordinate System for Graphics Objects When drawing objects on the screen, Java uses a coordinate system where the origin point (0,0) is at the upper-left corner of the screen area used for drawing The x-coordinate (horizontal) is positive and increasing to the right The y- coordinate(vertical) is positive and increasing down All coordinates are normally positive Units and sizes are in pixels The area used for drawing is typically a JFrame or JPanel Coordinate System for Graphics Objects The point (x,y) is located x pixels in from the left edge of the screen, and down y pixels from the top of the screen When placing a rectangle on the screen, the location of its upper-left corner is specified When placing a figure other than a rectangle on the screen, Java encloses the figure in an imaginary rectangle, called a bounding box, and positions the upper-left corner of this rectangle Screen Coordinate System The Method paint and the Class Graphics Almost all Swing and Swing-related components and containers have a method called paint The method paint draws the component or container on the screen It is already defined, and is called automatically when the figure is displayed on the screen However, it must be redefined in order to draw geometric figures like circles and boxes When redefined, always include the following: super.paint(g); The Method paint and the Class Graphics Every container and component that can be drawn on the screen has an associated Graphics object The Graphics class is an abstract class found in the java.awt package This object has data specifying what area of the screen the component or container covers The Graphics object for a JFrame specifies that drawing takes place inside the borders of the JFrame object The Method paint and the Class Graphics The object g of the class Graphics can be used as the calling object for a drawing method The drawing will then take place inside the area of the screen specified by g The method paint has a parameter g of type Graphics When the paint method is invoked, g is replaced by the Graphics object associated with the JFrame Therefore, the figures are drawn inside the JFrame Drawing a Very Simple Face (part 1 of 5) Drawing a Very Simple Face (part 2 of 5) Drawing a Very Simple Face (part 3 of 5) Drawing a Very Simple Face (part 4 of 5) Drawing a Very Simple Face (part 5 of 5) Some Methods in the Class Graphics Some Methods in the Class Graphics Some Methods in the Class Graphics Some Methods in the Class Graphics Drawing Ovals An oval is drawn by the method drawOval The arguments specify the location, width, and height of the smallest rectangle that can enclose the oval g.drawOval(100, 50, 300, 200); A circle is a special case of an oval in which the width and height of the rectangle are equal g.drawOval(X_FACE, Y_FACE, FACE_DIAMETER, FACE_DIAMETER); Drawing a Happy Face (Part 1 of 5) Drawing a Happy Face Drawing a Happy Face Drawing a Happy Face Drawing a Happy Face (Part 5 of 5) Drawing Arcs Arcs are described by giving an oval, and then specifying a portion of it to be used for the arc The following statement draws the smile on the happy face: g.drawArc(X_MOUTH, Y_MOUTH, MOUTH_WIDTH, MOUTH_HEIGHT, MOUTH_START_ANGLE, MOUTH_ARC_SWEEP); The arguments MOUTH_WIDTH and MOUTH_HEIGHT determine the size of the bounding box, while the arguments X_MOUTH and Y_MOUTH determine its location The last two arguments specify the portion made visible Specifying an Arc (Part 1 of 2) Specifying an Arc (Part 2 of 2) Rounded Rectangles A rounded rectangle is a rectangle whose corners have been replaced by arcs so that the corners are rounded g.drawRoundRect(x, y, width, height, arcWidth, arcHeight) The arguments x, y, width, and height determine a regular rectangle in the usual way The last two arguments arcWidth, and arcHeight, specify the arcs that will be used for the corners Each corner is replaced with an quarter of an oval that is arcWidth pixels wide and arcHeight pixels high When arcWidth and arcHeight are equal, the corners will be arcs of circles A Rounded Rectangle paintComponent for Panels A JPanel is a JComponent, but a JFrame is a Component, not a JComponent Therefore, they use different methods to paint the screen Figures can be drawn on a JPanel, and the JPanel can be placed in a JFrame When defining a JPanel class in this way, the paintComponent method is used instead of the paint method Otherwise the details are the same as those for a JFrame paintComponent for Panels paintComponent for Panels paintComponent for Panels Action Drawings and repaint The repaint method should be invoked when the graphics content of a window is changed The repaint method takes care of some overhead, and then invokes the method paint, which redraws the screen Although the repaint method must be explicitly invoked, it is already defined The paint method, in contrast, must often be defined, but is not explicitly invoked An Action Drawing (Part 1 of 7) An Action Drawing (Part 2 of 7) An Action Drawing (Part 3 of 7) An Action Drawing (Part 4 of 7) An Action Drawing (Part 5 of 7) An Action Drawing (Part 6 of 7) An Action Drawing (Part 7 of 7) The end King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS201 Lecture 17 : Applets Slides prepared by Rose Williams, Binghamton University Applets: Introduction Java programs are divided into two main categories, applets and applications An application is an ordinary Java program An applet is a kind of Java program that can be run across the Internet Programming Applets The word applet is meant to suggest a small Applets were intended to be small programs run over the Internet application However, there are no size constraints on applets Applets can be viewed over the Internet, or without any connection to the internet An applet is similar to a Swing GUI In fact, almost all of the Swing techniques can be used in applets Defining an Applet An applet class is normally defined as a derived class of the class JApplet The class JApplet is in the package javax.swing There is also an older class, Applet, which has been superseded by the JApplet class Applets in the Class Hierarchy Designing an Applet An applet class can be designed as a derived class of JApplet in much the same way that regular Swing GUIs are defined as derived classes of JFrame However, an applet normally defines no constructors The method init performs the initializations that would be performed in a constructor for a regular Swing GUI Designing an Applet Components can be added to an applet in the same way that a component is added to a JFrame The method add is used to add components to an applet in the same way that components are added to a JFrame An Applet (Part 1 of 2) An Applet (Part 2 of 2) How Applets Differ from Swing GUIs Some of the items included in a Swing GUI are not included in an applet Applets do not contain a main or setVisible method Applets are displayed automatically by a Web page or an applet viewer Applets do not have titles Therefore, they do not use the setTitle method They are normally embedded in an HTML document, and the HTML document can add any desired title How Applets Differ from Swing GUIs Applets do not use the setSize method The HTML document takes care of sizing the applet Applets do not have a close-window button Therefore, they do not have a setDefaultCloseOperation method When the HTML document containing the applet is closed, then the applet is automatically closed Running an Applet An applet class is compiled in the same way as any other Java class However, an applet is run differently from other Java programs The normal way to run an applet is to embed it in an HTML document The applet is then run and viewed through a Web browser Running an Applet An applet can also be viewed using an applet viewer An applet viewer is a program designed to run an applet as a stand-alone program The Java appletviewer can be used to run an applet: appletviewer FirstApplet.html It may be necessary, however, to create the HTML document, and place the applet in it Applet Examples http://www.nku.edu/~foxr/Camp/appletexamples.ht ml Menus in a JApplet Menus are constructed and added to a JApplet as they are for a JFrame JApplet has a method named setJMenuBar that behaves the same as the setJMenuBar method of a JFrame JApplet can also have menu bars added to a JApplet or to a panel that is part of the JApplet using the add method Tip: Converting a Swing Application to an Applet The fastest and easiest way to explain how to define an applet, is to explain how to modify a Swing GUI to transform it into an applet Derive the class from the class JApplet instead of from the class Jframe Remove the main method Replace the constructor with a no-parameter method named init 1. 2. 3. – 4. 5. 6. 7. – The body of the init method can be the same as the body of the deleted constructor, but with some items removed Delete any invocation of super Delete any method invocations that program the close-window button of a windowing GUI Delete any invocation of setTitle Delete any invocation of setSize The following applet was generated in this way An Applet Calculator (Part 1 of 9) An Applet Calculator (Part 2 of 9) An Applet Calculator (Part 3 of 9) An Applet Calculator (Part 4 of 9) An Applet Calculator (Part 5 of 9) An Applet Calculator (Part 6 of 9) An Applet Calculator (Part 7 of 9) An Applet Calculator (Part 8 of 9) An Applet Calculator (Part 9 of 9) Inserting an Applet in an HTML Document An applet can be placed in an HTML document with an applet tag: <applet code="PathToApplet" width=Number1 height=Number2> </applet> If given a .class file name only, then the HTML file and the applet file must be in the same directory The PathToApplet can be a full or relative path name Inserting an Applet in an HTML Document Note that the name of the .class file, not the .java file, is given Note also that the width and height of the applet is given in this command, and not within the applet class definition The width and height are in pixels The following code, when placed in an HTML document, will display the calculator applet in a browser as shown <applet code="AppletCalculator.class" width=400 height=300> </applet> An Applet in an HTML Document <html> <head> <title> Vampire Control </title> </head> . . . <applet code="AppletCalculator.class" width=400 height=300> </applet> . . . </html> Browser View Applets and Security An applet can be a program, written by someone else, that runs on your computer Whenever someone else's program runs on your computer, there are security questions you should ask: Will it read information from your files? Will it corrupt your operating system? Applets are designed so that they cannot do any of these things (at least easily) Applet Examples http://www-math.mit.edu/daimp/ The end King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS201 Lectures 18 : Threads Slides prepared by Rose Williams, Binghamton University Multithreading In Java, programs can have multiple threads Threads are often thought of as computations that run in parallel A thread is a separate computation process Although they usually do not really execute in parallel Instead, the computer switches resources between threads so that each one does a little bit of computing in turn Modern operating systems allow more than one program to run at the same time An operating system uses threads to do this Thread.sleep Thread.sleep is a static method in the class Thread that pauses the thread that includes the invocation It pauses for the number of milliseconds given as an argument Note that it may be invoked in an ordinary program to insert a pause in the single thread of that program It may throw a checked exception, InterruptedException, which must be caught or declared Both the Thread and InterruptedException classes are in the package java.lang A Nonresponsive GUI The following program contains a simple GUI that draws circles one after the other when the "Start" button is clicked There is a 1/10 of a second pause between drawing each circle If the close-window button is clicked, nothing happens until the program is finished drawing all its circles Note the use of the Thread.sleep (in the method doNothing) and getGraphics (in the method fill) methods Nonresponsive GUI Nonresponsive GUI Nonresponsive GUI Nonresponsive GUI Nonresponsive GUI Nonresponsive GUI If the close-window button is clicked, nothing happens until the program is finished drawing all its circles ! Because the method fill is invoked in the body of the method actionPerformed, the method actionPerformed does not end until after the method fill ends Until the method actionPerformed ends, the GUI cannot respond to anything else Fixing a Nonresponsive Program Using Threads This is how to fix the problem: Have the actionPerformed method create a new (independent) thread to draw the circles Once created, the new thread will be an independent process that proceeds on its own Now, the work of the actionPerformed method is ended, and the main thread (containing actionPerformed) is ready to respond to something else If the close-window button is clicked while the new thread draws the circles, then the program will end The Class Thread In Java, a thread is an object of the class Thread Usually, a derived class of Thread is used to program a thread The methods run and start are inherited from Thread The derived class overrides the method run to program the thread The method start initiates the thread processing and invokes the run method Threaded Version of FillDemo Without Threads With Threads Threaded Version of FillDemo The new program uses a main thread and a second thread to fix the nonresponsive GUI It creates an inner class Packer that is a derived class of Thread The method run is defined in the same way as the previous method fill Instead of invoking fill, the actionPerformed method now creates an instance of Packer, a new independent thread named packerThread The packerThread object then invokes its start method The start method initiates processing and invokes run Threaded Version of FillDemo (Part 4 of 6) The Runnable Interface Another way to create a thread is to have a class implement the Runnable interface The Runnable interface has one method heading: public void run(); A class that implements Runnable must still be run from an instance of Thread This is usually done by passing the Runnable object as an argument to the thread constructor The Runnable Interface: Suggested Implementation Outline public class ClassToRun extends SomeClass implements Runnable { . . . public void run() { // Fill this as if ClassToRun // were derived from Thread } . . . public void startThread() { Thread theThread = new Thread(this); theThread.start(); } . . . } FillDemo with Runnable interface The end King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS201 Lecture 19 : Recursion Slides prepared by Rose Williams, Binghamton University Recursive void Methods A recursive method is a method that includes a call to itself Recursion is based on the general problem solving technique of breaking down a task into subtasks In particular, recursion can be used whenever one subtask is a smaller version of the original task First Example : Vertical Numbers Vertical Numbers The static recursive method writeVertical takes one (nonnegative) int argument, and writes that int with the digits going down the screen one per line Note: Recursive methods need not be static This task may be broken down into the following two subtasks Simple case: If n<10, then write the number n to the screen Recursive Case: If n>=10, then do two subtasks: Output all the digits except the last digit Output the last digit Vertical Numbers Given the argument 1234, the output of the first subtask would be: 1 2 3 The output of the second part would be: 4 Vertical Numbers The decomposition of tasks into subtasks can be used to derive the method definition: Subtask 1 is a smaller version of the original task, so it can be implemented with a recursive call Subtask 2 is just the simple case Algorithm for Vertical Numbers Given parameter n: if (n<10) System.out.println(n); else { writeVertical (the number n with the last digit removed); System.out.println(the last digit of n); } Note: n/10 is the number n with the last digit removed, and n%10 is the last digit of n Tracing a Recursive Call Recursive methods are processed in the same way as any method call writeVertical(123); When this call is executed, the argument 123 is substituted for the parameter n, and the body of the method is executed Since 123 is not less than 10, the else part is executed Tracing a Recursive Call The else part begins with the method call: writeVertical(n/10); Substituting n equal to 123 produces: writeVertical(123/10); Which evaluates to writeVertical(12); At this point, the current method computation is placed on hold, and the recursive call writeVertical is executed with the parameter 12 When the recursive call is finished, the execution of the suspended computation will return and continue from the point above Execution of writeVertical(123) Tracing a Recursive Call writeVertical(12); When this call is executed, the argument 12 is substituted for the parameter n, and the body of the method is executed Since 12 is not less than 10, the else part is executed The else part begins with the method call: writeVertical(n/10); Substituting n equal to 12 produces: writeVertical(12/10); Which evaluates to write Vertical(1); Tracing a Recursive Call So this second computation of writeVertical is suspended, leaving two computations waiting to resume , as the computer begins to execute another recursive call When this recursive call is finished, the execution of the second suspended computation will return and continue from the point above Execution of writeVertical(12) Tracing a Recursive Call write Vertical(1); When this call is executed, the argument 1 is substituted for the parameter n, and the body of the method is executed Since 1 is less than 10, the if-else statement Boolean expression is finally true The output statement writes the argument 1 to the screen, and the method ends without making another recursive call Note that this is the stopping case Execution of writeVertical(1) Tracing a Recursive Call When the call writeVertical(1) ends, the suspended computation that was waiting for it to end (the one that was initiated by the call writeVertical(12)) resumes execution where it left off It outputs the value 12%10, which is 2 This ends the method Now the first suspended computation can resume execution Completion of writeVertical(12) Tracing a Recursive Call The first suspended method was the one that was initiated by the call writeVertical(123) It resumes execution where it left off It outputs the value 123%10, which is 3 The execution of the original method call ends As a result, the digits 1,2, and 3 have been written to the screen one per line, in that order Completion of writeVertical(123) General Form of a Recursive Method Definition The general outline of a successful recursive method definition is as follows: One or more cases that include no recursive calls: base cases or stopping cases One or more cases that include one or more recursive calls to the method being defined These recursive calls should solve "smaller" versions of the task performed by the method being defined They must come closer to the base case. Pitfall: Infinite Recursion In the writeVertical example, the series of recursive calls eventually reached a call of the method that did not involve recursion (a stopping case) If, instead, every recursive call had produced another recursive call, then a call to that method would, in theory, run forever This is called infinite recursion In practice, such a method runs until the computer runs out of resources, and the program terminates abnormally Pitfall: Infinite Recursion An alternative version of writeVertical Note: No stopping case! public static void newWriteVertical(int n) { newWriteVertical(n/10); System.out.println(n%10); } Pitfall: Infinite Recursion A program with this method will compile and run Calling newWriteVertical(12) causes that execution to stop to execute the recursive call newWriteVertical(12/10) Calling newWriteVertical(1) causes that execution to stop to execute the recursive call newWriteVertical(1/10) Which is equivalent to newWriteVertical(0) Calling newWriteVertical(0) causes that execution to stop to execute the recursive call newWriteVertical(0/10) Which is equivalent to newWriteVertical(1) Which is equivalent to newWriteVertical(0) . . . And so on, forever! Since the definition of newWriteVertical has no stopping case, the process will proceed forever (or until the computer runs out of resources) Recursion Versus Iteration Recursion is not absolutely necessary Any task that can be done using recursion can also be done in a nonrecursive manner A nonrecursive version of a method is called an iterative version An iteratively written method will typically use loops of some sort in place of recursion A recursively written method can be simpler, but will usually run slower and use more storage than an equivalent iterative version Iterative version of writeVertical Recursive Methods that Return a Value Recursion is not limited to void methods A recursive method can return a value of any type An outline for a successful recursive method that returns a value is as follows: One or more cases in which the value returned is computed in terms of calls to the same method the arguments for the recursive calls should be intuitively "smaller" One or more cases in which the value returned is computed without the use of any recursive calls (the base or stopping cases) Another Powers Method The method pow from the Math class computes powers It takes two arguments of type double and returns a value of type double The recursive method power takes two arguments of type int and returns a value of type int The definition of power is based on the following formula: xn is equal to xn-1 * x Another Powers Method In terms of Java, the value returned by power(x, n) for n>0 should be the same as power(x, n-1) * x When n=0, then power(x, n) should return 1 This is the stopping case The Recursive Method power Evaluating the Recursive Method Call power(2,3) Recursive Problem 1 Compute the factorial of an integer, i.e. fact(n) = n! Recursive Problem 2 Calculate the sum of an array of integers Recursive Problem 3 Reverse the order of the characters in a string Recursive Problem 4 Count number of digits in an integer Recursive Problem 5 Consider the following sequence of numbers: 1, 1, 2, 3, 5, 8, 13 Except for the first two integers, each integer is the sum of the previous two integers. This sequence is known as fibonacci numbers. Fibonacci numbers have important applications in computer science and mathematics. Write a program to produce the first n numbers of the fibonacci sequence Recursive Problem 6 A palindrome is a phrase that reads the same forwards and backwards. For example: radar able was I ere I saw elba pan a nap Write a program that answers the question, "Is this string a palindrome?" Recursive Problem 7 print out all the permutations of a string Example: permutations of "abc": abc acb bac bca cab cba (assume no repeated letters in string) Much simpler to solve this with recursion than without. Permutations Solution Given the empty set { }, the only possible permutation is { } Given the set {A}, the only possible permutation is {A} Given the set {A, B}, the possible permutations are {AB, BA} Given the set {A, B, C}, the possible permutations are {ABC, ACB, BAC, BCA, CAB, CBA} Etc. Finding all permutations of n objects To find all permutations of n objects: Find all permutations of n-1 of those objects Insert the remaining object into all possible positions of each permutation of n-1 objects Example: To find all permutations of 3 objects {A, B, C} Find all permutations of 2 of the objects, say B and C: B C and C B Insert the remaining object, A, into all possible positions (marked by ^) in each of the permutations of B and C: B ^ C ^ and ^ C ^ B ^ ^ ABC BAC BCA ACB CAB CBA Towers of Hanoi In a later course The end King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS201 Lecture 20 : Searching Slides prepared by Rose Williams, Binghamton University The Problem Searching is an every day occurrence. Searching a particular item among a collection of many items Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static final int NONE = -1; // not a legal index static int linearSearch(int target, int[] a) { for (int p = 0; p < a.length; p++) { if (target == a[p]) return p; } return NONE; } Searching an array of Strings Searching an array of Strings is just like searching an array of integers, except Instead of i1==i2 we need to use s1.equals(s2) static final int NONE = -1; // not a legal index static int linearSearch(String target, String[] a) { for (int p = 0; p < a.length; p++) { if (target.equals(a[p])) return p; } return NONE; } Searching an array of Objects Searching an array of Objects is just like searching an array of Strings, provided The operation equals has been defined appropriately static final int NONE = -1; // not a legal index static int linearSearch(Object target, Object[] a) { for (int p = 0; p < a.length; p++) { if (target.equals(a[p])) return p; } return NONE; } Java review: equals The Object class defines public boolean equals(Object obj) For most objects, this just tests identity: whether the two objects are really one and the same This is not generally what you want The String class overrides this method with a method that is more appropriate for Strings You can override equals for your own classes But there are some rules you should follow if you do Overriding equals If you override equals, your method should have the following properties (for your objects x, y, z) Reflexive: for any x, x.equals(x) should return true Symmetric: for any non-null objects x and y, x.equals(y) should return the same result as y.equals(x) Transitive: if x.equals(y) and y.equals(z) are true, then x.equals(z) should also be true Consistent: x.equals(y) should always return the same answer (unless you modify x or y, of course) For any non-null x, x.equals(null) should return false Java cannot check to make sure you follow these rules About sorted arrays An array is sorted in ascending order if each element is not smaller than the preceding element An array is sorted in descending order if each element is no larger than the preceding element When we just say an array is “sorted,” by default we mean that it is sorted in ascending order An array of Object cannot be in sorted order ! There is no notion of “smaller” or “larger” for arbitrary objects We can define an ordering for some of our objects The Comparable interface java.lang provides a Comparable interface with the following method: public int compareTo(Object that) This method should return A negative integer if this is less than that Zero if this equals that A positive integer if this is greater than that Reminder: you implement an interface like this: class MyObject implements Comparable { public int compareTo(Object that) {...} } Consistency with equals compareTo is consistent with equals if: x.compareTo(y)==0 gives the same boolean result as x.equals(y) Therefore: if you implement Comparable, you really should override equals as well Java doesn’t actually require consistency with equals, but sooner or later you’ll get into trouble if you don’t meet this condition Binary Search Ignoring one-half of the data when the data is sorted. Binary search Linear search has linear time complexity: Time n if the item is not found Time n/2, on average, if the item is found If the array is sorted, we can write a faster search How do we look up a name in a phone book, or a word in a dictionary? Look somewhere in the middle Compare what’s there with the thing you’re looking for Decide which half of the remaining entries to look at Repeat until you find the correct place This is the binary search algorithm Binary search algorithm To find which (if any) component of a[left..right] is equal to target (where a is sorted): Set l = left, and set r = right While l <= r, repeat: Let m be an integer about midway between l and r If target is equal to a[m], terminate with answer m If target is less than a[m], set r = m–1 If target is greater than a[m], set l = m+1 Terminate with answer none l ••• m-1 m m+1 ? r ••• Binary search in Java static int binarySearch(Comparable target, Comparable[] a, int left, int right) { int l = left, r = right; while (l <= r) { int m = (l + r) / 2; int comp = target.compareTo(a[m]); if (comp == 0) return m; else if (comp < 0) r = m – 1; else /* comp > 0 */ l = m + 1; } return NONE; // As before, NONE = -1 } Recursive binary search in Java static int binarySearch(Comparable target, Comparable[] a, int left, int right) { if (left > right) return NONE; int m = (left + right) / 2; int comp = target.compareTo(a[m]); if (comp == 0) return m; else if (comp < 0) return binarySearch(target, a, left, m-1); else // comp > 0 return binarySearch(target, a, m+1, right); } Java Class Package: The Method binarySearch The class Arrays in java.util defines versions of a static method with following specification: /** Task: Searches an entire array for a given item. * @param array the array to be searched * @param desiredItem the item to be found in the array * @return index of the array element that equals desiredItem; * otherwise returns -belongsAt-1, where belongsAt is * the index of the array element that should contain * desiredItem */ public static int binarySearch(type[] array, type desiredItem); The Method binarySearch Binary search takes log n time In binary search, we choose an index that cuts the remaining portion of the array in half We repeat this until we either find the value we are looking for, or we reach a subarray of size 1 If we start with an array of size n, we can cut it in half log2n times Hence, binary search has logarithmic (log n) time complexity For an array of size 1000, this is 100 times faster than linear search (210 ~= 1000) Conclusion Linear search has linear time complexity Binary search has logarithmic time complexity For large arrays, binary search is far more efficient than linear search However, binary search requires that the array be sorted If the array is sorted, binary search is 100 times faster for an array of size 1000 50 000 times faster for an array of size 1 000 000 This is the kind of speedup that we care about when we analyze algorithms The end King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS201 Lecture 21 : Sorting First semester 2009-2010 (091) Slides prepared by Rose Williams, Binghamton University Objectives To learn how to use the standard sorting methods in the Java API To learn how to implement the following sorting algorithms: selection sort, mergesort, and quicksort To understand the difference in performance of these algorithms, and which to use for small arrays, which to use for medium arrays, and which to use for large arrays Definition and applications of Sorting Definition : Sorting is the task of putting data into a particular order either ascending or descending The most intensively studied processing Internal sorting - data fit into RAM External sorting - data are on the disk Sorting speeds up search: Dictionary Files in a directory Calendar Phone list Using Java Sorting Methods Java API provides a class Arrays with several overloaded static sort methods for different array types The Collections class provides similar sorting methods Sorting methods for arrays of primitive types are based on quicksort algorithm Method of sorting for arrays of objects and Lists based on mergesort Selection Sort Selection Sort Sorting: Arrange things into either ascending or descending order Task: rearrange books on shelf by height Shortest book on the left Approach: Look at books, select shortest book Swap with first book Look at remaining books, select shortest Swap with second book Repeat … Selection Sort Before and after exchanging shortest book and the first book. Selection Sort The Selection sort begins at the front of the list and looks for the first element smaller (or larger) than the current element. Then the elements are switched. The actual identification of the element to switch is based upon the type of sort Ascending or descending Selection Sort A selection sort of an array of integers into ascending order. Selection Sort Iterative algorithm for selection sort Algorithm selectionSort(a, n) // Sorts the first n elements of an array a. for (index = 0; index < n - 1; index++) { indexOfNextSmallest = the index of the smallest value among a[index], a[index+1], . . . , a[n-1] Interchange the values of a[index] and a[indexOfNextSmallest] // Assertion: a[0] £ a[1] £ . . . £ a[index], and these are the smallest // of the original array elements. // The remaining array elements begin at a[index+1]. } Selection Sort in Java Merge Sort Mergesort A recursive divide-and-conquer algorithm A merge is a common data processing operation that is performed on two sequences of data with the following characteristics Both sequences contain items with a common compareTo method The objects in both sequences are ordered in accordance with this compareTo method Merge Algorithm 1. 2. Access the first item from both sequences While not finished with either sequence Compare the current items from the two sequences, copy the smaller current item to the output sequence, and access the next item from the input sequence whose item was copied 3. 4. Copy any remaining items from the first sequence to the output sequence Copy any remaining items from the second sequence to the output sequence Algorithm Conceptually, merge sort works as follows: 1. 2. 3. Divide the unsorted list into two sublists of about half the size Sort each of the two sublists recursively until we have list sizes of length 1, in which case the list itself is returned Merge the two sorted sublists back into one sorted list. Mergesort incorporates two main ideas to improve its runtime: 1. 2. A small list will take fewer steps to sort than a large list. Fewer steps are required to construct a sorted list from two sorted lists than two unsorted lists. For example, you only have to traverse each list once if they're already sorted How merge sort works Pseudocode function mergesort(m) var list left, right, result if length(m) ≤ 1 return m else middle = length(m) / 2 for each x in m up to middle add x to left for each x in m after middle add x to right left = mergesort(left) right = mergesort(right) result = merge(left, right) return result Pseudocode function merge(left,right) var list result while length(left) > 0 and length(right) > 0 if first(left) ≤ first(right) append first(left) to result left = rest(left) else append first(right) to result right = rest(right) if length(left) > 0 append left to result if length(right) > 0 append right to result return result MergeSort in Java MergeSort in Java Merge Sort The merge sort algorithm requires recursion The concept used in this algorithm is called divide-andconquer The array is first split into two smaller arrays Each of the smaller two arrays are recursively sorted The two arrays are merged back into one array The base case for the merge sort is when the array to be sorted only has one element left that does not need to be rearranged If there is more than one element to sort, split the arrays into two sections and call the merge sort Quick Sort Quicksort Developed in 1962 by C. A. R. Hoare Recursive Divide-and-conquer The fastest algorithm known Average running time O(N log N) Worst-case running time O(N2) but very unlikely to happen Quicksort Quicksort rearranges an array into two parts so that all the elements in the left subarray are less than or equal to a specified value, called the pivot Quicksort ensures that the elements in the right subarray are larger than the pivot Advantage: Disadvantage: No extra memory is needed Fast running time (in average) Unstable in running time Finding “pivot” element is a big issue! Quicksort Algorithm To sort a[left...right]: 1. if left < right: 1.1. Partition a[left...right] such that: all a[left...p-1] are less than a[p], and all a[p+1...right] are >= a[p] 1.2. Quicksort a[left...p-1] 1.3. Quicksort a[p+1...right] 2. Terminate Partitioning A key step in the Quicksort algorithm is partitioning the array We choose some (any) number p in the array to use as a pivot We partition the array into three parts: p numbers less than p p numbers greater than or equal to p Partitioning Choose an array value (say, the first) to use as the pivot Starting from the left end, find the first element that is greater than or equal to the pivot Searching backward from the right end, find the first element that is less than the pivot Interchange (swap) these two elements Repeat, searching from where we left off, until done Example of Partitioning choose pivot: search: swap: search: swap: search: swap: search: 436924312189356 436924312189356 433924312189656 433924312189656 433124312989656 433124312989656 433122314989656 433122314989656 swap with pivot: 133122344989656 (left > right) Partitioning To partition a[left...right]: 1. Set pivot = a[left], l = left + 1, r = right; 2. while l < r, do 2.1. while l < right & a[l] < pivot , set l = l + 1 2.2. while r > left & a[r] >= pivot , set r = r - 1 2.3. if l < r, swap a[l] and a[r] 3. Set a[left] = a[r], a[r] = pivot 4. Terminate Selecting the Pivot First element - a bad choice In general, don't select the pivot near the beginning or the end of the set Middle element is a good choice Median-of-three - the median of the first, middle, and last elements How Quick Sort works Quick Sort in Java Comparison of Sorts Quick Sort and Merge Sort will always be faster than the Selection sort. Quick Sort sorts “in place” and the hidden constant in the average case is smaller than Merge Sort's Merge Sort’s worst case behavior is better than Quick Sort’s worst case Selection Sort Selection Sort: Merge Sort: best, worst, and average cases are: Q(n2) best, worst, and average cases are Q(n log n) Quick Sort: Best and average cases are Q(n log n) Worst case is Q(n2) Other Sort algorithms Bubble Sort 1. 2. Compare each pair of adjacent elements from the beginning of an array and, if they are in reversed order, swap them. If at least one swap has been done, repeat step 1. Bubble Sort Bubble Sort in Java Complexity: Q(n2) Insertion Sort Array is imaginary divided into two parts - sorted one and unsorted one. At the beginning, sorted part contains first element of the array and unsorted one contains the rest. At every step, algorithm takes first element in the unsorted part and inserts it to the right place of the sorted one. When unsorted part becomes empty, algorithm stops. Insertion Sort Insertion Sort Complexity: Q(n2) The end King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS201 Lecture 22 : ArrayList Slides prepared by Rose Williams, Binghamton University The ArrayList Class ArrayList is a class in the standard Java libraries Unlike arrays, which have a fixed length once they have been created, an ArrayList is an object that can grow and shrink while your program is running In general, an ArrayList serves the same purpose as an array, except that an ArrayList can change length while the program is running The ArrayList Class The class ArrayList is implemented using an array as a private instance variable When this hidden array is full, a new larger hidden array is created and the data is transferred to this new array The ArrayList Class Why not always use an ArrayList instead of an array? 1. 2. 3. An ArrayList is less efficient than an array It does not have the convenient square bracket notation The base type of an ArrayList must be a class type (or other reference type): it cannot be a primitive type This last point is less of a problem now that Java provides automatic boxing and unboxing of primitives Using the ArrayList Class In order to make use of the ArrayList class, it must first be imported from the package java.util An ArrayList is created and named in the same way as object of any class, except that you specify the base type as follows: ArrayList<BaseType> aList = new ArrayList<BaseType>(); Using the ArrayList Class An initial capacity can be specified when creating an ArrayList as well The following code creates an ArrayList that stores objects of the base type String with an initial capacity of 20 items ArrayList<String> list = new ArrayList<String>(20); Specifying an initial capacity does not limit the size to which an ArrayList can eventually grow Note that the base type of an ArrayList is specified as a type parameter Using the ArrayList Class The add method is used to set an element for the first time in an ArrayList list.add("something"); The method name add is overloaded There is also a two argument version that allows an item to be added at any currently used index position or at the first unused position Using the ArrayList Class The size method is used to find out how many indices already have elements in the ArrayList int howMany = list.size(); The set method is used to replace any existing element, and the get method is used to access the value of any existing element list.set(index, "something else"); String thing = list.get(index); Summary of Adding to an ArrayList The add method is usually used to place an element in an ArrayList position for the first time (at an ArrayList index) The simplest add method has a single parameter for the element to be added, and adds an element at the next unused index, in order Summary of Adding to an ArrayList An element can be added at an already occupied list position by using the two-parameter version of add This causes the new element to be placed at the index specified, and every other member of the ArrayList to be moved up by one position Summary of Adding to an ArrayList The two-argument version of add can also be used to add an element at the first unused position (if that position is known) Any individual element can be changed using the set method However, set can only reset an element at an index that already contains an element In addition, the method size can be used to determine how many elements are stored in an ArrayList Methods in the Class ArrayList The tools for manipulating arrays consist only of the square brackets and the instance variable length ArrayLists, however, come with a selection of powerful methods that can do many of the things for which code would have to be written in order to do them using arrays Some Methods in the Class ArrayList Some Methods in the Class ArrayList Some Methods in the Class ArrayList Some Methods in the Class ArrayList Some Methods in the Class ArrayList Some Methods in the Class ArrayList Some Methods in the Class ArrayList Some Methods in the Class ArrayList Some Methods in the Class ArrayList Some Methods in the Class ArrayList Some Methods in the Class ArrayList The "For Each" Loop The ArrayList class is an example of a collection class Starting with version 5.0, Java has added a new kind of for loop called a for-each or enhanced for loop This kind of loop has been designed to cycle through all the elements in a collection (like an ArrayList) A for-each Loop Used with an ArrayList A for-each Loop Used with an ArrayList A for-each Loop Used with an ArrayList Tip: Use trimToSize to Save Memory An ArrayList automatically increases its capacity when needed However, the capacity may increase beyond what a program requires In addition, although an ArrayList grows automatically when needed, it does not shrink automatically If an ArrayList has a large amount of excess capacity, an invocation of the method trimToSize will shrink the capacity of the ArrayList down to the size needed Pitfall: The clone method Makes a Shallow Copy When a deep copy of an ArrayList is needed, using the clone method is not sufficient Invoking clone on an ArrayList object produces a shallow copy, not a deep copy In order to make a deep copy, it must be possible to make a deep copy of objects of the base type Then a deep copy of each element in the ArrayList can be created and placed into a new ArrayList object The end King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS201 Lecture 23 : Generics Slides prepared by Rose Williams, Binghamton University Introduction to Generics Beginning with version 5.0, Java allows class and method definitions that include parameters for types Such definitions are called generics Generic programming with a type parameter enables code to be written that applies to any class Parameterized Classes and Generics The class ArrayList is a parameterized class It has a parameter, denoted by Base_Type, that can be replaced by any reference type to obtain a class for ArrayLists with the specified base type Starting with version 5.0, Java allows class definitions with parameters for types These classes that have type parameters are called parameterized class or generic definitions, or, simply, generics Generics Classes and methods can have a type parameter A type parameter can have any reference type (i.e., any class type) plugged in for the type parameter When a specific type is plugged in, this produces a specific class type or method Traditionally, a single uppercase letter is used for a type parameter, but any non-keyword identifier may be used Generics A class definition with a type parameter is stored in a file and compiled just like any other class Once a parameterized class is compiled, it can be used like any other class However, the class type plugged in for the type parameter must be specified before it can be used in a program Doing this is said to instantiate the generic class Sample<String> object = new Sample<String>(); A Class Definition with a Type Parameter Class Definition with a Type Parameter A class that is defined with a parameter for a type is called a generic class or a parameterized class The type parameter is included in angular brackets after the class name in the class definition heading Any non-keyword identifier can be used for the type parameter, but by convention, the parameter starts with an uppercase letter The type parameter can be used like other types used in the definition of a class Example: Ordered Pair Class Example: Ordered Pair Class Example: Ordered Pair Class Example: Ordered Pair Class Example: Using Ordered Pair Class Using Our Ordered Pair Class Pitfall: A Generic Constructor Name Has No Type Parameter Although the class name in a parameterized class definition has a type parameter attached, the type parameter is not used in the heading of the constructor definition public Pair() A constructor can use the type parameter as the type for a parameter of the constructor, but in this case, the angular brackets are not used public Pair(T first, T second) However, when a generic class is instantiated, the angular brackets are used Pair<String> pair = new Pair<String>("Happy", "Day"); Pitfall: A Primitive Type Cannot be Plugged in for a Type Parameter The type plugged in for a type parameter must always be a reference type It cannot be a primitive type such as int, double, or char However, now that Java has automatic boxing, this is not a big restriction Note: reference types can include arrays Pitfall: A Type Parameter Cannot Be Used Everywhere a Type Name Can Be Used Within the definition of a parameterized class definition, there are places where an ordinary class name would be allowed, but a type parameter is not allowed In particular, the type parameter cannot be used in simple expressions using new to create a new object For instance, the type parameter cannot be used as a constructor name or like a constructor: T object = new T(); T[] a = new T[10]; Pitfall: An Instantiation of a Generic Class Cannot be an Array Base Type Arrays such as the following are illegal: Pair<String>[] a = new Pair<String>[10]; Although this is a reasonable thing to want to do, it is not allowed given the way that Java implements generic classes The end King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS201 Lecture 24 : Collections Slides prepared by Rose Williams, Binghamton University Collections A Java collection is any class that holds objects and implements the Collection interface For example, the ArrayList<T> class is a Java collection class, and implements all the methods in the Collection interface Collections are used along with iterators The Collection interface is the highest level of Java's framework for collection classes All of the collection classes discussed here can be found in package java.util The Collection Landscape Wildcards Classes and interfaces in the collection framework can have parameter type specifications that do not fully specify the type plugged in for the type parameter Because they specify a wide range of argument types, they are known as wildcards public void method(String arg1, ArrayList<?> arg2) In the above example, the first argument is of type String, while the second argument can be an ArrayList<T> with any base type Wildcards A bound can be placed on a wildcard specifying that the type used must be an ancestor type or descendent type of some class or interface The notation <? extends String> specifies that the argument plugged in be an object of any descendent class of String The notation <? super String> specifies that the argument plugged in be an object of any ancestor class of String The Collection Framework The Collection<T> interface describes the basic operations that all collection classes should implement The method headings for these operations are shown on the next several slides Since an interface is a type, any method can be defined with a parameter of type Collection<T> That parameter can be filled with an argument that is an object of any class in the collection framework Collection Interface methods Method Headings in Collection<T> Method Headings in Collection<T> Method Headings in Collection<T> Method Headings in Collection<T> Method Headings in Collection<T> Method Headings in Collection<T> Method Headings in Collection<T> Method Headings in Collection<T> Collection Relationships There are a number of different predefined classes that implement the Collection<T> interface Programmer defined classes can implement it also A method written to manipulate a parameter of type Collection<T> will work for all of these classes, either singly or intermixed There are two main interfaces that extend the Collection<T> interface: The Set<T> interface and the List<T> interface Collection Relationships Classes that implement the Set<T> interface do not allow an element in the class to occur more than once The Set<T> interface has the same method headings as the Collection<T> interface, but in some cases the semantics (intended meanings) are different Methods that are optional in the Collection<T> interface are required in the Set<T> interface Collection Relationships Classes that implement the List<T> interface have their elements ordered as on a list Elements are indexed starting with zero A class that implements the List<T> interface allows elements to occur more than once The List<T> interface has more method headings than the Collection<T> interface Some of the methods inherited from the Collection<T> interface have different semantics in the List<T> interface The ArrayList<T> class implements the List<T> interface Methods in the Set<T> Interface Methods in the Set<T> Interface Methods in the Set<T> Interface Methods in the Set<T> Interface Methods in the Set<T> Interface Methods in the Set<T> Interface Methods in the List<T> Interface (Part 1 of 16) Methods in the List<T> Interface (Part 2 of 16) Methods in the List<T> Interface (Part 3 of 16) Methods in the List<T> Interface (Part 4 of 16) Methods in the List<T> Interface (Part 7 of 16) Methods in the List<T> Interface (Part 9 of 16) Methods in the List<T> Interface (Part 10 of 16) Methods in the List<T> Interface (Part 12 of 16) Methods in the List<T> Interface (Part 13 of 16) Methods in the List<T> Interface (Part 14 of 16) Methods in the List<T> Interface (Part 15 of 16) Comparison The Collections Class The Collections class is a utility class. It contains static methods for manipulating collection objects. The Arrays class is also a utility class. It contains static methods for manipulating arrays. One useful method used is asList() to convert an array into a list. The following are the most frequently used methods of the Collections class. static static static static static static static static int binarySearch(List list, Object o) int binarySearch(List list, Object o, Comparator c) void sort(List list) void sort(List list, Comparator c) Object max(Collection c) Object min(Collection c) void reverse(List list) void shuffle(List list) The end King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS201 Lecture 25 : Iterators Slides prepared by Rose Williams, Binghamton University Iterators An iterator is an object that is used with a collection to provide sequential access to the collection elements This access allows examination and possible modification of the elements An iterator imposes an ordering on the elements of a collection even if the collection itself does not impose any order on the elements it contains If the collection does impose an ordering on its elements, then the iterator will use the same ordering The Iterator<T> Interface Java provides an Iterator<T> interface Any object of any class that satisfies the Iterator<T> interface is an Iterator<T> An Iterator<T> does not stand on its own It must be associated with some collection object using the method iterator If c is an instance of a collection class (e.g., Vector<String>), the following obtains an iterator for c: Iterator iteratorForC = c.iterator(); Methods in the Iterator<T> Interface Methods in the Iterator<T> Interface (Part 2 of 2) The ListIterator<T> Interface The ListIterator<T> interface extends the Iterator<T> interface, and is designed to work with collections that satisfy the List<T> interface A ListIterator<T> has all the methods that an Iterator<T> has, plus additional methods A ListIterator<T> can move in either direction along a list of elements A ListIterator<T> has methods, such as set and add, that can be used to modify elements Methods in the ListIterator<T> Interface (Part 1 of 4) Methods in the ListIterator<T> Interface (Part 2 of 4) Methods in the ListIterator<T> Interface (Part 3 of 4) Methods in the ListIterator<T> Interface (Part 4 of 4) The ListIterator<T> Cursor Every ListIterator<T> has a position marker known as the cursor If the list has n elements, they are numbered by indices 0 through n-1, but there are n+1 cursor positions When next() is invoked, the element immediately following the cursor position is returned and the cursor is moved forward one cursor position When previous() is invoked, the element immediately before the cursor position is returned and the cursor is moved back one cursor position ListIterator<T> Cursor Positions Iterator methods ListIterator methods Exercise Write a program that reads a text from System.in and breaks it up into individual words. Insert the words into a linked list. Then remove all words that contain the letter ‘a’. Print all the words of the obtained list as well as its size. Pitfall: next and previous Can Return a Reference Theoretically, when an iterator operation returns an element of the collection, it might return a copy or clone of the element, or it might return a reference to the element Iterators for the standard predefined collection classes, such as ArrayList<T> and HashSet<T>, actually return references Therefore, modifying the returned value will modify the element in the collection Example An Iterator Returns a Reference Tip: Defining Your Own Iterator Classes There is usually little need for a programmer defined Iterator<T> or ListIterator<T> class The easiest and most common way to define a collection class is to make it a derived class of one of the library collection classes By doing this, the iterator() and listIterator() methods automatically become available to the program If a collection class must be defined in some other way, then an iterator class should be defined as an inner class of the collection class Tip: For-Each Loops as Iterators Although it is not an iterator, a for-each loop can serve the same purpose as an iterator A for-each loop can be used to cycle through each element in a collection For-each loops can be used with any of the collections discussed here For-Each Loops as Iterators The end