Upload
aishatu-musa-abba
View
53
Download
0
Tags:
Embed Size (px)
DESCRIPTION
COS 212
Citation preview
Unit 01 1
Inheritance
• Recall What Inheritance is About
• The extends Keyword
• The Object Class
• Overriding versus Overloading
• What is Actually Inherited?
• Single vs. Multiple Inheritance
• Up-Casting
Sahalu Junaidu
2
Recall What Inheritance is About
• Inheritance allows a software developer to derive a new class from an existing one. –Reusability
• The existing class is called the parent class, base class or super class.
• The new class is called the child class, derived class or subclass.
• As the name implies, the child inherits characteristics of the parent.
• That is, the child class inherits the methods and data defined in the parent class.
• Inheritance relationships are often shown graphically in a class diagram, with the arrow pointing to the parent class.
• Inheritance creates an is-a relationship, meaning the child is a more specific version of the parent.
Student
GraduateStudent
defendThesis()
Sahalu Junaidu Unit 01
3
The extends Keyword• In Java, the keyword extends is used to establish an inheritance.
1. public class Student{2. private String name;3. private int id;4. private double gpa;5.6. public Student(int id, String name, double gpa){...}7. public Student(int id, double gpa){...}8. public String getName(){...}9. public int getId(){...}10. public double getGPA(){...}11. public String toString(){...}12. public void setGPA(double newGPA){...}13. }
1. public class GraduateStudent extends Student{2. private String thesisTitle;3. public GraduateStudent(...){...}4. public String toString(){...} // overridden5. public void defendThesis(){...} // added6. }
Sahalu Junaidu Unit 01
4
The Object Class
• A class called Object is defined in the java.lang package of the Java
standard class library.
• If a class is not explicitly defined to be the child of an existing class, it is
assumed to be the child of the Object class.
• Thus, the Object class is the ultimate parent of all classes.
• The Object class contains a few useful methods, toString, equals, etc.,
which are inherited by all classes.
• The toString method in the Object class is defined to return the name of the
object's class and its location in the memory, while the equals method
determines if two references are aliases.
• Although all objects are guaranteed to have a toString and equals methods,
it is often desirable to override these methods when we write our classes.
Sahalu Junaidu Unit 01
5
Overriding Methods• A child class can override a method it inherited from its super class.• The new method must have the same signature as the parent's method.
1. public class Student{2. private String name;3. private int id;4. private double gpa;5. //...6. public String toString(){7. return "ID: "+id+“ Name: "+name+“ GPA: "+gpa;8. }9. //...10. }
1. public class GraduateStudent extends Student{2. private String thesisTitle;3. //...4. public String toString() // overridden{5. return super.toString()+“ Thesis Title: "+thesisTitle;6. }7. //...8. }
Sahalu Junaidu Unit 01
6
Overloading vs Overriding
• Comparison between overloading and overriding
Overriding deals with two methods, one in a parent class and one in a child class with the same signature
Overriding lets you define a similar operation in different ways for different object types
Overloading deals with multiple methods in the same class with the same name but different signatures.
Overloading lets you define a similar operation in different ways for different data
Sahalu Junaidu Unit 01
7
Constructors are not Inherited
• Constructors are not inherited, even though they have public visibility.• However, the super reference can be used within the child's constructor to
call the parent's constructor.• In that case, the call to parent's constructor must be the first statement.
1. public class GraduateStudent extends Student{2. private String thesisTitle;3. //...4. public GraduateStudent(int id, String name, double gpa, String title){5. super(id, name, gpa);6. thesisTitle = title;7. }8. //...9. }
• If super is not used to call the parent's constructor, the compiler inserts a call to the parent's default constructor. An error results if no such default constructor exists.
Sahalu Junaidu Unit 01
8
What then is Inherited• Fields and Methods are inherited if their access modifiers allow.
• public variables and methods are inherited, but private ones are are not.
• When an instance of a subclass is created, so is that of its super class.
Sahalu Junaidu Unit 01
9
The protected Visibility Modifier
• We saw that fields that are declared private cannot be inherited.• We also know that it is a very bad practice to declare fields as public. So is there a compromise? Yes, protected modifier.
1. public class Student{2. protected String name;3. protected int id;4. protected double gpa;5. //...6. }
1. public class GraduateStudent extends Student{2. private String thesisTitle;3. //...4. public String toString(){5. return "ID: "+id+"Name: "+name+"GPA: "+gpa+"ThesisTitle: "+thesisTitle;6. }7. //...8. }
Sahalu Junaidu Unit 01
10
Single vs. Multiple Inheritance
• Multiple inheritance allows a class to be derived directly from two or more classes, inheriting the members of all parent.
• Collisions, such as the same variable name in two parents, have to be resolved - leading to complex code.
• To avoid this complexity, Java supports only single inheritance, meaning that a derived class can have only one direct parent class.
Student
GraduateStudent
defendThesis()
Object
Sahalu Junaidu Unit 01
11
Class Hierarchy
• A child class of one parent can be the parent of another child, forming class hierarchies.
• Two children of the same parent are called siblings - Example, Faculty and Staff..
• Good class design puts all common features as high in the hierarchy as is reasonable
Sahalu Junaidu Unit 01
12
Up-Casting
• An object reference can refer to an object of its class, or to an object of any class related to it by inheritance
• For example, if the Employee class is used to derive a class, Faculty, then an Employee reference can be used to point to a Faculty object.
• This assigning is called up-casting, because we are going up the inheritance tree.
• Up-casting is considered to be a widening conversion since the subclass object has more methods than its superclass.
Sahalu Junaidu Unit 01
13
Why Up-Casting
• The advantage of up-casting is that some methods apply to a superclass and all its subclasses.
• Such a method can be designed to accept a superclass reference so that it can be called with a superclass object or subclass object.
• For example, a method that generates pay-slip for all employees may have the following heading:
• Now since the method is expecting Employee as argument, we can call it with an object of MonthlyEmployee or HourlyEmployee.
1. MonthlyEmployee secretary = new MonthlyEmployee("Al-Amir", 8000);
2. HourlyEmployee consultant = new HourlyEmployee("Umar", 500);
3. //...
4. generatePaySlip(secretary);
5. generatePaySlip(consultant);
Sahalu Junaidu Unit 01
14
Exercises
Write each of the following classes:
1. A class, Person, with an instance variable, name. Write appropriate accessor and mutator methods for the class. Also write a toString method for the class.
2. Employee, that extends Person, and has: two additional instance variables, ID and payRate; and an additional method, pay, that returns the payRate. Override the toString method accordingly.
3. Faculty, that extends Employee, and has two additional variables; officeHours of type String and teachingCourses, which is an array of Courses. Each course has course code and course title. Write appropriate accessor, mutator and toString methods for the class.
4. TestPersons, that has two methods: void printPerson(Person p) that prints its argument. And a main method that creates an instance of each of the above classes and prints it using printPerson method.
Sahalu Junaidu Unit 01
15
Example
class A {
String a = "A String";
String method1(){
return "method1() from class A.";
}
static String method2(){
return "method2() from class A.";
}
}
class ShadowingVsOverriding extends A {
double a = 7;
String method1(){
return "method1() from class ShadowingVsOverriding.";
}
static String method2(){
return "method2() from class ShadowingVsOverriding.";
}Sahalu Junaidu Unit 01
16
Example – Cont’d
public static void main(String args[]){
//A obj = new ShadowingVsOverriding();
ShadowingVsOverriding obj = new ShadowingVsOverriding();
System.out.println(obj.a);
System.out.println(obj.method1());
System.out.println(obj.method2());
}
7.0
method1() from class ShadowingVsOverriding.
method2() from class ShadowingVsOverriding.
Press any key to continue...
Sahalu Junaidu Unit 01
Unit 02 17
Abstract Classes
• What is an Abstract Class?
• Properties of an Abstract Class
• Discovering Abstract Classes
Sahalu Junaidu
Unit 02 18
What is an Abstract Class?
• A subclass (programmer) normally has the option of whether to override the methods of a superclass or not.
• However, there are situations where the superclass (programmer) would like to force the subclass (programmer) to override a certain method.
• This is usually the case if there is no suitable default implementation.
• For example, consider following
examples of Employee and
HourlyEmployee classes.Sahalu Junaidu
19
What is an Abstract Class? – Cont’d
1. class Employee{2. private String name;3. private double payRate;4.5. public Employee(String name, double payRate){6. this.name = name;7. this.payRate = payRate;8. }9. public double pay(){10. return payRate;11. }12. public void setPayRate(double newRate){13. payRate = newRate;14. }15. public String toString(){16. return "Name: "+name+"Pay Rate: "+payRate;17. }18. }
• The payRate field represents the montly pay for the employee. Notice that the pay method simply returns the value of this field.
Sahalu Junaidu Unit 02
20
What is an Abstract Class? – Cont’d
1. class HourlyEmployee extends Employee{2. private int hours;3.4. public HourlyEmployee(String name, double rate){5. super(name, rate);6. hours = 0;7. }8. public void assHours(int moreHours){9. hours += moreHours;10. }11. public String toString(){12. return super.toString()+"Hours: "+hours;13. }14. public double pay(){15. return super.pay() * hours;16. }17. }
The payRate field represents the hourly pay for the employee. Here the pay method multiplies this value with the hours worked and returns the result.
Sahalu Junaidu Unit 02
21
What is an Abstract Class? – Cont’d
• Clearly, if the pay method is not overridden, by mistake, the pay of the HourlyEmployee will be computed wrongly.• To force the subclass programmer to override this method, the method should be declared as abstract.• An abstract method consists of only the method heading.
1. abstract class Employee{2. private String name;3. private double payRate;4.5. public Employee(String name, double payRate){6. this.name = name;7. this.payRate = payRate;8. }9. public abstract double pay();
10. public void setPayRate(double newRate){11. payRate = newRate;12. }13. //...14. }
Sahalu JunaiduUnit 02
22
What is an Abstract Class? – Cont’d
• Now, once a class has at least one abstract method, then the class is said to be abstract and it must be declared as such in its heading.
• Thus, an abstract class essentially means a class that is "not completely" defined.
• The term, concrete class, is sometimes used to describe a class that is not abstract.
• Note: it is not necessary for an abstract class to have abstract methods.
• Even if all the methods in a class are implemented, the class will still be abstract if it is declared as such in its heading.
Sahalu Junaidu Unit 02
23
Properties of an Abstract Class
• An abstract class cannot be instantiated - that is, it cannot be used to create objects.• For example, We cannot create an object of the Employee class.
• Thus, to represent an employee whose pay is per month, we need to sub-class the Employee abstract class as follows:
1. class MonthlyEmployee extends Employee{2. public MonthlyEmployee(String empNamem double empRate){3. super(empName, empRate);4. }5. public double pay(){6. return payRate;7. }8. }
Sahalu Junaidu Unit 02
24
Properties of an Abstract Class – Cont’d
• The relationship between the three classes is shown by the following:
• Although an abstract class cannot be used to create objects, it can be used to define reference variables.
• Similar to what we saw in inheritance, this variable can be assigned an object created using a concrete sub-class of Employee.
Sahalu Junaidu Unit 02
25
Properties of an Abstract Class – Cont’d
• In summary, an abstract class is just like a normal class except that it cannot be instantiated and is mainly used to factor out instance variables and methods that all classes in a class-hierarchy should have.
Sahalu Junaidu Unit 02
26
Discovering Abstract Classes
• Suppose we wish to write a program that manipulates two-dimensional geometrical shapes, namely:
– Squares
– Rectangles and
– Circles
• Suppose further that we want each such shape to tell its name, its area and its perimeter.
• Since each of these shapes is a type of shape, it makes sense to have a superclass, Shape, from which the others can be derived.
• However, since the computation of area and perimeter for each of these shapes is different, the subclasses should be forced to override these methods. Thus the Shape class must be abstract.
Sahalu Junaidu Unit 02
27
Discovering Abstract Classes – Cont’d
• Moreover, since square is a special type of rectangle, we can derive it from the Rectangle class.
• Thus, we have a two level hierarchy tree shown as follows:
Sahalu Junaidu Unit 02
28
Discovering Abstract Classes – Cont’d
• The code for these classes is shown as follows:
1. public abstract class Shape{2. public String name(){3. return getClass().getName();4. }5. public abstract double area();6. public abstract double perimeter();7. }
1. public class Circle extends Shape{2. public double radius;3. public Circle(double r){4. radius = r;5. }6. public double area(){7. return Math.PI * (radius * radius);8. }9. public double perimeter(){10. return (2.0 * Math.PI )*radius;11. }12. }
Sahalu Junaidu Unit 02
29
Discovering Abstract Classes – Cont’d
1. public class Rectangle extends Shape{2. private double length;3. private double width;4.5. public Rectangle(double length, double width){6. this.length = length;7. this.width = width;8. }9. public double area(){10. return length * width;11. }12.}
1. public class Square extends Rectangle{2. public Square(double length){3. super(length, length);4. }5. }Sahalu Junaidu Unit 02
30
Exercises
1. Write a class, TestEmpolyee, that has the following methods:
a. printPay(Employee emp) : that prints the name and salary of emp.
b. a main method that creates an instance of MonthlyEmployee and
that of HourlyEmployee, and prints them using printPay method.
2. Write a class, Manager, that extends MonthlyEmployee, and has another instance variables, bonus and an instance method, setBonus. Override the pay method and update TestEmployee accordinly.
3. Write a class, TestShapes, that creates an instance of each of our shape classes and prints it.
4. Suppose you wish to write an application that stores information about reading materials in a BookShop. Reading matrials could be books, journals, magazines and newspapers. Identify the classes (including abstract classes, if any) that are needed for this application. Draw a class diagram for the classes and implement them.
Sahalu Junaidu Unit 02
31
Interfaces
• What is an Interface?
• Interface Declaration Syntax
• Implementing Interfaces
• Using Interfaces as Types
• Interfaces and Inheritance
• Interfaces Cannot Grow
• Abstract Classes Versus Interfaces
Sahalu Junaidu Unit 03
32
What is an Interface?
• We have seen that inheritance allows code reusability - a subclass inherits
the properties of its super class.
• Inheritance also allows type sharing - an instance of a subclass is of type its
class, its superclass, and any class up its class-hierarchy tree.
• But Java allows only single inheritance. So are there other ways of
achieving more of the above advantages?
• Regarding having more code reusability, the answer is NO.
• However, regarding having more type sharing, the answer is YES. It is
possible for an object to be of a type outside its inheritance tree - This is
what interfaces are about.
Sahalu Junaidu Unit 03
33
What is an Interface? –Cont’d
• Interfaces are used to realize some of the advantages of multiple inheritance, while avoiding its complexity.
• For example, both GraduateStudent and Faculty might implement the Instructor interface.
• Interfaces only declare methods that objects must have but with no implementation - all methods are abstract.
• Interfaces differ from abstract classes in that:
– They cannot have implemented methods
– No constructors
– No instance variables except constants.
• Interface names are often adjectives, ending in -able.
examples: Colorable, Rotatable, Comparable, Runnable
• Interfaces that specify roles can be named with nouns.
examples: Container, Mover, Instructor
Sahalu Junaidu Unit 03
34
Interface Declaration Syntax• Interfaces are declared similar to classes, except "interface" is used instead of "class".
1. public interface Instructor{2. String getOfficeHours();3. Course[] getTeachingCourses();4. }
• All methods in an interface are automatically public and abstract.
• Thus, the above declaration is the same as the following:
1. public interface Instructor{2. public abstract String getOfficeHours();3. public abstract Course[] getTeachingCourses();4. }
Sahalu Junaidu Unit 03
35
Implementing Interfaces• A class implements an interface similar to the way it extends a superclass but using " implements" instead of "extends".
• A class can extend another class and at the same time implements one or more interfaces.
1. public class GraduateStudent extends Student implements Instructor{2. private String thesisTitle;3. private String officeHours;4. private Course[] teachingCourses;5. public GraduateStudent(int id, String name, double gpa, String title){6. super(id, name, workLoad);7. thesisTitle = title;8. }9. // ... other methods10. public String getOfficeHours(){11. return officeHours();12. }13. public Course[] getTeachingCourses(){14. return teachingCourses;15. }16. }
Sahalu Junaidu Unit 03
36
Implementing Interfaces – Cont’d
• Note: although methods of an interface are automatically public, they must be specified as
such in the implementing class.
• If a class implements more than one interface, the interface names are separated by commas.
• What happens if a class does not define all the methods of an interface it claims to
implement?
• Same thing that happens if an abstract method of a superclass is not defined - the
implementing class is abstract.
• If a super class implements an interface, then all its subclasses are considered to
implement it too.
Sahalu Junaidu Unit 03
Unit 03 37
Using Interfaces as Types• Interfaces can be used as types of variables and parameters.
• For example, an object of GraduateStudent can be of type GraduateStudent, Student, Object or Instructor.
• Similarly, if Faculty is defined as shown below, then its instance can be of type Faculty, MonthlyEmployee, Employee, Instructor, Comparable, or Object.
• Thus, a method with the following header can accept both an object of Faculty or that of GraduateStudent.
Sahalu Junaidu
38
Interfaces and Inheritance• Like classes, interfaces can extend other interfaces
• For example, if we have a Container interface, we can extend it to have SearchableContainer interface.
1. public interface Container{2. void add(Object o);3. int getCount();4. boolean isEmpty();5. boolean isFull();6. void purge();7. }
1. public interface SearchableContainer extends Container{2. boolean isMember(Object object);3. void remove(Object object);4. }
• Unlike classes, interfaces can extend any number of other interfaces
• This is because interfaces merely declare methods, but do not implement, so no collision can occur as in multiple inheritance.
Sahalu Junaidu Unit 03
40
Interfaces Cannot Grow
• It important to think through very well about the methods (and their signatures) when designing an interface.
• This is because Interfaces are like foundation to a building. To make changes, the whole building must be destroyed.
• If you add a single method to an interface or change the signature of a method, then all classes that implement the old Interface will break because they don't implement the interface anymore!
• The only solution in this case is to extend the interface.
Sahalu Junaidu Unit 03
41
Abstract Classes Versus Interfaces
Interfaces Abstract Classes
Defines a set of methods Models an object with properties and methods
Factors out common methods of potentially dissimilar objects
Factors out common properties and methods of similar objects
Does not implement its methods May implement some or all of its methods
A class can implement multiple interfaces
A class can extend only one abstract class
Sahalu Junaidu Unit 03
42
Exercises
Write each of the following:1. an interface, Instructor, which has two methods: String getOfficeHours() and
Course[ ] getTeachingCourses().2. a class, Course, with instance variables: courseCode, creditHours, and title; and
appropriate accessor, mutator and toString methods.3. a class Faculty that extends MonthlyEmpolyee and implements the Instructor
interface. It has two additional instance variables: String officeHourse and Course[] teachingCourses.
4. classes, Student and GraduateStudents as described in page 3 of the inheritance session.
5. a class, ReaseachAssistant, that extends GraduateStudent and implements the Instructor interface
6. A test class, TestInstructors, that has the following methods: void PrintTeachingDetails(Instructor i): that prints the office hours and teaching courses for i; and a main method, that creates instances of Faculty and ReasearchAssistant and prints their teaching details.
Sahalu Junaidu Unit 03
43
Polymorphism
• What is Polymorphism?
• Taking Advantage of Polymorphism
• Down-Casting
• Advantages of Polymorphism
Sahalu Junaidu Unit 04
44
What is Polymorphism?
• Polymorphism means many forms (it derives from the Greek words Poly,
meaning many, and Morphos, meaning form).
• In Java, the term is used in a number of ways.
• For example, we recall that a reference of type
superclass can be assigned an object of any of
its subclasses.
• Similarly, a reference of type a given interface can be assigned
an object of any class that implements the interface.
• These types of references are therefore called polymorphic
references - since they can take different forms.
Sahalu Junaidu Unit 04
45
What is Polymorphism? -Cont’d
• However, the polymorphism which we consider is this lecture, is
that which involves binding of method calls to particular methods.
• We explain this using an example.
• Recall our Shapes example discussed in the Abstract classes lecture.
Sahalu Junaidu Unit 04
46
What is Polymorphism? -Cont’d
• With these classes in mind, consider the following application and its output.
1. public class TestShapes{2. public static void main(String[] args){3. Shape[] shape = new Shape[3];4.5. shape[0] = new Rectangle(5, 10);6. shape[1] = new Square(10);7. shape[2] = new Circle(15);8.9. for(int i = 0; i<shape.length; i++){10. System.out.println("\n"+shape[i].name());11. System.out.println("Perimeter: "+shape[i].perimeter());12. System.out.println("Area: "+shape[i].area());13. }14. }15. }• The application creates each type of shape and prints its properties.
Sahalu Junaidu Unit 04
47
What is Polymorphism? -Cont’d
• First, we note that because the references (of type Shape) in the array, shape, are polymorphic, we are able to store all the three types of shapes in one array.
• Second, and the most important point, the same set of statements produced three different outputs.• for(int i = 0; i<shape.length; i++){
1. System.out.println("\n"+shape[i].name());
2. System.out.println("Perimeter: "+shape[i].perimeter());
3. System.out.println("Area: "+shape[i].area());
4. }
Sahalu Junaidu Unit 04
48
What is Polymorphism? -Cont’d
• How does the system know which area method to call from the statement,
shape[i].area(), given that the reference type is Shape?
• The answer, as far as Java Compiler is concerned is “I don’t know”. That is
this question cannot be answered at compilation time.
• It is only possible to answer this question after knowing the actual type of
object being referenced by the reference variable shape[i].
• The association of a method call to a particular method
is called binding, and Java exhibits what is called
run-time binding, also called dynamic binding or
late-binding.
Sahalu Junaidu Unit 04
49
What is Polymorphism? -Cont’d
• Java uses late-binding for all methods except those that are declared as
final.
• In other languages such as Pascal, binding is determined by the compiler.
Such languages are said to exhibit early or static binding.
• Since binding takes place at run-time in Java, it is possible to write code
that executes differently depending on the actual object.
• This behavior, whereby the same code executes differently, depending on
the object it acts on is what is called polymorphism.
Sahalu Junaidu Unit 04
50
Taking Advantage of Polymorphism
• Since binding takes place at run-time, it is possible to make a call to abstract methods, since by the time the code executes, the methods would have been implemented.• For example, we can modify the Shape class as follows:
1. public abstract class Shape{2. public String name(){3. return getClass().getName();4. }5. public abstract double area();6. public abstract double perimeter();7. public String toSring(){8. return name()+"\nPerimeter: "+perimeter()+"\nArea: "+area();9. }10. }
• Note that the toString method is calling the area and perimeter methods even though they are declared abstract.
Sahalu Junaidu Unit 04
51
Taking Advantage of Polymorphism – Cont‘d
• With this modification, the application can now be simplified as follows and it produces the same output as before:
1. public class TestShapes{
2. public static void main(String[] args){
3. Shape[] shape = new Shape[3];
4.
5. shape[0] = new Rectangle(5, 10);
6. shape[1] = new Square(10);
7. shape[2] = new Circle(15);
8.
9. for(int i = 0; i<shape.length; i++)
10. System.out.println(shape[i]);
11. }
12. }
• The println calls the toString method of the object. Since the method is not overridden in the subclasses, that of the super class is used.
• Due to polymorphism, the call to perimeter and area methods in toString method will be bound to those of the actual object.
Sahalu Junaidu Unit 04
52
Down-Casting
• We have seen that an object of a subclass can be assigned to a reference variable of type superclass –Up-casting
• A natural question to ask is, does Java allow the reverse?
• Assigning an object of a superclass to a reference of type subclass, called down-casting, can also be done, but it is considered to be a narrowing conversion and must be done with a cast.
• In fact down-casting is only advisable if the object being down-cast is
actually of the subclass type, which was up-cast to the superclass and now
being down-cast back to the subclass.Sahalu Junaidu Unit 04
53
Down-Casting –Cont’d• A good question now is, why would it be necessary to go through this circle of up-casting and then down-casting?
• To answer this question, we take the following example:1. import java.util.*;2. public class TestShapes2{3. public static void main(String[] args){4. Vector shape = new Vector(3);5. shape.add(new Rectangle(5, 10))6. shape.add(new Square(10));7. shape.add(new Circle(15));8. System.out.println("Shape\tArea");9. System.out.println("***************************");10. for(int i = 0; i<shape.size(); i++){11. Shape nextShape = (Shape)shape.get(i);12. System.out.println(nextShape.name()+"\t"+nextShape.area());13. }14. }}
Sahalu Junaidu Unit 04
54
Down-Casting –Cont’d
• In our example, if the method we want to call is not in the superclass Shape, then we still need to down-cast further.
• For example, suppose that the Circle class has an additional method, public double getRadius(), and we wish to call this method. Then we must down-cast the object returned by the get method to Circle.
• But how do we know that the actual object is of type Circle.
• Fortunately, Java has an operator, instaceof, which we can use to check the actual type of an object.1. for(int i = 0; i<shape.size; i++){2. Shape nextShape (Shape)shape.get(i);3. System.out.println(nextShape.name()+"\t"+nextShape.area());4. if(nextShape instanceOf Circle){5. Circle circle = (Circle)nextShape;6. System.out.println("Radius = "+circle.getRadius());7. }8. }
Sahalu Junaidu Unit 04
55
Down-Casting –Cont’d
• Although the Compiler will allow down-casting even if the actual object is not of type the subclass being down-cast to, a run-time error will result if the resulting reference is used to call a method that does not exists.
• To avoid this, it is advisable to always use the instanceof operator to check the type of objected before down-casting it.
1. Employee emp1 = new MonthlyEmployee("Sahalu Junaidu");2. if(emp1 instanceof HourlyEmployee){3. HourlyEmployee emp2 = (HourlyEmployee)emp1;4. emp2.addHours(60);5. }
Sahalu Junaidu Unit 04
56
Advantages of Polymorphism
• Extensibility: It allows the functionality of a
code to be extended. For example, if we define
another subclass of Shape, Triangle, then the
same code in our application can be used to
process Triangle shapes as well.
• To conclude, we take a quick look at the advantages of polymorphism
• Generic Code: Polymorphism allows us to write code that can be applied to
different types of objects and get different result based on the object. There
is no need to write separate code for each type.
Sahalu Junaidu Unit 04
57
Advantages of Polymorphism – Cont’d
• Readability: It is obviously more readable to have a statement like:
• Rather than:1. for(int i = 0; i<munShapes; i++){
2. switch(shapeType[i]){
3. 'c': System.out.println(circleArea()); break;
4. 's': System.out.println(squareArea()); break;
5. ...
6. }
7. }
• In fact any time you find yourself doing the later, it is a pointer to re-think your code. It probably could be made more Polymorphic.
Sahalu Junaidu Unit 04
58
Exercises
1(a). Write a class, Triangle, that extends Shape, and has three instance variable, side1, side2, side3. Implement the area and perimeter methods. Note: area = SQRT(s(s-side1)(s-side2)(s-side3)), where, s = perimeter/2.
(b). Write a class, TestShapes, that creates an instance of each of our shape classes and prints it.
2(a). Write an interface, Zakatable, that has a method getZakat() and a constant, ZAKAT_RATE= 0.025
(b).Write a class, IslamicBankAccount, that implements Zakatable. It has methods: deposit, withdraw, getBalance, and addDivident, which is used to add profit or loss to the account.
(c).Modify the Employee abstract class so that it implements Zakatable.
(d).Write a test class, that has two methods: void PrintZakat(Zakatable o) that prints the zakat from any zakatable object, o; and a main method that creates instances of MonthlyEmployee and IslamicBankAccount and print their zakat.
Sahalu Junaidu Unit 04
59
Packages
• What is a Package?
• Why use Packages?
• Creating a Package
• Naming a Package
• Using Package Members
• Managing Source and Class Files
• Visibility Modifiers
Sahalu Junaidu Unit 05
60
What is a Package?
• A package is a collection of related classes and interfaces that provides
access protection and namespace management.
• The classes in Java API are organized into packages. For example:
• Applet classes are in java.applet package
• I/O classes are in java.io package
• GUI classes are in java.awt.
• You can also organize the classes you
create into packages and you should. Why?
Sahalu Junaidu Unit 05
61
Why use Packages?
• Easy to know where to find classes and interfaces that provide a
particular set of functions. –For I/O functions go to java.io package.
• Avoid conflict with class names in other packages.
Classes in different packages can have same name.
–A package provides a new namespace.
• You can allow classes within a package to have access to each other.
Sahalu Junaidu Unit 05
62
Creating a Package
• To create a package, you put a package statement at the top of each source file for the class or interface that belongs to the package.
• For example, suppose we want to create a package, graphics, to store our shape classes, namely, Shape, Circle, Rectangle, and Square.
• Then we should add the statement, package graphics; as the first statement in each of the source files.
1. public abstract class Shape{2. public String name(){3. return getClass().getName();4. }5. public abstract double area();6. public abstract perimter();7. public String toString(){8. return name()+"\nPerimeter: "+perimeter()+"\nArea: "+area();9. }10. }
Sahalu Junaidu Unit 05
63
Creating a Package-Cont’d
• The scope of the package statement is the entire source file,
so if source file contains more than one class or interface,
they all belong to the package specified by the package
statement.
• If package is not specified for a class or interface, then the
class or interface belongs to the default package, which is a
package that has no name.
Sahalu Junaidu Unit 05
64
Naming a Package
• By convention, packages are named using lower case letters.
• Dots are also used to group related packages together.
• For example, the packages: java.awt, java.io, java.lang, are named as such to
indicate that they all belong to Java API.
• Similarly, java.awt.color, java.awt.geom, java.awt.event, are named as such to
indicate that they all belong to a group of classes for programming GUI
applications.
• Notice that this grouping is for the human reader only. As far as the system is
concerned, the packages java.awt.color is completely independent of
java.awt.geom.
Sahalu Junaidu Unit 05
65
Naming a Package-Cont’d
• Within one organization, it is clear that packages can be used to avoid
conflict in class names. What about between different organizations?
• It is likely that two organizations working on similar projects may come up
with the same package names and probably common class names. Thus, a
user dealing with these two organizations may still face conflict.
• To avoid this, by convention, organizations use their reversed Internet
domain name in their package names, like: com.company.package
• We shall name our packages in this course starting with the prefix, ics201.
Example: ics201.graphics, ics201.lab01, etc.
Sahalu Junaidu Unit 05
66
Using Package Members
• To use a public package member (a class or
interface) from outside its package, you must
do one of the following:
o Refer to the member by its long name
o Import the package member, or
o Import the member's entire package.
• Each of these methods is appropriate for
different situations, as explained in the
following sections.
Sahalu Junaidu Unit 05
67
Referring to a Package Member by Full Name
• So far, our examples have referred to classes and interfaces by their simple names, such as Rectangle.
• You can use a package member’s simple name if:
– The code you are writing is in the same package as the member
– If the members package has been imported.
• However, if a member is from a different package and that package has not been imported, you must use the member’s fully qualified name: ics201.graphics.Rectangle
• To create an instance of the member we use:
ics201.graphics.Rectangle myRect = new ics201.graphics.Rectangle();
Sahalu Junaidu Unit 05
68
Importing a Package Member• To import a specific package member into the current file, put an import
statement at the beginning the file before any class or interface definitions but after the package statement, if there is one.
1. package ics201.lab02;2. import ics201.graphics.Shape;3. import ics201.graphics.Rectangle;4. import ics201.graphics.Square;5. import ics201.graphics.Circle;
6. public class TestShapes{7. public static void main(String[] args){8. Shape[] shapes = new Shape[2];9. shape[0] = new Rectangle(5, 10);10. shape[0] = new Square(10);11.12. for(int i = 0; i<shape.length; i++)13. System.out.println(shape[i]);14. }15. }
• This approach is used if few members are needed from a package.
Sahalu Junaidu Unit 05
69
Importing an Entire Package
• To import all of the classes and interfaces contained in a particular package, use the asterisk (*).
1. package ics201.lab02;2. import ics201.graphics.*;3. public class TestShapes{4. public static void main(String[] args){5. Shape[] shape = new Shape[2];6. shape[0] = new Rectangle(5, 10);7. shape[0] = new Square(10);8.9. for(int i=0; i< shape.length; i++)10. System.out.println(shape[i]);11. }12. }
• As noted earlier, ics201 and ics201.graphics are independent packages, so the statement, import ics201.*; only imports ics201 package but not ics201.graphics.
Sahalu Junaidu Unit 05
70
Importing an Entire Package- Cont’d
• Also note that the asterisk cannot be used to match a subset of a package. For example, the following does not match all the classes in the graphics package that begin with a:
• For convenience, the Java runtime system automatically imports three entire packages:
o The default package (the package with no name)
o The java.lang package
o The current package
• What if two packages have classes with the same name and both packages are imported? -- You must use fully qualified names.
Sahalu Junaidu Unit 05
71
Managing Source and Class Files
• Declaring package names at the beginning of source files is what is required to create a package.
• However, for the Java system to locate your source and class files, you must store them in a directory whose name matches the name of their package.
• For example, the source code for the Rectangle class should be in a file, Rectangle.java, and must be in a directory, ics201\graphics. The ics201\graphics directory can be anywhere on the file system.
Sahalu Junaidu Unit 05
72
Managing Source and Class Files- Cont’d
• Note however, that the .class and .java files do not have to be in the same directory as shown below:
• Since the directory structure can be anywhere in the file system, it is obvious
that the package name alone does not provide a java tool, such as the
Compiler, with all the information need to locate a class.
• The balance of the information is provided by class path.
Sahalu Junaidu Unit 05
73
Managing Source and Class Files- Cont’d
• A class path is an ordered list of directories or jar files in which to search for class files.
• Each directory listed in the class path is a top-level directory in which package directories appear.
• For example, suppose that both .java and .class files for the ics201.graphics package are stored in the same directory. Suppose also that the directory structure for the package is in a directory z:\cs, as shown below, then we must add z:\cs to the class path:
Sahalu Junaidu Unit 05
74
Visibility Modifiers
• Now that we have learnt about packages, this is a good time to summarize what we learnt about visibility modifiers.
• Visibility modifiers are used to allow/deny access to other classes or interfaces.
• There are four of them, namely, public, private, and protected. The fourth, the default, does not have a keyword, but is assumed if none of the other three is specified.
Sahalu Junaidu Unit 05
75
Example
1. package package1;
2. public class A{
3. public A(){
4. System.out.println("Inside Class A");
5. }
6. int method1(int x){
7. return x*x;
8. }
9. public int method2(int x){
10. return method1(x) + method1(x);
11. }
12. }
Sahalu Junaidu Unit 05
76
Example (cont’d)1. package package2;
2. import package1.*;
3. public class B extends A{
4. public B(){
5. System.out.println("Inside Class B");
6. }
7. public int method1(int x){
8. A a = new B();
9. return a.method2(x);
10. }
11. public int method2(int x){
12. return x;
13. }
14. public static void main(String [] x){
15. B b = new B();
16. System.out.println(b.method1(3));
17. }
18. }Sahalu Junaidu Unit 05
77
Exercises
1. Add the statement: package ics202.graphics; to each of our shape classes, except TestShape. Store all the files in some root folder. Try compiling and running the TestShape class. What happens?
2. Create a folder, ics201\graphics, and store the shape files in it, except the TestShape class. Do not put any import statement in the TestShape. Try compiling and running TestShape. What happens?
3. Add the import statement, import ics201.graphics.*; to TestShape Try compiling and running TestShape without giving the class path for the ics201.graphics package. What happens?
4. Try compiling and running TestShape, giving the class path for the ics201.graphics package. It should compile and run successfully.
5. Try each of the methods of importing classes discussed in this session and the TestShape class.
6. Add the import statement; java.awt.*; What happens? How can this problem be resolved?
Sahalu Junaidu Unit 05
Unit 06 78
Java Virtual Machine (JVM)
• What is Java Virtual Machine?
• The Class Loader Subsystem
• Linkingo Verification
o Preparation
o Resolution
• Class Initialization
• Class Instantiation
Sahalu Junaidu
Unit 06 79
What is JVM• JVM is a component of the Java system that interprets and executes the
instructions in our class files.
• The following figure shows a block diagram of the JVM that includes its major subsystems and memory areas.
Sahalu Junaidu
Unit 06 80
What is JVM Cont’d
• Each instance of the JVM has one method area, one heap, and one or more stacks - one for each thread.
• When JVM loads a class file, it puts its information in the method area.
• As the program runs, all objects instantiated are stored in the heap.
• The stack area is used to store activation records as a program runs.
Sahalu Junaidu
Unit 06 81
The Class Loader Subsystem
• The class loader performs three main functions of JVM, namely: loading, linking and initialization.
• The linking process consists of three sub-tasks, namely, verification, preparation, and resolution, as shown by the following figure.
• These activities are performed in a strict order as shown by the figure.Sahalu Junaidu
Unit 06 82
Class Loading
• Loading means reading the class file for a type, parsing it to get its information, and storing the information in the method area.
• For each type it loads, the JVM must store the following kinds of information in the method area:
• The fully qualified name of the type
• The fully qualified name of the type's direct superclass or if the type is an interface, a list of its direct super interfaces .
• Whether the type is a class or an interface
• The type's modifiers ( public, abstract, final, etc)
• Constant pool for the type: constants and symbolic references.
• Field info : name, type and modifiers of variables (not constants)
• Method info : name, return type, number & types of parameters, modifiers, bytecodes, size of stack frame and exception table.
Sahalu Junaidu
Unit 06 83
Class Loading – Cont’d
• The end of the loading process is the creation of an instance of java.lang.Class for the loaded type.
• The purpose is to give access to some of the information captured in the method area for the type, to the programer.
• Some of the methods of the class java.lang.Class are:
1. public String getName()2. public Class getSupClass()3. public boolean isInterface()4. public Class[] getInterfaces()5. public Method[] getMethods()6. public Fields[] getFields()7. public Constructor[] getConstructors()
• Note that for any loaded type T, only one instance of java.lang.Class is created even if T is used several times in an application.
• To use the above methods, we need to first call the getClass method on any instance of T to get the reference to the Class instance for T.
Sahalu Junaidu
Unit 06 84
Class Loading –Cont’d
1. import java.lang.reflect.Method;2. //you must import your Circle class3. public class TestClassClass{4. public static void main(String[] args){5. Circle circle = new Circle(10);6. Class circleClassInfo = circle.getClass();7. System.out.println("Class name is :"+circleClassInfo.getName());8. System.out.println("Parent is :"+circleClassInfo.getSuperclass());9. Method[] methods = circleClassInfo.getMethods();10. System.out.println("\nMethods are: ");11. for(int i = 0; i<methods.length; i++)12. System.out.println(methods[i]);13. }14. }
Sahalu Junaidu
Unit 06 85
Class Loading – Cont’d• What if we do not have an object of a class T? Use the following.
Public static Class forName(String className) throws ClassNotFoundException
1. import java.lang.reflect.Method;2. public class TestClassClass{3. public static void main(String[] args) throws Exception {4. Class test = Class.forName("TestClassClass");5. System.out.println("\nClass name is: "+test.getName());6. System.out.println("Superclass is: "+test.getSuperclass());7. System.out.println("\nMethods are: ");8. Method[] methods = test.getMethods();9. for(int i = 0; i<methods.length; i++)10. System.out.println(methods[i]);11. }12. }
Sahalu Junaidu
Unit 06 86
Linking : Verification
• The next process handled by the class loader is Linking. This involves three sub-processes: Verification, Preparation and Resolution.
• Verification is the process of ensuring that binary representation of a class is structurally correct.
• The JVM has to make sure that a file it is asked to load was generated by a valid compiler and it is well formed.
• Class B may be a valid sub-class of A at the time A and B were compiled, but class A may have been changed and re-compiled.
• Example of some of the things that are checked at verification are:
– Every method is provided with a structurally correct signature.
– Every instruction obeys the type discipline of the Java language
– Every branch instruction branches to the start not middle of another instruction.
Sahalu Junaidu
Unit 06 87
Preparation
• In this phase, the Java virtual machine allocates memory for the class (i.e static) variables and sets them to default initial values.
• Note that class variables are not initialized to their proper initial values until the initialization phase - no java code is executed until initialization.
• The default values for the various types are shown below:
Sahalu Junaidu
Unit 06 88
Resolution• Resolution is the process of replacing symbolic names for types, fields and
methods used by a loaded type with their actual references.
• Symbolic references are resolved into a direct references by searching through the method area to locate the referenced entity.
• For the class below, at the loading phase, the class loader would have loaded the classes: TestClassClass, Circle, Shape, System, & Object.
1. public class TestClassClass{2. public static void main(String[] args){3. Circle circle = new Circle(10);4. Class circleClassInfo = circle.getClass();5. System.out.println("Parent is: "+circleClassInfo.getSuperclass());6. }7. }
• The names of these classes would have been stored in the constant pool for TestClassClass.
• In this phase, the names are replaced with their actual references.
Sahalu Junaidu
Unit 06 89
Class Initialization• This is the process of setting class variables to their proper initial values - initial values desired by the programer.
1. class Example1{
2. static double rate = 3.5;
3. static int size = 3*(int)(Math.random()*5);
4. ...
5. }
• Initialization of a class consists of two steps: – Initializing its direct superclass (if any and if not already initialized)– Executing its own initialization statements
• The above imply that, the first class that gets initialized is Object.• Note that static final variables are not treated as class variables but as constants and are assigned their values at
compilation.
1. class Example2{
2. static final int angle = 35;
3. static final int length = angle * 2;
4. ...
5. }
Sahalu Junaidu
Unit 06 90
Class Instantiation
• After a class is loaded, linked, and initialized, it is ready for use. Its static fields and static methods can be used and it can be instantiated.
• When a new class instance is created, memory is allocated for all its instance variables in the heap.
• Memory is also allocated recursively for all the instance variables declared in its super class and all classes up is inheritance hierarchy.
• All instance variables in the new object and those of its superclasses are then initialized to their default values.
• The constructor invoked in the instantiation is then processed according to the rules shown on the next page.
• Finally, the reference to the newly created object is returned as the result.
Sahalu Junaidu
Unit 06 91
Class Instantiation – Cont’d
• Rules for processing a constructor:
1. Assign the arguments for the constructor to its parameter variables.
2. If this constructor begins with an explicit invocation of another constructor
in the same class (using this), then evaluate the arguments and process that
constructor invocation recursively.
3. If this constructor is for a class other than Object, then it will begin with an
explicit or implicit invocation of a superclass constructor (using super).
Evaluate the arguments and process that superclass constructor
invocation recursively.
4. Initialize the instance variables for this class with their proper values.
5. Execute the rest of the body of this constructor.
Sahalu Junaidu
Unit 06 92
Example of Class Instantiation 11. class GrandFather{2. int grandy = 70;3. public GrandFather(int grandy){4. this.grandy = grandy;5. System.out.println("Grandy: "+grandy);6. }7. }8. class Father extends GrandFather{9. int father = 40;10. public Father(int grandy, int father){11. super(grandy);12. this.father = father;13. System.out.println("Grandy: "+grandy+" Father: "+father);14. }15. }16. class Son extends Father{17. int son = 10;18. public Son(int grandy, int father, int son){19. super(grandy, father);20. this.son = son;21. System.out.println("Grandy: "+grandy+" Father: "+father+" Son: "+son);22. }23. }24. public class Instantiation{25. public static void main(String[] args){26. Son s = new Son(65, 35, 5);27. }28. } Sahalu Junaidu
Unit 06 93
Example of Class Instantiation 21. class Super {2. Super() { printThree(); }3. void printThree() {4. System.out.println("three");5. }6. }7. class Test extends Super {8. int three = (int)Math.PI; // That is, 39. public static void main(String[] args) {10. Test t = new Test();11. t.printThree();12. }13. void printThree() {14. System.out.println(three);15. }16.}
Sahalu Junaidu
Unit 06 94
Exercises
1. Write a program to show that each loaded type has only one instance of java.lang.Class associated with it, irrespective of how many times it is used in a class.
2. Write a program to show that Loading may be caused either by creating an instance of a class or by accessing a static member.
3. Write a class to show that class variables are initialized with their default values when loaded. Also show that instance variables are initialized with their default values when an object is created.
4. Demonstrate that Verification actually takes place in the Loading process. To do this, write a class, Base, and a class, SubClass, that extends Base. Compile both classes. Then modify Base by changing the signature of one of its methods and compile it alone. Now write a test program that uses Subclass and try to compile and run it.
Sahalu Junaidu
Unit 07 95
Nested Classes
• Learning Outcomeso List and distinguish between the different categories of nested classes.
o List and explain four applications/benefits of nested classes.
o Use nested classes in applications development.
• Introduction
• static Member Classes
• Non-static Member Classes
• Local Classes
• Anonymous Classes
• Exercises
Sahalu Junaidu
Unit 07 96
Introduction to Nested Classes
• So far, our classes and interfaces were defined at top-level.
• These top-level classes and interfaces are grouped into packages.
• Classes in the same package are accessible to each other.
• With access modifiers, classes
can have inter-package access.
• Newer versions of Java
enable defining classes and
interfaces inside other classes.
Sahalu Junaidu
Unit 07 97
Introduction to Nested Classes (cont’d)
• There are four categories of nested classes in Java:
1. static member classes and interfaces.
2. Member classes
3. Local classes.
4. Anonymous classes.
• static member classes and interfaces are defined with the static
keyword.
• Member, local and anonymous classes are non-static, collectively called
inner classes.
• Member classes are defined inside a class while local and anonymous
classes are defined inside a block of Java code.
• We refer to both static and non-static classes as nested classes.Sahalu Junaidu
Unit 07 98
Nested Classes at a Glance
1 class OuterClass{ 2 static class StaticMemberClass { 3 // ... 4 } 5 static interface StaticMemberInterface{ 6 void f(); 7 } 8 class MemberClass { 9 // ...10 }11 public void myMethod(){12 class LocalClass {13 // ...14 }15 }16 public StaticMemberInterface myMethod2(){17 return new StaticMemberInterface(){18 public void f(){}19 };20 }21 }
Sahalu Junaidu
Unit 07 99
Why Nested Classes?
• Why does Java introduce nested classes?
• Nested classes provide additional support for:
1. Object-orientation.
o Separation of definition from functionality.
2. Code organization.
o Namespace control and access control
3. 'Multiple inheritance'.
o Multiple nested classes inheriting from many other classes.
4. Event-driven programming.
o Accessing private data of an enclosing class.
Sahalu Junaidu
Unit 07 100
static Member Classes
• A static member class (or interface) is defined as a static member of another class.
• static member classes are analogous to other static class members.
• Like a class method, a static member class is a top-level entity.
• A static member class has access to all
static members of its outer class.
• static member classes can be defined only
in top-level classes .
Sahalu Junaidu
Unit 07 101
Introducing Our Working Example
• Our working example involves a Course class containing students’ grades:
• There is an interface, MaxMin, with single method:
• The class implementing MaxMin must have access to the grades array.
• To return the best and worst grades, we may define two methods.• We define a class Pair that holds the best and worst grades.
Sahalu Junaidu
Unit 07 102
Example 1: static Member Classes
1 import java.util.*; 2 class Course1{ 3 private static double [] grades; 4 interface MaxMin{ void bestAndWorst();} 5 static class Pair implements MaxMin{ 6 private double best; 7 private double worst; 8 public String toString(){ 9 return "Best grade: "+best+"\nWorst grade: "+worst+"\n";10 }11 public void bestAndWorst(){12 if(grades.length > 0){13 best = grades[0];14 worst = grades[0];15 for(int i=1; i<grades.length; i++){16 if (best < grades[i]) best = grades[i];17 else if (worst > grades[i]) worst = grades[i];18 }19 }20 }21 }
Sahalu Junaidu
Unit 07 103
Example 1 (cont’d)
22 Course1(int size){23 grades = new double[size];24 for(int i=0; i<size; i++)25 grades[i] = 100*Math.random();26 }27 public MaxMin getPair(){28 return new Pair();29 }30 }31 public class Course1Test{32 public static void main(String [] args){33 Course1 c1 = new Course1(10);34 Course1.MaxMin cs = new Course1.Pair();35 cs.bestAndWorst();36 System.out.println(cs);37 }38 }
Sahalu Junaidu
Unit 07 104
Non-static Member Classes
• A member class is defined as a non-static member
of another class.
• A member class is analogous to an instance field or instance
method.
• Like other instance members, a member class can have any access
modifier.
• Every instance of a member class is linked with an instance of the
containing class.
• Member classes cannot have static fields, static methods or static
classes.
• Interfaces cannot be defined as member classes. Why?
Sahalu Junaidu
Unit 07 105
Example 2: Member Classes
1 protected class Pair implements MaxMin{ 2 public void bestAndWorst(){ 3 if(grades.length > 0){ 4 best = grades[0]; 5 worst = grades[0]; 6 for(int i=1; i<grades.length; i++){ 7 if (best < grades[i]) best = grades[i]; 8 else if (worst > grades[i]) worst = grades[i]; 9 }10 }11 }12 }13 public class Course2Test{14 public static void main(String [] args){15 Course2 c2 = new Course2(10);16 Course2.MaxMin cs = c2.new Pair();17 cs.bestAndWorst();18 System.out.println(cs);19 }20 }
Sahalu Junaidu
Unit 07 106
Example 3: Can We Override Member Classes
1 class Course3{ 2 public Course3(){ 3 System.out.println("Couse3 constructor."); 4 new Pair(); 5 } 6 protected class Pair { 7 public Pair(){ 8 System.out.println("Course3.Pair constructor."); 9 } }10 }11 class OverridingMemberClass extends Course3{12 public OverridingMemberClass(){13 System.out.println("OverridingMemberClass constructor.");14 }15 protected class Pair {16 public Pair(){17 System.out.println("OverridingMemberClass.Pair constructor."); }18 }19 public static void main(String [] args){20 new OverridingMemberClass();21 }22 }
Sahalu Junaidu
Unit 07 107
Example 3b: Inheriting Member Classes
1 class Course4{ 2 public Course4(){ 3 System.out.println("Course4 constructor."); 4 } 5 protected class Pair { 6 public Pair(){ 7 System.out.println("Course4.Pair constructor."); 8 } 9 void f(){10 System.out.println("Method f() From Course4.Pair.");11 }12 }13 }14 class InheritingMemberClass extends Course4{15 public InheritingMemberClass(){16 System.out.println("InheritingMemberClass constructor.");17 new Pair().f();18 }19 public static void main(String [] args){20 new InheritingMemberClass().new Pair();21 }22 }
Sahalu Junaidu
Unit 07 108
Using this Keyword in Member Classes
• The this reference is applicable inside member classes.
• From within an instance of a member class we can refer to two
objects.
• How do we distinguish the two objects?
• The next example demonstrates how this can be done.
– To refer to the outer class object, use the notation OuterClass.this
Sahalu Junaidu
Unit 07 109
Example 4: Keyword this in Member Classes
// code omitted
1 public void bestAndWorst(){ 2 if(Course2.this.grades.length > 0){ 3 this.best = Course2.this.grades[0]; 4 this.worst = Course2.this.grades[0]; 5 for(int i=1; i<grades.length; i++){ 6 if (best < grades[i]) best = grades[i]; 7 else if (worst > grades[i]) worst = grades[i]; 8 } 9 }10 }
// code omitted
Sahalu Junaidu
Unit 07 110
Review Exercises (cont’d)
3. Use appropriate examples to explain how nested classes provide
additional support for object orientation, code organization and
multiple implementation inheritance.
4. Can an interface be defined inside a member class? Give an
example or a counter example.
5. Compare and contrast static member classes and member classes.
6. Write a complete program to illustrate how to access object of an
outer class from an object of the inner class.
7. Let B be a member class inside another class A. Let another class
C extend B. Is it possible for class C to have a no-arg constructor?
Sahalu Junaidu
Unit 08 111
Introduction to GUI Programming
• Learning Outcomes
o Explain the motivation for, and usefulness of GUIs.
o List and explain seven principles of good GUI design and their benefits.
o Discuss what GUI programming involves, and explain how Java's GUI library evolved.
• Introduction to User Interfaces
• GUI Design Issues
• GUI Programming Issues
• Self-check Exercise
• Java GUI Library Evolution
• Exercises
Sahalu Junaidu
Unit 08 112
Introduction to User Interfaces
• A user interface (UI) is that part of a program that interacts with the user .
• A user interface can be based on text or graphics.
• In a text-based UI the commands are entered from the keyboard.
• In a graphical UI the user interacts with GUI objects.
• In a console program, the system usually
controls user actions.
• In GUI programs, the user controls the
behavior of the program.
• Thus, GUI programs give more control to the user.
Sahalu Junaidu
Unit 08 113
Principles of GUI Design
• Give time for GUI design and integration.
• Have a simple and clear layout.
• Use graphics objects and terminology
consistently.
• Be functionally intuitive and visually
attractive.
• Provide visual and audible feedback.
• Be responsive.
• Be flexible and customizable.
Sahalu Junaidu
Unit 08 114
Benefits of Good GUIs
• Facilitate higher user productivity and lower long-term costs.
• Improve integrity of underlying application.
• Improve the reliability and safety of mission-critical applications.
• Improve user confidence.
• Make software more marketable.
Sahalu Junaidu
Unit 08 115
GUI Programming Issues
• What do I need to know to write good GUI applications?
• Writing GUI applications requires knowledge of:
1. Graphics
2. Media
3. Windows
4. Events
5. Multithreading
Sahalu Junaidu
Unit 08 116
Java GUI API Evolution
• Java provides classes representing UI items like windows, buttons, menus etc.
• The GUI toolkit in older versions of Java is called AWT.
• An enriched version the toolkit, Swing, was developed in later versions of Java.
• AWT and Swing are part of the Java Foundation Classes (JFC).
• Why was Swing developed in addition to AWT?
Sahalu Junaidu
Unit 08 117
Java GUI API Evolution (cont'd)
• Programs using AWT components are multi-platform.
• However, GUI components in AWT are abstract and rely on native peers.
• By relying on native peers, AWT components are limited:
• slow on some platforms.
• portability problems.
• Unlike AWT, Swing components
are rendered and controlled by the JVM.
Sahalu Junaidu
Unit 08 118
Review Exercises
1. Explain the advantages of graphics-based over text-based user
interfaces.
2. What is a good and effective GUI? Why is it necessary to design GUI for
all on-trivial applications? Explain..
3. Explain the implications of good as well as badly designed GUIs.
4. What is JFC? What Swing? Why was the JFC enriched with Swing?
5. AWT components are said to be heavy weight while Swing
components are said to be light weight. Explain what these notions
mean.
6. Enumerate the major knowledge units that must be understood for
developing effective GUI applications. Briefly explain each of these
knowledge units.
Sahalu Junaidu
Unit 09 119
Java GUI Components and Events
Learning Outcomeso Distinguish between GUI components and containers.
o Identify and distinguish top-level containers from other containers.
o Write simple programs to add components into containers.
o Explain what Events are, and distinguish between Event sources, Event classes and Event listeners.
GUI Components and Containers Swing's Top-level Containers Adding Components to Containers Self-check Exercise 1 GUI Events GUI Events Classes Self-check Exercise 2 ExercisesSahalu Junaidu
Unit 09 120
Introduction to Components
• A component is an object having a graphical representation that can be displayed on the screen.
• Example of components in a typical GUI include:
• buttons, text boxes, lables and pop-up menus
Sahalu Junaidu
Unit 09 121
Introduction to Containers
A container is a special component that can hold other components.
• Example of containers in typical GUI applications include:o panels, windows, applets, frames
• Functionality of most GUI
components derive from the
Component and
Container classes.
Sahalu Junaidu
Unit 09 122
Swing’s Top-level Containers
• JApplet, JWindow, JFrame and JDialog are the top-level Swing
containers.
• Strictly speaking, JWindow and JFrame are the top-level containers.
• However, use top-level classes to refer to JApplet, JWindow, JFrame
and JDialog.
• A top-level container can be displayed without being added to another
container.
• Top-level containers are the only heavyweight Swing components.
• If you create an AWT window and add 3 buttons to it, AWT will
create four peers for you.
• Top-level containers do not behave exactly like other containers
Sahalu Junaidu
Unit 09 123
Anatomy of Top-level Containers
• Each top-level container has only one component, JRootPane.
• The root pane consists of three other containers: the layered, content and glass panes:
Sahalu Junaidu
Unit 09 124
Anatomy of Top-level Containers (cont’d)
• The root pane has a glass pane on top and a layered pane underneath.
• The glass pane component is
always painted last and appears
on top of the content pane and
menu bar.
• The layered pane consists of
a menu bar and a content pane.
• A content pane is a Container that covers the visible area
of a container.
• A content pane is automatically created for a newly created container.
• Components must be added to the content pane of a container.
• The content pane can be retrieved using the getContentPane method.
Sahalu Junaidu
Unit 09 125
Example 1: Creating Windows & Frames
1 import java.awt.*; import javax.swing.*; 2 public class TopLevelWindows{ 3 public static void main(String [] args){ 4 JFrame frame = new JFrame("My JFrame"); 5 frame.setLocation(100,100); 6 frame.setSize(300,300); 7 Container fcp = frame.getContentPane(); 8 JButton fb = new JButton("Draggable, Resizable Frame"); 9 fcp.add(fb);1011 JWindow window = new JWindow();12 window.setLocation(500,100);13 window.setSize(300,300);14 Container wcp = window.getContentPane();15 JButton wb = new JButton("Unmovable, No Frills Window");16 wcp.add(wb);1718 frame.setVisible(true);19 window.setVisible(true);20 }21 }
Sahalu Junaidu
Unit 09 126
Example 2: Adding Components to Containers
1 import java.awt.*; 2 import javax.swing.*; 3 public class AddingComponents extends JFrame{ 4 5 JButton button = new JButton("Press Me"); 6 JLabel label = new JLabel( "Running Total:"); 7 JTextField textField = new JTextField(10); 8 Container cp = getContentPane(); 910 public AddingComponents() {11 super("A Container With Components");12 setSize(300,100);13 cp.setLayout(new FlowLayout());14 cp.add(label);15 cp.add(textField);16 cp.add (button);17 setVisible(true);18 }19 public static void main(String args []) {20 new AddingComponents();21 }22 }
Sahalu Junaidu
Unit 09 127
Introduction to GUI Events
• We will now discuss how components and containers communicate.
• When a user interacts with a GUI component, events are triggered.
• An event is an action triggered by the user or by some other means.
• When an event is triggered an event object is created and delivered
to the event receivers.
• Execution of these kinds of programs is driven by users’ activation
of events.
• Event classes, event sources and event listeners are three groups of
Java classes crucial for event-driven programming.
Sahalu Junaidu
Unit 09 128
Events Classes Hierarchy• Event classes represent events and contain methods for getting information
on the events.
• Here is the class hierarchyfor events classes:
Sahalu Junaidu
Unit 09 129
Events Source Classes
• An event source is the component that generates an event.
• A source must register listeners who may wish to take some action
when the event is generated.
• When an event occurs the source informs all registered listeners for
this event.
• An event listener can register or unregister with the following
methods:
1. public void addTypeListener(TypeListener t)
2. public void removeTypeListener (TypeListener t)
• Type is the name of the event and t is a reference to the event
listener.
Sahalu Junaidu
Unit 09 130
Events Listener Classes
• The java.awt.event package contains interfaces and classes for dealing with events.
• Each listener interface is a specification for receiving a particular type of event.
• An event listener class implements the listener interfaces of interest to the class.
• Every event handler should satisfy these two conditions:
1. Implement an interface.
2. Register as event listener.
Sahalu Junaidu
Unit 09 132
Exercises
1. The Panel, Window and JComponent class each subclasses Component class.
Write down the similarities and differences between these classes in a tabular form.
2. Write down in tabular form the similarities and differences between top-level
components and other GUI components.
3. Write a Java program to display three frames as follows. The top-left corner of the
second frame should have the same coordinates as the bottom-right corner of the
first frame. Similarly, the top-left corner of the third frame should have the same
coordinates as the bottom-right corner of the second frame.
4. Run the program in Example 2. Try resizing the window and watch how the
components placements change. Modify this program by adding four more buttons.
Remove the setSize method call and replace it with the call to the pack method.
Re-run the program and notice the output.
5. Write short notes on
a. Event classes
b. Event sources
c. Event listeners
Sahalu Junaidu
Unit 10 133
Event-Driven Programming
• Learning Outcomeso Extend the example programs to write more interesting GUI
o Use nested classes and adapter classes to write medium-sized applications.
• Example 1: Handling Button Events
• Example 2: Handling Mouse Events
• Example 3: Handling Keyboard Events
• Self-check Exercise 1
• Adapter Classes
• Example 4: Handling Window Events
• Example 5: Handling Text Field Events
• Self-check Exercise 2
• Exercises
Sahalu Junaidu
Unit 10 134
Handling Button Events
• This example builds on Example 2 of the preceding section.
• Notice that when the button is pushed in that example, nothing happens.
• We will add some code to respond to the button pushes.
• When the mouse is pushed it generates and ActionEvent.
• Thus, we will be implementing the
corresponding ActionListener interface.
• ActionListener consists of the method:
Sahalu Junaidu
Unit 10 135
Example 1: Button Events 1 import java.awt.*; 2 import java.awt.event.*; 3 class ButtonEventTest extends AddingComponents 4 implements ActionListener{ 5 private int sum; 6 public ButtonEventTest() { 7 button.addActionListener(this); 8 } 9 public void actionPerformed(ActionEvent ae) {10 sum += 1;11 textField.setText(sum+"");12 Toolkit.getDefaultToolkit().beep();13 }14 public static void main(String args []) {15 new ButtonEventTest();16 }17 }
Sahalu Junaidu
Unit 10 136
Handling Mouse Events
• This example illustrates how mouse events can be responded to.
• It also shows how a single listener can register with many sources.
• The event listener in this case will implement the MouseListener
interface.
• MouseListener consists of five methods:
• The program is given in the following page.
Sahalu Junaidu
Unit 10 137
Example 2: Mouse Events 1 import java.awt.*; import java.awt.event.*; 2 public class MouseEventTest extends ButtonEventTest{ 3 public MouseEventTest(){ 4 class LightUpListener extends MouseAdapter { 5 public void mouseEntered(MouseEvent e) { 6 Component c = (Component)e.getSource(); 7 c.setBackground(Color.green); 8 } 9 public void mouseExited(MouseEvent e) {10 Component c = (Component)e.getSource();11 c.setBackground(Color.red);12 }13 }14 MouseListener listener = new LightUpListener();15 button.addMouseListener(listener);16 textField.addMouseListener(listener);17 cp.addMouseListener(listener);18 }19 public static void main(String[] args) {20 new MouseEventTest();21 }22 }Sahalu Junaidu
Unit 10 138
Handling Keyboard Events
• This example illustrates how keyboard events can be responded to.
• To receive KeyEvent, a component must have keyboard focus.
• We will be implementing the KeyListener interface.
• KeyListener consists of three methods:
• Notice that when you press a key, at least two events are generated.
Sahalu Junaidu
Unit 10 139
Example 3: Keyboard Events
1 import java.awt.*; import java.awt.event.*; 2 import javax.swing.JApplet; 3 public class KeyEventTest extends JApplet implements KeyListener{ 4 private String msg = ""; 5 private int startX = 10, startY = 10; 6 public void keyPressed(KeyEvent ke){ 7 showStatus("Key Down"); 8 } 9 public void keyReleased(KeyEvent ke){showStatus("Key Up"); }10 public void keyTyped(KeyEvent ke){11 msg += ke.getKeyChar();12 repaint();13 }14 public void init(){15 requestFocus();16 addKeyListener(this);17 }18 public void paint(Graphics g){19 g.drawString(msg,startX,startY);20 }21 }
Sahalu Junaidu
Unit 10 140
Introduction to Adapter Classes
• From previous examples, listener interfaces can have several
methods.
• A particular listener may not be
interested in all the methods.
• Nevertheless, the listener must implement
all methods in the interface.
• Java provides adapter classes for
implementing handlers selectively.
• Adapter classes provide empty implementations for the handlers.
• Most listener interfaces with two or more methods have matching
adapter classes.
Sahalu Junaidu
Unit 10 141
Handling Window Events
• This example shows how window events can be handled.
• The listener should implement the WindowListener interface.
• WindowListener consists of seven methods:
• We will extend the corresponding WindowAdapter in this example.
Sahalu Junaidu
Unit 10 142
Example 4: Window Events 1 import javax.swing.*;import java.awt.event.*; 2 class WindowEventTest extends JFrame{ 3 private String msg = "Are you sure you want to Quit Window?"; 4 public WindowEventTest() { 5 super("Window Event Test"); setSize(300,300); 6 addWindowListener(new WindowAdapter(){ 7 public void windowClosing(WindowEvent we) { 8 WindowEventTest obj = WindowEventTest.this; 9 int result = JOptionPane.showConfirmDialog(obj, msg);10 if (result == JOptionPane.YES_OPTION)11 System.exit(0);12 else {13 int keepOpen = WindowConstants.DO_NOTHING_ON_CLOSE;14 setDefaultCloseOperation(keepOpen);15 }16 }});17 }18 public static void main(String args [] ) {19 WindowEventTest wt = new WindowEventTest();20 wt.setVisible(true);21 }22 }Sahalu Junaidu
Unit 10 143
Handling Text Field Events
• This example shows how texfield events are generated and handled.
• It also illustrates the use of multiple handlers.
• Two text fields are shown handling an ActionEvent in different ways.
• The program implements Celcius to Fahrenheit temperature conversions.
• You enter a temperature value in one text
field and get the
equivalent in the other.
• The complete program follows in the next page.
Sahalu Junaidu
Unit 10 144
Example 5: Text Field Events
1 import java.awt.*; 2 import java.awt.event.*; 3 import javax.swing.*; 4 class TextFieldEventTest extends JFrame{ 5 JTextField celcius = new JTextField(10); 6 JTextField fahrenheit = new JTextField(10); 7 Container c = getContentPane(); 8 TextFieldEventTest(){ 9 c.setLayout(new FlowLayout());10 c.add(new JLabel("Celcius"));11 c.add(celcius);12 celcius.addActionListener(new ActionListener() {13 public void actionPerformed(ActionEvent ae){14 String cString = celcius.getText();15 double cValue = Double.parseDouble(cString.trim());16 double fValue = cValue*9.0/5.0+32.0;17 fahrenheit.setText((int)fValue+"");18 }19 });// code continues next page
Sahalu Junaidu
Unit 10 145
Text Field Events – Cont’d
20 c.add(new JLabel("Fahrenheit"));21 c.add(fahrenheit);22 fahrenheit.addActionListener(new ActionListener() {23 public void actionPerformed(ActionEvent ae){24 String fString = fahrenheit.getText();25 double fValue = Double.parseDouble(fString.trim());26 double cValue = (fValue-32.0)*5.0/9.0;27 celcius.setText((int)cValue+"");28 }29 });30 } // end of constructor31 public static void main(String [] args){32 TextFieldEventTest t = new TextFieldEventTest();33 t.pack();34 t.show();35 }36 }
Sahalu Junaidu
Unit 10 146
Review Exercises
1. Extend Example 1 by adding a Reset Total button. When the
Reset Total button is pushed, the running total should be reset to
zero.
2. Modify the program in Example 2 to work as a stand-alone application.
3. Modify the program in Example 3 to display its output on the
application’s JFrame window.
4. Modify the program in Example 4 to use an anonymous inner class to
implement the windowClosing() handler method.
5. Extend Example 5 to validate the data entered in both text fields to avoid
the spurious exceptions currently raised when invalid characters are
included in the input.
Sahalu Junaidu
Unit 10 147
Review Exercises (cont’d)
6. A student has written a working applet. Write a step-by-step procedure
that guides the student to make his applet work as an application also.
7. Consider the program in Example 1. Write down all the events
generated from the time the frame is displayed up to the time the user
pushes the PushMe button. You may restrict your answer to the events
covered in this section.
Sahalu Junaidu
Unit 11 148
GUI Layout Managers
• Learning Outcomeso List and distinguish between the four most common, standard layout
managers in Java.
o Use these and other layout managers to build good GUI applications.
• Introduction
• FlowLayout Manager
• GridLayout Manager
• Self-check Exercise 1
• BorderLayout Manager
• GridBagLayout Manager
• Self-check Exercise 2
• Exercises
Sahalu Junaidu
Unit 11 149
Introduction to GUI Layout Managers
• A layout manager determines the placement of components with a container.
• Each container has a default layout manager.
• A new layout manager can be installed using the setLayout method.
• Each layout manager implements
one of the two interfaces:
LayoutManger or LayoutManger2.
• Here are some common standard
layout managers of Java:
o FlowLayout
o GridLayout
o BorderLayout
o GridBagLayout
Sahalu Junaidu
Unit 11 150
Introduction to Flow Layout
• FlowLayout places components sequentially from left to right in the order added.
• Components placement depends on the current size of the container.
• When the container is resized the components are automatically repositioned.
• FlowLayout is the default layout
for panels.
• FlowLayout has three constructors:
o FlowLayout()
o FlowLayout(int align)
o FlowLayout(int align, int hgap, int vgap)
Sahalu Junaidu
Unit 11 151
Example 1: Flow Layout Test 1 import javax.swing.*; 2 class TestFlowLayout extends JFrame{ 3 JPanel panel = new JPanel(); 4 public TestFlowLayout(){ 5 panel.add(new JButton("1")); 6 panel.add(new JButton("2")); 7 panel.add(new JButton("3")); 8 panel.add(new JButton("4")); 9 panel.add(new JButton("5"));10 panel.add(new JButton("6"));11 panel.add(new JButton("7"));12 setContentPane(panel);13 setSize(300,300);14 setTitle("Flow Layout Test");15 setVisible(true);16 }17 public static void main(String [] args){18 new TestFlowLayout();19 }20 }
Sahalu Junaidu
Unit 11 152
Introduction to Grid Layout
• GridLayout places components in a rectangular grid.
• GridLayout is good for laying out containers that look like grids.
• GridLayout forces occupation of all available container space.
• GridLayout has three constructors:
o GridLayout()
o GridLayout(int rows, int cols)
o GridLayout(int rows, int cols, int hgap, int vgap)
Sahalu Junaidu
Unit 11 153
Example 2: Grid Layout Test
1 import java.awt.*; import javax.swing.*; 2 import javax.swing.border.*; 3 class TestGridLayout extends TestFlowLayout{ 4 public TestGridLayout(){ 5 panel.add(new JButton("8")); 6 panel.add(new JButton("9")); 7 panel.add(new JButton("*")); 8 panel.add(new JButton("0")); 9 panel.add(new JButton("#"));10 JLabel jlb = new JLabel("03-860-4698", SwingConstants.CENTER);11 Border b =BorderFactory.createBevelBorder(BevelBorder.RAISED);12 jlb.setBorder(BorderFactory.createTitledBorder(b,"Telephone"));13 panel.add(jlb);14 setTitle("Grid Layout Test");15 panel.setLayout(new GridLayout(0,3));16 setVisible(true);17 }18 public static void main(String [] args){19 new TestGridLayout();20 }21 }
Sahalu Junaidu
Unit 11 154
Introduction to Border Layout
• BorderLayout places components according to five areas:
"North", "South", "East", "West" and "Center".
• When you enlarge a container the center area grabs as much
of the new space as possible.
• BorderLayout is good for maintaining a row of buttons in one
of the areas near the edgees.
• BorderLayout has two constructors:
o BorderLayout()
o BorderLayout(int hgap, int vgap)
Sahalu Junaidu
Unit 11 155
Example 3: Border Layout Test
1 import java.awt.*; import javax.swing.*; 2 public class TestBorderLayout extends TestGridLayout{ 3 public TestBorderLayout() { 4 setTitle("Border Layout Test."); 5 JPanel jp1 = (JPanel)getContentPane(); 6 JPanel jp2 = new JPanel(); 7 jp2.setLayout(new BorderLayout()); 8 9 jp2.add(new JButton("NORTH"), "North");10 jp2.add(new JButton("WEST"), "West");11 jp2.add(new JButton("EAST"), "East");12 jp2.add(new JButton("SOUTH"), "South");1314 jp2.add(jp1);15 setContentPane(jp2);16 setVisible(true);17 }18 public static void main(String args [] ) {19 new TestBorderLayout();20 }21 }
Sahalu Junaidu
Unit 11 156
Exercises
1. Move the call to the setVisible() method from the main() method to the TetFlowLayout constructor in Example 1. Then compile and run each of Examples 2, 3 and 4. You will notice some changes when displaying the frames. Explain.
2. Modify Example 2 to add two other types of borders to it.3. Compare Example 2 and Example 3. In Example 2 we inherited a panel, added
more components to it and then changed the panel’ÿ layout manager. In Example 3 we had to create an additional panel. Can Example 3 be written in similar manner to Example 2 without the additional panel? If it is possible, write the equivalent program otherwise explain why it is not possible.
4. Change the fill constraint variable on Line 13 from BOTH to each of the following: NONE, HORIZONTAL and VERTICAL. Run the program in each case and study the effect.
Sahalu Junaidu
Unit 12 157
Further GUI Programming
• Learning Outcomeso Extend examples presented to write more useful applications.
o Write non-trivial, event-driven GUI applications.
• Introduction
• Example 1: Enhancing the Telephone Handset Example
• Example 2: Menu Test
• Self-check Exercise 1
• Example 3: File Dialog Test
• Example 4: Popup Menu Test
• Self-check Exercise 2
• Exercises
Sahalu Junaidu
Unit 12 158
Introduction
• This is our concluding session on GUIs and event-driven programming.
• In our discussion on GUI-based programs so far, we have covered:
– GUI design issues, GUI components and containers.
– Basic event handling.
– Basic layout management.
• We now cover typical GUI elements found in Windows environment including:
– Menus and pop-up menus
– File dialogs
– Mnemonics and keyboard accelerator
• With this coverage the student's knowledge base of the basics would
• be broadened.
Sahalu Junaidu
Unit 12 159
Introduction to Example 1
• This example builds on Example 4 of the preceding section.
• Example 4 of the preceding section developed a simple GUI for a
telephone handset.
• We will now add event-handling code to display typed numbers.
• Here is a sample output of the program:
Sahalu Junaidu
Unit 12 160
Example 1: The Telephone Handset
1 import java.awt.*; import javax.swing.*; import java.awt.event.*; 2 class TelephoneTest extends TestGridBagLayout 3 implements ActionListener{ 4 public TelephoneTest(){ 5 Component components[] = getContentPane().getComponents(); 6 JPanel cancelPanel = (JPanel)components[13]; 7 JButton cancel = (JButton)cancelPanel.getComponent(0); 8 for(int i=0;i<components.length; i++){ 9 if(components[i] instanceof JButton)10 ((JButton)components[i]).addActionListener(this);11 }12 cancel.addActionListener(this);13 }14 public void actionPerformed(ActionEvent ae) {15 if (ae.getActionCommand().equals("Cancel"))16 display.setText("");17 else18 display.setText(display.getText()+ae.getActionCommand());19 }20 public static void main(String [] args){21 new TelephoneTest().setVisible(true);22 }}
Sahalu Junaidu
Unit 12 161
Introduction to Example 2
• In this example we demonstrate how menus, separator,
mnemonic and accelerators can be added into an
application.
• The output of the example is as follows:
Sahalu Junaidu
Unit 12 162
Class Hierarchy for Menus
• Classes used to define menus are:
o JMenuBar
o JMenuItem
o JMenu
o JCheckButtonMenuItem
o JRadioButtonMenuItem
Sahalu Junaidu
Unit 12 164
Example 2: Menus and Mnemonics
1 import java.awt.event.*; 2 import javax.swing.*; 3 class MenuTest extends JFrame { 4 private JMenuBar menuBar = new JMenuBar(); 5 protected JMenu fileMenu = new JMenu("File"); 6 protected JMenuItem neW, open, quit, save, print; 7 private JMenuItem saveCurrent, saveAs, saveAll; 8 MenuTest(String title){ 9 super(title);10 setJMenuBar(menuBar);11 menuBar.add(fileMenu);12 fileMenu.setMnemonic('F');13 fileMenu.add(neW = new JMenuItem ("New"));14 fileMenu.add(open = new JMenuItem ("Open"));15 open.setMnemonic('o');16 fileMenu.add(save = new JMenu ("Save"));17 save.add(saveCurrent = new JMenuItem ("Save Current"));18 save.add(saveAs = new JMenuItem ("Save As"));19 save.add(saveAll = new JMenuItem ("Save All"));20 fileMenu.add(save);21 fileMenu.add(print = new JCheckBoxMenuItem ("Print"));22 fileMenu.addSeparator();
Sahalu Junaidu
Unit 12 165
Menus and Mnemonics (cont’d)
23 fileMenu.add(quit = new JMenuItem("Quit"));24 quit.setMnemonic(KeyEvent.VK_Q);25 quit.setAccelerator(26 KeyStroke.getKeyStroke(KeyEvent.VK_Q,KeyEvent.CTRL_MASK));27 quit.addActionListener(new ActionListener(){28 public void actionPerformed(ActionEvent e){29 int result=JOptionPane.showConfirmDialog(MenuTest.this,30 "Quit/Close Menu Demos Window?");31 if (result == JOptionPane.YES_OPTION)32 System.exit(0);33 }34 });35 setSize(300,300);36 }37 public static void main(String args[]){38 MenuTest t = new MenuTest("Menus Test");39 t.setVisible(true);40 }41 }
Sahalu Junaidu
Unit 12 166
Introduction to Example 3
• This example extends Example 2 to launch a file dialog on selecting
the Open menu.
• The selected file name is simply printed on another display window.
• The output is as follows:
Sahalu Junaidu
Unit 12 167
Example 3: File Dialog Test
1 import java.awt.*; 2 import java.awt.event.*; 3 import javax.swing.*; 4 class FileDialogTest extends MenuTest { 5 JEditorPane textPane= new JEditorPane(); 6 FileDialogTest(String title){ 7 super(title); 8 open.addActionListener( new ActionListener() { 9 public void actionPerformed(ActionEvent e ) {10 FileDialog fd = new FileDialog(FileDialogTest.this);11 fd.setVisible(true);12 textPane.setText("Selected file: "+fd.getFile());13 } });14 getContentPane().add(textPane);15 }16 public static void main(String args[]){17 FileDialogTest t = new FileDialogTest("File Dialog Test");18 t.setVisible(true);1920 }21 }
Sahalu Junaidu
Unit 12 168
Introduction to Example 4
• This example extends Example 2 of the preceding section to add pop-up menus..
• The output looks like:
• The menu consists of three colors that can be used to reset a component’s background color.
Sahalu Junaidu
Unit 12 169
Example 4: Popup Menu Test
1 import java.awt.*; import java.awt.event.*; import javax.swing.*; 2 public class PopupMenuTest extends TestGridLayout{ 3 Component selectedComponent; 4 JPopupMenu colorMenu = new JPopupMenu(); 5 JMenuItem blue, white, yellow; 6 public PopupMenuTest(){ 7 setTitle("Popup Menu Test"); 8 colorMenu.add(blue=new JMenuItem("Blue")); 9 colorMenu.add(white=new JMenuItem("White"));10 colorMenu.add(yellow=new JMenuItem("Yellow"));11 Component components[] = getContentPane().getComponents();12 class MyListener extends MouseAdapter {13 public void mousePressed(MouseEvent e){checkPopup(e);}14 public void mouseClicked(MouseEvent e){checkPopup(e);}15 public void mouseReleased(MouseEvent e){checkPopup(e);}16 public void checkPopup(MouseEvent e) {17 if (e.isPopupTrigger()){18 selectedComponent = e.getComponent();19 colorMenu.show(e.getComponent(),e.getX(),e.getY());20 }21 }22 }
Sahalu Junaidu
Unit 12 170
Popup Menu Test (cont’d)
23 MouseListener mylistener = new MyListener();24 for(int i=0;i<components.length-1; i++){25 JButton b = (JButton)components[i];26 b.addMouseListener(mylistener);27 }28 blue.addActionListener(new ActionListener () {29 public void actionPerformed(ActionEvent ae){30 selectedComponent.setBackground(Color.blue);31 }});32 white.addActionListener(new ActionListener() {33 public void actionPerformed(ActionEvent ae){34 selectedComponent.setBackground(Color.white);35 }});36 yellow.addActionListener(new ActionListener() {37 public void actionPerformed(ActionEvent ae){38 selectedComponent.setBackground(Color.yellow);39 }});40 }41 public static void main(String[] args) {42 new PopupMenuTest().setVisible(true);43 }44 }
Sahalu Junaidu
Unit 12 171
Review Exercises
1 What are the event sources and event listeners in Example 1?2 Can the event handler in Example 1 be implemented in a single anonymous
class? If not, why not?3 Modify Example 1 to use two inner classes instead of one. Can the two inner
classes both be anonymous? Is the program with one inner class better than the one with two? Explain.
4 Enhance Example 1 so that when the Redial button is pushed the last text displayed on the text component is displayed again.
5 Write a Java program to illustrate how a component event can be handled. 6 Modify Example 3 so that when a file is double-clicked from the file dialog
indow the file is opened rather than displaying its name in the editor pane.7 When you run Example 4, you will find that the lower part of the window is not
responding to the popup menu. Modify this program to ensure that that part of the window also responds to the popup menu events like the buttons in the window.
Sahalu Junaidu
Unit 13 172
Introduction to Searching and Sorting
• Comparable Interface
• Comparator Interface
• Algorithm Complexity Classes
• Exercises
Sahalu Junaidu
Unit 13 173
The Comparable Interface
• The Comparable interface of java.lang
public interface Comparable{
public abstract int compareTo(Object object);
}
• This interface may be used to order objects of a class that have a natural ordering.
• Several core Java classes implement Comparable.
• A user defined class that implements Comparable should implement the compareTo method such that : object1.compareTo(object2) is:
0 if object1 “is equal to” object2
> 0 if object1 “is greater than” object2
< 0 if object1 “is less than” object2
Sahalu Junaidu
Unit 13 174
The Comparable Interface (cont’d)
• It is also preferable for object1.compareTo(object2) to return 0 if and only if object1.equals(object2) is true.
• The compareTo method throws a ClassCastException if the type of this object and the type of the object passed as parameter are not compatible for comparison.
• Example: 1. public class BankAccount implements Comparable{
2. private int accountNumber;
3. // . . .
4. public int compareTo(Object object){
5. BankAccount account = (BankAccount) object;
6. if(accountNumber < account.accountNumber)
7. return –;
8. else if(accountNumber == account.accountNumber)
9. return 0;
10. else
11. return 1;
12. }}
Sahalu Junaidu
Unit 13 175
The Comparable Interface (cont’d)
• Example:
Assuming that account1 and account2 are BankAccount objects, a typical call to the compareTo method is:
1. int comparisonResult = account1.compareTo(account2);
2. if(comparisonResult == 0)
3. System.out.println(“Same account”);
4. else
5. System.out.println(“Different accounts”);
• To define an ordering for objects that do not implement Comparable, or to define an ordering other than the natural ordering defined by Comparable, the java.util.Comparator interface should be used.
Sahalu Junaidu
Unit 13 176
The Comparator Interface
• The Java collection framework is a set of important utility classes and interfaces in the java.util package for working with collections.
• A collection is a group of objects.
• The Comparator interface is one of the collections framework interfaces.
• Comparator defines how collection objects are compared.
public interface Comparator{
public abstract int compare(Object object1, Object object2);
public abstract boolean equals(Object object);
}
• The Comparator interface is used when:
• the collection objects to be ordered do not have a natural ordering defined by the Comparable interface
• the objects are to be ordered by not using their natural ordering.
Sahalu Junaidu
Unit 13 177
The Comparator Interface (cont’d)
• A class that implements Comparator should implement the compare method such that its return value is:
0 if object1 “is equal to” object2
> 0 if object1 “is greater than” object2
< 0 if object1 “is less than” object2
• It is also preferable for the compare method to return 0 if and only if object1.equals(object2) is true.
• The compare method throws a ClassCastException if the type of object1 and that of object2 are not compatible for comparison.
• The equals method returns true if its parameter is a Comparator object and if it uses the same ordering as the invoking Comparator object; otherwise it returns false.
Sahalu Junaidu
Unit 13 178
The Comparator Interface (cont’d)
• Note: Since each class inherits the equals method from the Object class, it is not necessary for a class that implements the Comparator interface to implement the equals method.
• Example: The reverse Comparator for strings
1. import java.util.*;
2. public class StringReverseComparator implements Comparator{
• 3. public int compare(Object object1, Object object2){
• 4. String string1 = object1.toString();
• 5. String string2 = object2.toString();
• 6. // Reverse the comparison
• 7. return string2.compareTo(string1);
• 8. }
• 9. }
Sahalu Junaidu
Unit 13 179
The Comparator Interface (cont’d)
import java.util.*; class BankAccount implements Comparable{
private int accountNumber;protected String name; private double balance;// . . .public int compareTo(Object object){ BankAccount account = (BankAccount) object;if(accountNumber < account.accountNumber)
return -1;else if(accountNumber == account.accountNumber)
return 0;else
return 1;}public String toString(){
return "Account#: " + accountNumber + " , Name: " + name + " , Balance: " + balance + " SR";}
Sahalu Junaidu
Unit 13 180
Example 1: The Comparator Interface
1 import java.util.*; 2 class MyComparator implements Comparator { 3 public int compare(Object obj1, Object obj2) { 4 int i1 = ((Integer)obj1).intValue(); 5 int i2 = ((Integer)obj2).intValue(); 6 return Math.abs(i2) - Math.abs(i1); 7 } 8 } 9 public class TestCollections {10 public static void main(String args[]) {11 ArrayList array = new ArrayList();12 array.add(new Integer(-200));13 array.add(new Integer(100));14 array.add(new Integer(400));15 array.add(new Integer(-300));16 Collections.sort(array);17 System.out.println("Natural ordering: " + array);18 Collections.sort(array, new MyComparator());19 System.out.println("My own ordering : " + array);20 }21 }
Sahalu Junaidu
Unit 13 181
The Comparator Interface (cont’d)
1 A Comparator for BankAccount objects2 class MyComparator implements Comparator{3 public int compare(Object object1, Object object2){4 BankAccount account1 = (BankAccount) object1;5 BankAccount account2 = (BankAccount)object2;6 String string1 = account1.name;7 String string2 = account2.name;8 // Reverse the comparison9 return string2.compareTo(string1);10 }11 }
Sahalu Junaidu
Unit 13 182
Algorithm Complexity Classes
• Different algorithms require different amount of running time and space.
• The less amount of running time the more time-efficient the algorithm.
• The less amount of space requirements the more space-efficient the algorithm.
• The resources (such as time and space) required to solve a problem usually increase with an increase in the size n of the problem.
• Several factors affect the time and space requirements of an algorithm: hardware, language of implementation, Compiler being used, etc.
• The average running time of an algorithm is a function f(n) of the problem size n.
• Algorithms are classified into different groups (called complexity classes) based on f(n)
Sahalu Junaidu
Unit 13 184
Exercises
1. Write a Comparator to compare names by last name.
2. Write a Comparator to compare names by middle name. Assume that each name to be compared, consists of three names: first, middle, and last.
3. Arrange algorithm complexity classes from the most time-efficient to the least time-efficient.
Sahalu Junaidu
Unit 14 185
Searching and Sorting
• Linear Search
• Binary Search
• Selection Sort
• Insertion Sort
• Bubble (or Exchange) Sort
• Exercises
Sahalu Junaidu
Unit 14 186
Linear Search• Searching is the process of determining whether or not a given value exists in
a data structure or a storage media.
• We discuss two searching methods on one-dimensional arrays: linear search and binary search.
• The linear (or sequential) search algorithm on an array is:– Sequentially scan the array, comparing each array item with the searched value.
– If a match is found; return the index of the matched element; otherwise return –1.
• The algorithm translates to the following Java method:public static int linearSearch(Object[] array, Object key){
for(int k = 0; k < array.length; k++)
if(array[k].equals(key))
return k;
return -1;
}
• Note: linear search can be applied to both sorted and unsorted arrays.
Sahalu Junaidu
Unit 14 187
Binary Search The binary search algorithm can only be applied to an array that
is sorted; furthermore, the order of sorting must be known. The binary search algorithm for an array sorted in ascending
order is:
– if(there are more elements in the current array){– Compare the current middle array element with key (the value searched for).– There are three possibilities:
• 1. key == array[middle]• the search is successful, return middle.• 2. key < array[middle]• binary search the current lower half of the array.• 3. key > array[middle]• binary search the current upper half of the array.
– }– the search is not successful; return –1
Sahalu Junaidu
Unit 14 188
Binary Search (cont’d) The algorithm translates to the following Java method:public static int binarySearch(Object[] array, Object key, Comparator comparator){
return binarySearch(array, key, 0, array.length - 1, comparator);}private static int binarySearch(Object[] array, Object key, int low, int high, Comparator comparator){
if(low > high) return -1;else{ int middle = (low + high)/2; int result = comparator.compare(key, array[middle]); if(result == 0) return middle; else if(result < 0) return binarySearch(array, key, low, middle - 1, comparator); else return binarySearch(array, key, middle + 1, high, comparator);}
}
Sahalu Junaidu
Unit 14 189
Selection Sort• We discuss five sorting algorithms on one-dimensional arrays.
• Sorting is the process of arranging data in a data structure or a storage media such that it is in increasing or decreasing order of some key in the date.
• The pseudo-code for Selection sort algorithm to sort an array in increasing is:
selectionSort(array){
for(k = 0; k < array.length – 1; k++){
select the minimum element among array[k]...array[array.length – 1];
swap the selected minimum with x[k];
}
}
• To sort an array in decreasing order, the maximum element is selected in each iteration (or pass) of the algorithm.
Sahalu Junaidu
Unit 14 190
Selection Sort (cont’d) public static void selectionSort(Object[] array, Comparator comparator){
int minPos = 0;
Object temp;
for(int i = 0; i < array.length - 1; i++){
minPos = i;
for(int k = i + 1; k < array.length; k++){
if(comparator.compare(array[k], array[minPos]) < 0)
minPos = k;
}
temp = array[minPos];
array[minPos] = array[i];
array[i] = temp;
}
}Sahalu Junaidu
Unit 14 191
Selection Sort (cont’d)
• To sort an array with k elements, Selection sort requires k – 1 passes.
• Example:
Sahalu Junaidu
Unit 14 192
Insertion Sort• The Insertion sort pseudo-code algorithm is:
insertionSort(array){
for(i = 1; i < array.length; i++){
temp = array[i];
insert temp in its proper location in the sorted subarray array[0]...array[i -1]
}
• Inserting temp in its proper location involves two steps:
• Finding the position k where temp is to be inserted.
• Shifting each of the elements array[k]...array[i -1] to the right
//inserting to maintain ascending order
temp = array[i];
k = i;
while(k > 0 && array[k - 1] > temp){
array[k] = array[k - 1];
k--;
}
array[k] = temp;
Sahalu Junaidu
Unit 14 193
Insertion Sort (cont’d) public static void insertionSort(Object[] array, Comparator
comparator){
int i,k;
Object temp;
for(i = 1; i < array.length ; i++){
temp = array[i];
k = i;
while((k > 0) && comparator.compare(array[k-1], temp) > 0){
array[k] = array[k-1];
k--;
}
array[k] = temp;
}
}Sahalu Junaidu
Unit 14 194
Insertion Sort (cont’d)
• To sort an array with k elements, Insertion sort requires k – 1 passes.
• Example:
Sahalu Junaidu
Unit 14 195
Bubble Sort• The Bubble (Exchange) sort pseudo-code algorithm is:
bubbleSort(array){
numberOfPasses = 1;
while(numberOfPasses < array.length){
for(k = 1; k <= array.length – numberOfPasses; k++)
swap array[k-1] and array[k] if they are out of order;
numberOfPasses++;
}
• Note: If no swaps occur in an iteration of the for loop, the array is sorted. A boolean variable may be used to terminate the while loop prematurely.
Sahalu Junaidu
Unit 14 196
Bubble Sort (cont’d)
public static void bubbleSort(Object[] array, Comparator comparator){
int pass = 1;
Object temp;
boolean sorted;
do{
sorted = true;
for(int m = 1; m <= array.length - pass; m++){
if(comparator.compare(array[m - 1], array[m]) > 0){
temp = array[m-1];
array[m-1] = array[m];
array[m] = temp;
sorted = false;
}
}
pass++;
}while(! sorted);
}
Sahalu Junaidu
Unit 14 197
Bubble Sort (cont’d)
• To sort an array with k elements, Bubble sort requires k – 1 passes.
• Example:
Sahalu Junaidu
Unit 14 198
Exercises on Searching1. What is a sequential search?
2. What is a binary search?
3. Write an iterative binarySearch method on an Object array.
4. Write a recursive binarySearch method on a double array.
5. Write a recursive linearSearch method on an Object array.
6. Write an iterative linearSearch method on a double array.
7. A binary search of an array requires that the elements be sorted in ascending order.
8. Suppose it is known that an array is sorted. When is linear search better than binary Search?
9. Mention the advantages, if any, of linear search over binary search.
10. Mention the advantages, if any, of binary search over linear search.
11. Mention the disadvantages, if any, of binary search over linear search.
12. Mention the disadvantages, if any, of linear search over binary search.
13. Design a Java program that will determine the average running times of binary search and linear
search on sufficiently large integer arrays.
14. Each line of a text file contains the name of a person and his/her telephone number:
firstName secondName telephoneNumber
The names may not be unique and may also not be sorted. The telephone numbers are also not sorted. Write a Java telephone lookup program that handles lookups by name as well as by telephone number. Use binary search for both lookups.
Sahalu Junaidu
Unit 14 199
Exercises on Searching (cont’d)
15. An integer array of size 100 stores contiguous integers. What is the minimum number of
comparisons to determine if:
(a) a value is in the array? (b) a value is not in the array?
16. The information of students taking two courses is maintained in two Object arrays, course1 and
course2. By defining an appropriate Student class, write a Java program to determine the
students who are:
(a) taking both courses. (b) not taking both courses.
17. The element being searched for is not in an array of 100 elements. What is the maximum number
of comparisons needed in a sequential search to determine that the element is not there if the
elements are:
(a) completely unsorted? (b) sorted in ascending order?
(c) sorted in descending order?
18. The element being searched for is not in an array of 100 elements. What is the average number
of comparisons needed in a sequential search to determine that the element is not there if the
elements are:
(a) completely unsorted? (b) sorted in ascending order?
(c) sorted in descending order?
Sahalu Junaidu
Unit 14 200
Exercises on Searching (cont’d)
19. Implement each of the following Java String search methods:
20. Write a linear search method:
public static Object linearSearch(Object[] array, Object key)
that returns null if the search is not successful; otherwise it returns a reference to the first matching object.
21. Write a binary search method:
21 public static Object binarySearch(Object[] array, Object key)
that returns null if the search is not successful; otherwise it returns a reference to the a matching object. Assume that the elements of the array are Comparable.
Sahalu Junaidu
Unit 14 201
Exercises on Searching (cont’d)
22. Consider the following array of sorted integers:
10, 15, 25, 30, 33, 34, 46, 55, 78, 84, 96, 99
Using binary search algorithm, search for 23. Show the sequence of array elements that are
compared, and for each comparison, indicate the values of low and high.
Sahalu Junaidu
Unit 14 202
Exercises on Sorting1. Write a method:
public static boolean isSorted(Object[] array, Comparator comparator)
that returns true if array is sorted; otherwise it returns false.
2. Write a recursive bubble sort on a double array.
3. Write a recursive insertion sort on a double array.
4. Write a recursive selection sort on an Object array of Comparable objects.
5. Many operations can be performed faster on sorted than on unsorted data. For which of the following operations is this the case?
(a) Finding an item with minimum value.
(b) Computing an average of values.
(c) Finding the middle value (the median).
(d) Finding the value that appears most frequently in the data.
(e) Finding the distinct elements of an array.
(f) Finding a value closest to a given value.
(g) Finding whether one word is an anagram (i.e., it contains the same letters) as another word.
(example: plum and lump).
6. Rewrite some of the sorting methods we have studied such that each sorts an Object array of Comparable objects.
7. Show the contents of the following integer array:
43, 7, 10, 23, 18, 4, 19, 5, 66, 14
when the array is sorted in ascending order using:
(a) bubble sort, (b) selection sort, (c) insertion sort.Sahalu Junaidu
Unit 14 203
Exercises on Sorting (cont’d)8. Implement an insertion sort on an integer array that in each pass places both the minimum and maximum elements in their proper locations.
9. In our implementation of bubble sort, an array was scanned top-down to bubble down the largest element. What modifications are needed to make it work bottom-up to bubble up the smallest element?
10. A cocktail shaker sort is a modification of bubble sort in which the direction of bubbling changes in each iteration: In one iteration, the smallest element is bubbled up; in the next, the largest is bubbled down; in the next the second smallest is bubbled up; and so forth. Implement this algorithm.
11. Explain why insertion sort works well on partially sorted arrays.
Sahalu Junaidu
Unit 15 205
Merge Sort• The merge sort algorithm to sort an array from index low to high:
if(high > low){
Split the array into two halves
merge sort the left half
merge sort the right half
merge the two sorted halves into one sorted array
}
• The above algorithm translates to the following pseudo-code:
mergeSort(array, low, high){
middle = (low + high) / 2;
mergeSort(array, low, middle);
mergeSort(array, middle + 1, high);
merge(array, low, middle, middle + 1, high);
}
Sahalu Junaidu
Unit 15 206
Merge Sort (cont’d)• Note that in a merge sort, the splitting and merging process are intermingled. However, we
can view merge sort as:• 1. Continually splitting the original array of size n until it has created n one element subarrays (each of which is a sorted subarray).
• 2. Adjacent sorted subarrays are then merged into larger and larger sorted subarrays, until the entire array is merged back.
• Example: merging two adjacent, sorted portions of an array
Sahalu Junaidu
Unit 15 207
Merge Sort (cont’d)
public static void mergeSort(Object[] array, Comparator comparator){
mergeSort(array, 0, array.length - 1, comparator);
}
private static void mergeSort(Object[] array, int low, int high,
Comparator comparator){
if(last > first){
int mid = (low + high)/2;
mergeSort(array, low, mid, comparator);
mergeSort(array, mid + 1, high, comparator);
merge(array, low, mid, mid + 1, high, comparator);
}
}
Sahalu Junaidu
Unit 15 208
Merge Sort (cont’d)private static void merge(Object[] array,int leftLowIndex, int leftHighIndex,int rightLowIndex, int rightHighIndex,
Comparator comparator){
int low = leftLowIndex;
int index = leftLowIndex;
Object[] tempArray = new Object[array.length];
while(leftLowIndex <= leftHighIndex && rightLowIndex <= rightHighIndex){
if(comparator.compare(array[leftLowIndex], array[rightLowIndex]) < 0)
tempArray[index++] = array[leftLowIndex++];
else tempArray[index++] = array[rightLowIndex++];
}
while(leftLowIndex <= leftHighIndex)
tempArray[index++] = array[leftLowIndex++];
while(rightLowIndex <= rightHighIndex)
tempArray[index++] = array[rightLowIndex++];
for(int k = low; k <= rightHighIndex; k++)
array[k] = tempArray[k];
}
Sahalu Junaidu
Unit 15 209
Merge Sort (cont’d)• A recursive-tree for merge
sorting an array x with 7
mergeSort(array, low, high){
if(high > low){
middle = (low + high) / 2;
mergeSort(array, low, middle);
mergeSort(array, middle + 1, high);
merge(array, low, middle, middle + 1, high);
}
}
Sahalu Junaidu
Unit 15 210
Quick Sort• The quick sort algorithm to sort an array from index low to high:
if(high > low){
1. Select a pivot element p to be used to partition the array into two partitions.
2. Scan through the array, moving all elements smaller than p to the lower partition,
and all elements equal to or greater than p to the upper partition.
3. Sort the low and upper partitions recursively using quick sort
}
• The above algorithm can be translated to the following pseudo-code: quickSort(array, low, high){
if(high > low){
select a pivotValue
partition the array so that:
array[low]...array[pivotIndex –1] < pivotValue
array[pivotIndex] = pivotValue
array[pivotIndex + 1]...array[high] >= pivotValue
quickSort(array, low, pivotIndex –1);
quickSort(array, pivotIndex + 1, high);
}
}
Sahalu Junaidu
Unit 15 211
Quick Sort (cont’d)
• Any array element can be selected as pivot; but ideally the pivot should be the median value.
• Quick sort is most efficient when the pivot is as close to the median as possible; otherwise the depth of recursion increases resulting in a decrease in efficiency.
• Computing median values in each partition degrades the performance of quick sort
• The Quick sort method is:public static void quickSort(Object[] array, Comparator comparator){
quickSort(array, 0, array.length - 1, comparator);
}
private static void quickSort(Object[] array, int low,int high, Comparator comparator){
if(low < high){
int pivotIndex = partition(array, low, high, comparator);
quickSort(array, low, pivotIndex - 1, comparator);
quickSort(array, pivotIndex + 1, high, comparator);
}
}
Sahalu Junaidu
Unit 15 212
Quick Sort (cont’d)private static int partition(Object[] array, int firstIndex,int lastIndex, Comparator comparator){
int middleIndex = (firstIndex + lastIndex)/2;
Object pivotValue = array[middleIndex];
/* Temporarily place pivotValue into first position of current partition */
swap(array, firstIndex, middleIndex);
int pivotIndex = firstIndex;
int index = firstIndex + 1;
while(index <= lastIndex){
if(comparator.compare(array[index], pivotValue) < 0){
++pivotIndex;
swap(array, pivotIndex, index);
}
index++;
}
// Return pivotValue to partition point
swap(array, firstIndex, pivotIndex);
return pivotIndex;
}
Sahalu Junaidu
Unit 15 214
Exercises1. What is the advantage of the bubble sort algorithm we have studied over all the other sorting methods we have studied?
2. When are bubble, insertion, and selection sort methods more efficient than merge sort and quicksort?
3. What is the disadvantage of merge sort as compared to quicksort?
4. What role, if any, does the size of data objects play in a sort?
5. Give the merge sort recursion-tree for the array:
43, 7, 10, 23, 18, 4, 19, 5, 66, 14, 2
6. A merge sort is used to sort an array of 1000 integers in descending order. Which of the following statements is true?
(a) The sort is fastest if the original integers are sorted in ascending order.
(b) The sort is fastest if the original integers are sorted in descending order.
(c) The sort is fastest if the original integers are completely in random order.
(d) The sort is the same, no matter what the order of the original integers.
7. A different method for choosing the pivot for each partition in quicksort is to take the median of the first, last and central keys. Implement a quicksort algorithm using this approach.
8. A different approach to the selection of a pivot in quicksort is to take the average of all the keys in a partition (assuming that the keys are numeric) as the pivot for that partition. The resulting algorithm is called meansort. Implement a quicksort algorithm using this approach. Note: The average of the keys is not necessarily one of the keys in the array.
Sahalu Junaidu
Unit 15 215
Exercises (cont’d)9. In quicksort, why is it better to choose the pivot from the center of the array rather from one of the ends?
10. What is the property of the best pivot in a quicksort?
11. What is the property of the worst pivot in a quicksort?
12. Suppose that, instead of sorting, we wish only to find the m th quicksort can be adapted to this problem, doing much less work than a complete sort.
13. Implement a non-recursive mergesort, where the length of the array is a power of 2. First merge adjacent regions of size 1, then adjacent regions of size 2, then adjacent regions of size 4, and so on.
14. Implement a non-recursive mergesort, where the length of the array is an arbitrary number.
Hint: Use a stack to keep track of which subarrays have been sorted.
15. Implement each of the sorting algorithms we have studied such that each displays the number of swaps and comparisons. Each of the implementations should be used to sort integer arrays with the same 100 random integers.
Sahalu Junaidu
Unit 15 216
Exercises (cont’d)16. Design a test program to compare the execution times of bubble sort, selection sort, insertion sort, merge sort, and quick sort on integers
arrays of equal lengths with similar random integers. For shorter lengths, sort many arrays and obtain the average execution time.
Sahalu Junaidu
Unit 16 217
Java Collections Framework: Interfaces
• Introduction to the Java Collections Framework (JCF)
• The Comparator Interface Revisited
• The Collection Interface
• The List Interface
• The Iterator Interface
• The ListIterator Interface
Sahalu Junaidu
Unit 16 218
The Java Collections Framework
• A collection is a group of objects.
• The Java Collections Framework is a set of important utility classes and interfaces in the java.util package for working with collections.
• The Collections Framework consists of three parts:
– Interfaces: the abstract data types that the framework supports.
• E.g., java.util.Comparator, java.util.Collection, java.util.Iterator
– Implementations: concrete versions of these interfaces.
• E.g., java.util.ArrayList and java.util.LinkedList.
– Algorithms: predefined actions defined on the interfaces or their implementations. E..g., Collections.sort(), Collections.binarySearch()
Sahalu Junaidu
Unit 16 219
Why Develop the JCF?
• An array is a common data structure suitable in many situations
• However, arrays are not always good for some of the following:– It requires size information for creation
– Inserting an element may lead to moving other elements around
– Deleting an element may lead to moving other elements around
• Other data structures, like linked list and trees, are better for some situations
• The JCF provides efficient implementations for these common data structures
• Using the JCF interfaces, these data structures can be manipulated in a uniform way
Sahalu Junaidu
Unit 16 220
Some Benefits of the JCF
• Benefits– It reduces programming effort: by providing useful data structures. Programmer
can focus on problem at hand
– Improve program speed and quality: by providing high-performance, high-quality implementations for the most common data structures
– Allows interoperability among unrelated APIs: If a network API provides a Collection of node names, and a GUI toolkit expects a Collection of column headings, they will interoperate seamlessly even though they were written independently
– It fosters software reuse
• Concerns– JCF data structures work only with objects, not primitive types
– A Collection can contain incompatible types at the same time
– JFC methods are generic; must always downcast from Object to our types
Sahalu Junaidu
Unit 16 221
Collections Framework’s Interfaces
Object <<interface>> Comparable
Collections AbstractCollection
AbstractList
AbstractSequentialList
LinkedList
ArrayList
<<interface>> Collection
<<interface>> Comparator
<<interface>> Iterator
<<interface>> List
<<interface>> ListIterator
java.lang
Sahalu Junaidu
Unit 16 222
The Comparator Interface Revisited
• Recall that the Comparator interface is used when
– The objects to be compared do not support natural ordering or
– When we desire a different ordering than the natural
• The interface:
public interface Comparator { public abstract int compare(Object object1, Object object2); public abstract boolean equals(Object obj);}
Sahalu Junaidu
Unit 16 223
Example 1: The Comparator Interface
1 import java.util.*; 2 class MyComparator implements Comparator { 3 public int compare(Object obj1, Object obj2) { 4 int i1 = ((Integer)obj1).intValue(); 5 int i2 = ((Integer)obj2).intValue(); 6 return Math.abs(i2) - Math.abs(i1); 7 } 8 } 9 public class TestCollections {10 public static void main(String args[]) {11 ArrayList array = new ArrayList();12 array.add(new Integer(-200));13 array.add(new Integer(100));14 array.add(new Integer(400));15 array.add(new Integer(-300));16 Collections.sort(array);17 System.out.println("Natural ordering: " + array);18 Collections.sort(array, new MyComparator());19 System.out.println("My own ordering : " + array);20 }21 }
Sahalu Junaidu
Unit 16 224
The Collection Interface
public interface Collection{ public abstract boolean add(Object object); public abstract boolean addAll(Collection collection); public abstract void clear(); public abstract boolean remove(Object object); public abstract boolean removeAll(Collection collection); public abstract boolean retainAll(Collection collection); public abstract boolean isEmpty(); public abstract boolean contains(Object object); public abstract boolean containsAll(Collection collection); public abstract equals(Object object); public abstract int size(); public abstract Iterator iterator(); public abstract int hashCode(); public abstract Object[] toArray(); public abstract Object[] toArray(Object[] array); }
Sahalu Junaidu
Unit 16 225
The List Interface
public abstract void add(int index, Object object); public abstract Object get(int index); public abstract int indexOf(Object object); public abstract int lastIndexOf(Object object); public abstract Object remove(int index); public abstract Object set(int index, Object object); public abstract ListIterator listIterator(); public abstract ListIterator listIterator(int index); public abstract List subList(int fromIndex, int toIndex);
• The List interface represents an ordered collection of objects.
• Each element in a list has an index, or position. The indexes range from 0 to size() – 1.
• List extends Collection. It has the following additional methods to those it inherits and
overrides:
Sahalu Junaidu
Unit 16 226
The Iterator Interface
public interface Iterator{ public abstract boolean hasNext(); public abstract Object next(); public abstract void remove();}
• To visit all the elements of a collection object c, code such as such as the
following may be used:
Iterator iter = c.iterator();while(iter.hasNext( )){ Object obj = iter.next(); process(obj);}
• Note: When next() is invoked, the iterator jumps over the next element, and it
returns a reference to the object that it just passed.
Sahalu Junaidu
Unit 16 227
The Iterator Interface (cont’d)
Iterator iter = c.iterator( );iter.next(); // skip over the first elementiter.remove(); // remove the first element
• The remove() method of an iterator removes the element whose reference was returned by the last call to
next(). For example, the following code removes the first element in a collection c:
Iterator iter = c.iterator( ); iter.remove();
• It is illegal to call the remove() method of an iterator if it was not preceded by a
call to next(). For example, the following is invalid:
Sahalu Junaidu
Unit 16 228
Example 2: The Iterator Interface
1 import java.util.*; 2 public class TestIterator { 3 public static void main(String[] args) { 4 //LinkedList list = new LinkedList(); 5 ArrayList list = new ArrayList(); 6 7 for(int i = 0; i < 6; i++) 8 list.add(new Integer(i)); 910 Iterator iter = list.iterator();1112 while (iter.hasNext()){13 Integer myInt = (Integer)iter.next();14 System.out.print(myInt+" ");15 }16 System.out.println();17 }18 }
Sahalu Junaidu
Unit 16 229
The ListIterator Interface
public abstract boolean hasPrevious(); public abstract int nextIndex(); public abstract Object previous(); public abstract int previousIndex(); public abstract add(Object object); public abstract void set(Object object);
• The ListIterator interface extends Iterator to allow bi-directional traversal of a list, and the modification of a list.
• It has the following additional methods to those it inherits and overrides:
Sahalu Junaidu
Unit 16 230
Example 3: The ListIterator Interface
1 import java.util.*; 2 public class TestListIterator { 3 public static void main(String[] args) { 4 //LinkedList list = new LinkedList(); 5 ArrayList list = new ArrayList(); 6 7 ListIterator iter2, iter1 = list.listIterator(); 8 9 for(int i = 0; i < 6; i++)10 iter1.add(new Integer(i));1112 iter2 = list.listIterator();13 iter2.next(); // skip the first element14 iter2.add(new Integer(25)); // add immediately after the first1516 System.out.println(list);17 }18 }
Sahalu Junaidu
Unit 16 231
Example 4: The ListIterator Interface
1 import java.util.*; 2 public class TestListIterator2 { 3 public static void main(String[] args) { 4 ArrayList list = new ArrayList(); 5 int bonus = 1; 6 7 for(int i = 0; i < 6; i++) 8 list.add(new Integer(i)); 910 ListIterator iter = list.listIterator();1112 System.out.println("List before: " + list);1314 while (iter.hasNext()){15 Integer myInt = (Integer)iter.next();16 iter.set(new Integer(myInt.intValue()+bonus));17 }18 System.out.println("List after : " + list);19 }20 }
Sahalu Junaidu
Unit 17 232
Java Collections Framework: Classes I
• JCF Class Hierarchy
• The ArrayList Class
• The Collections Class
Sahalu Junaidu
Unit 17 233
Collections Framework’s Classes
Object
Collections AbstractCollection
AbstractList
AbstractSequentialList
LinkedList
ArrayList
<<interface>> Collection
<<interface>> List
Sahalu Junaidu
Unit 17 234
The ArrayList Class
• The ArrayList class is List implementation based on a dynamic array. Thus, an
ArrayList object is a dynamic array
• It extends the AbstractList class and implements the List interface of the JCF
• Before Java 1.2, the functionality of the ArrayList was provided by the Vector class
• ArrayList is very much like the Vector class except that ArrayList methods are not
synchronized
• Since this class is based on an array, it is better used in applications requiring fast
direct access to objects
• However, the LinkedList class will give better performance for applications
requiring frequent insertions and deletions
Sahalu Junaidu
Unit 17 235
Example 1: Kinds of Objects a Collection
1 import java.util.ArrayList; 2 import java.util.Collections; 3 class ArrayListOfAllKinds{ 4 public static void main(String args []){ 5 ArrayList theArray = new ArrayList(); 6 7 theArray.add(new Double(3.7)); 8 theArray.add(new Boolean(true)); 9 theArray.add(new Integer(19));10 theArray.add(new String(";-)"));1112 System.out.println(theArray);13 }14 }
Sahalu Junaidu
Unit 17 236
Example 2: List of Lists
1 import java.util.ArrayList; 2 class ListOfLists{ 3 public static void main(String s[]){ 4 ArrayList kfupm=new ArrayList(); 5 ArrayList ics=new ArrayList(); 6 ArrayList coe=new ArrayList(); 7 ArrayList mis=new ArrayList(); 8 String[] icsBasics={"ics102", "ics103", "ics201", "ics202"}; 9 String[] coeBasics={"coe200", "ics102", "ics201", "ics202"};10 String[] misBasics={"mis105", "mis345", "mis301", "ics201"};11 for (int i=0; i<icsBasics.length; i++) {12 ics.add(icsBasics[i]);13 coe.add(coeBasics[i]);14 mis.add(misBasics[i]);15 }16 kfupm.add(ics);17 kfupm.add(coe);18 kfupm.add(mis);19 System.out.println(kfupm);20 }21 }
Sahalu Junaidu
Unit 17 237
Example 3: Using ArrayList
1 import java.util.*; 2 class MyArrayList extends ArrayList{ 3 public MyArrayList(int size){ 4 super(size); 5 } 6 public void removeRange(int x, int y){ //protected method of ArrayList 7 super.removeRange(x,y); 8 } 9 }10 class TestArrayList{11 public static void main(String s[]){12 MyArrayList c = new MyArrayList(100); //initial capacity13 ListIterator iter = c.listIterator();14 for(int i=0; i<6; i++)15 iter.add(new Integer(i)); // using iterator's add16 c.add(2,"ICS 201"); // using collection's add17 System.out.println(c);18 c.removeRange(3,6);19 System.out.println(c);20 }21 }
Sahalu Junaidu
Unit 17 238
Example 4: Using ArrayList
1 import java.util.*; 2 class TestArrayList2{ 3 public static void main(String s[]){ 4 ArrayList c, c1, c2 = new ArrayList(), c3 = new ArrayList(); 5 ListIterator iter = c3.listIterator(); 6 for(int i=0; i<s.length; i++) 7 iter.add(s[i]); 8 for(int i=0; i<10; i++) 9 c2.add(new Integer(i));10 Collections.shuffle(c2);11 System.out.println("Shuffled: "+ c2);12 c1 = new ArrayList(c3);13 c2.addAll(3,c1);14 c = (ArrayList)c2.clone();15 c.remove(3);16 System.out.println(c);17 System.out.println(c1);18 System.out.println(c2);19 System.out.println(c3.containsAll(c1));20 }21 }
Sahalu Junaidu
Unit 17 239
The Collections Class
• The Collections class contains static methods for manipulating collection
objects.
• The Collections class has no constructors.
• The most common algorithms in this class are those for sorting and
searching
– We have already seen examples usage of Collections.sort() and Collections.shuffle().
• We will revisit and conclude with an example on our BankAccount class
Sahalu Junaidu
Unit 17 240
Example 5: Searching Collections
1 import java.util.*; 2 class BankAccount implements Comparable{ 3 private int accountNumber; 4 protected String name; 5 private double balance; 6 public BankAccount(int accountNumber, String name, double balance){ 7 this.accountNumber = accountNumber; 8 this.name = name; 9 this.balance = balance;10 }11 public int compareTo(Object object){12 BankAccount account = (BankAccount) object;13 return accountNumber - account.accountNumber;14 }15 public String toString(){16 return accountNumber + " " + name + " " + balance + " SR";17 }18 }
Sahalu Junaidu
Unit 17 241
Example 5: Searching Collections (cont’d)
19 public class SortingAndSearching{20 public static void main(String[] args){21 ArrayList list = new ArrayList();22 list.add(new BankAccount(9234, "Ahmad", 50000 ));23 list.add(new BankAccount(8000, "Abubakar", 40000 ));24 list.add(new BankAccount(6000, "Yusuf", 6000 ));25 list.add(new BankAccount(9975, "Zubeir", 10000 ));26 System.out.println("Sorted in increasing order of Account Number:");27 Collections.sort(list); System.out.println(list);28 System.out.println("Sorted in decreasing order of Customer name:");29 Collections.sort(list, new Comparator(){30 public int compare(Object object1, Object object2){31 BankAccount account1 = (BankAccount) object1;32 BankAccount account2 = (BankAccount)object2;33 String string1 = account1.name;34 String string2 = account2.name;35 return string2.compareTo(string1);36 }});37 System.out.println(list);38 BankAccount ba = new BankAccount(6000, "Ali", 7000);39 System.out.println(Collections.binarySearch(list, ba));40 }41 }
Sahalu Junaidu
Unit 18 242
Java Collections Framework: Classes II
• Introduction
• LinkedList Nodes Declarations
• Using the LinkedList Collection
• Introduction to Stacks and Queues
• Implementing Stacks and Queues using LinkedList
Sahalu Junaidu
Unit 18 243
The LinkedList Class
• As discussed earlier, the LinkedList Collection is a better choice in applications
requiring frequent insertions and deletions from any place
• If, on the other hand, there are frequent retrievals, then the ArrayList
Collection is a better choice for good performance.
• A linked data structure is a collection of nodes storing data and links
(references) to other nodes.
• Two such data structures are singly linked list (SLL) and doubly linked list
(DLL)
• Next, we show the nodes declarations for these two flavors of linked lists.
Sahalu Junaidu
Unit 18 244
Singly-Linked Lists: Nodes Declaration
public class SLLNode{ protected Object data; protected SLLNode next; public SLLNode(Object data, SLLNode next){ this.data = data;
this.next = next; } public SLLNode(Object data){
this(data, null); } // . . .}
tail
head
Sahalu Junaidu
Unit 18 245
Doubly-Linked Lists: Nodes Declaration
public class DLLNode{ protected Object data; protected DLLNode next; protected DLLNode previous; public DLLNode(Object data, DLLNode nxt, DLLNode prev){ this.data = data;
next = nxt;if(next != null) next.previous = this;previous = prev;if(previous != null) previous.next = this;
} public DLLNode(Object data){
this(data, null, null); } // . . .}
tail
head
Sahalu Junaidu
Unit 18 246
Example 1: Merging Linked Lists
1 import java.util.*; 2 public class InterleaveLinkedLists { 3 public static void main(String[] args) { 4 LinkedList list1 = new LinkedList(); 5 LinkedList list2 = new LinkedList(); 6 for(int i = 20; i <= 30; i++) 7 list1.add(new Integer(i)); 8 for(int i = 1; i <= 7; i++) 9 list2.add(new Integer(i));10 System.out.println("list1 is: " + list1);11 System.out.println("list2 is: " + list2);12 ListIterator iter1, iter2;13 for(iter1=list1.listIterator(),iter2=list2.listIterator(); iter2.hasNext();) {14 if(iter1.hasNext())15 iter1.next();16 iter1.add(iter2.next());17 }18 System.out.println("The merged list is:");19 System.out.println(list1);20 }21 }
Sahalu Junaidu
Unit 18 247
Example 2: Reversing a Linked List
1 import java.util.*; 2 public class ReversingLinkedList { 3 public static void main(String[] args) { 4 ListIterator iter1, iter2; 5 LinkedList c = new LinkedList(); 6 for(int i = 20; i <= 30; i++) 7 c.add(new Integer(i)); 8 System.out.println("Original : " + c); 9 int j,size = c.size();10 for(j=0,iter1 = c.listIterator(),iter2 = c.listIterator(size);11 iter1.hasNext () && iter2.hasPrevious () && j<size/2;) {12 exchange(c, c.indexOf(iter1.next ()), c.indexOf(iter2.previous()));13 j++;14 }15 System.out.println("Reversed : " + c);16 }17 public static void exchange(List a, int i, int j) {18 Object temp = a.get(i);19 a.set(i, a.get(j));20 a.set(j, temp);21 }22 }
Sahalu Junaidu
Unit 18 248
The Stack Collection
• A stack is a LIFO (Last In First Out) data structure. The last element
inserted is the first element to be removed.
• A stack can be implemented as a linked list in which insertion is always
done at the first position (usually called the top) of the stack. Removal is
also always done at this position.
• Usual stack operations: push(), pop(), isEmpty(), top()
(peek() in Java)top
Sahalu Junaidu
Unit 18 249
Using java.util.Stack
1 import java.util.Stack; 2 class TestStack{ 3 public static void main(String args[]){ 4 Stack s = new Stack(); 5 s.push("One"); 6 s.push("Two"); 7 System.out.println("Top: " + s.peek()); 8 s.push("Three"); 910 while(!(s.isEmpty()))11 System.out.println(s.pop());12 }13 }
Sahalu Junaidu
Unit 18 250
Implementing Stacks using LinkedList
1 import java.util.*; 2 class OurStack{ 3 protected LinkedList list; 4 public OurStack(){ 5 list = new LinkedList(); 6 } 7 public Object pop() throws NoSuchElementException{ 8 if(list.isEmpty()) 9 throw new NoSuchElementException();10 else11 return list.removeFirst();12 }13 public void push(Object obj){14 list.addFirst(obj);15 }16 public Object peek() throws NoSuchElementException{17 if(list.isEmpty())18 throw new NoSuchElementException();19 else20 return list.getFirst();21 }
22 public void clear(){23 list.clear();24 }25 public boolean isEmpty(){26 return list.isEmpty();27 }28 public int contains(Object obj){29 return list.indexOf(obj);30 }31 public String toString(){32 return list.toString();33 }34 }
Sahalu Junaidu
Unit 18 251
Example 3: Reversing a Text File
1 import java.io.*; 2 public class ReverseTextFile{ 3 public static void main(String[] args) throws IOException{ 4 5 OurStack stack = new OurStack(); 6 7 BufferedReader inputStream = new BufferedReader(new FileReader("myfile.txt")); 8 String inputLine, line; 9 while((inputLine = inputStream.readLine()) != null)10 stack.push(inputLine);1112 inputStream.close();1314 PrintWriter outputStream = new PrintWriter(new FileWriter("myfile.txt"));15 while(! stack.isEmpty())16 outputStream.println(stack.pop());1718 outputStream.close();1920 System.out.println("The reversal process is complete");21 }22 }
Sahalu Junaidu
Unit 18 252
Example 4: Evaluating Postfix Expressions
1 import java.util.*; 2 class EvaluatePostFix{ 3 public static void main(String args[]){ 4 Stack stack = new Stack(); 5 String postFix = "3 4 - 5 3 * -"; 6 int i; 7 double o1, o2; 8 Double obj, op1, op2, result; 9 char ch;10 for(i=0; i<postFix.length(); i++){11 ch = postFix.charAt(i);12 if(isDigit(ch)){13 obj = new Double(ch-'0');14 stack.push(obj);15 }else if(isOperator(ch)){16 op2 = (Double)stack.pop();17 o2 = op2.doubleValue();18 op1 = (Double)stack.pop();19 o1 = op1.doubleValue();
Sahalu Junaidu
Unit 18 253
Evaluating Postfix Expressions (cont’d)
20 switch(ch){21 case '+' :22 result = new Double(o1+o2);23 stack.push(result);24 break;25 case '-' :26 result = new Double(o1-o2);27 stack.push(result);28 break;29 case '*' :30 result = new Double(o1*o2);31 stack.push(result);32 break;33 case '/' :34 result = new Double(o1/o2);35 stack.push(result);36 } // switch37 } //else if38 } // for
Sahalu Junaidu
Unit 18 254
Evaluating Postfix Expressions (cont’d)
39 result = (Double)stack.pop();40 System.out.println("Result = " + result.doubleValue());41 } // main42 public static boolean isOperator(char ch){43 return ((ch == '+') || (ch == '-') ||44 (ch == '*') || (ch == '/'));45 }46 public static boolean isDigit(char ch){47 int value = ch - '0';48 return (value < 10 && value > -1);49 }50 } // class
Sahalu Junaidu
Unit 18 255
Implementing Queue Using LinkedList
• A queue is a FIFO (First In First Out) data structure.
• A queue can be implemented as a linked list in which insertion (enqueing)
is always done at the last queue position (rear), and removal (dequeing) is
always done at the first queue position (front).
• There is no Queue class in the Java API but the ArrayList methods
addLast(), getFirst(), removeFirst() and isEmpty() can
be used to simulate a queue.
rear
front
Sahalu Junaidu
Unit 18 256
Implementing Queue (cont’d)
1 import java.util.*; 2 public class OurQueue{ 3 protected LinkedList list; 4 public OurQueue(){ 5 list = new LinkedList(); 6 } 7 public Object dequeue() throws NoSuchElementException{ 8 if(list.isEmpty()) 9 throw new NoSuchElementException();10 else11 return list.removeFirst();12 }13 public void enqueue(Object obj){14 list.addLast(obj);15 }16 public Object peek() throws NoSuchElementException{17 if(list.isEmpty())18 throw new NoSuchElementException();19 else20 return list.getFirst();21 }
22 public void clear(){23 list.clear();24 }25 public boolean isEmpty(){26 return list.isEmpty();27 }28 public int contains(Object obj){29 return list.indexOf(obj);30 }31 public String toString(){32 return list.toString();33 }34 }
Sahalu Junaidu
Unit 19 257
Introduction to Threads and Concurrency
• Introduction to Threads
• Multithreading Examples
• Life-cycle of a Thread
• Thread Priorities
• More Examples
Sahalu Junaidu
Unit 19 258
Introduction: What is a Thread?
• Just like human being can walk, talk, see, hear etc at the same time, computers
can also download documents, print a file, receive e-mail concurrently
• Computers normally achieve concurrency using threads
• A thread or thread of control is a section of code executed independently of
other threads of control within a single program
• Each thread has its own stack, priority, and virtual set of registers
• Every program has at least one thread
• Every Java applet or application is multithreaded
Sahalu Junaidu
Unit 19 260
Introduction: Where are Threads Used?
• Threads are used by virtually every computer user in the following instances:
– In Internet browsers
– In databases
– In operating systems (for controlling access to shared resources etc)
• Benefits of threads
– More productivity to the end user (such as responsive user interface)
– More efficient use of the computer (such as using the CPU while performing input-output)
– Sometimes advantageous to the programmer (such as simplifying program logic)
Sahalu Junaidu
Unit 19 261
Threads in Java
• Java is one of the few (the only?) languages that supports threads at the language level
• Writing multithreaded programs can be tricky: imagine reading three books by reading
few words from each book for a few seconds repeatedly in succession
• Although Java is portable, its multithreading is platform dependent: a multithreaded
program could behave differently on different platforms:
• Under Solaris implementation, an executing thread can run to completion or can be
preempted by a higher priority thread
• On windows (NT and 98) threads are timesliced and preemption occurs with higher as
well as with equal priority threads
• To create a thread, you extend java.lang.Thread or implement java.lang.Runnable
Sahalu Junaidu
Unit 19 262
Example 1: Extending java.lang.Thread
1 class OurClass1{ 2 public void run(){ 3 for(int i=0; i<100; i++) 4 System.out.print("Salam "); 5 } 6 } 7 public class OurClass1Tester{ 8 public static void main(String args[]){ 9 OurClass1 oc = new OurClass1();10 oc.run();11 run();12 }13 static void run(){14 for(int i=0; i<100; i++)15 System.out.print("Shabab.");16 }17 }
1 class OurClass2 extends Thread{ 2 public void run(){ 3 for(int i=0; i<100; i++) 4 System.out.print("Salam "); 5 } 6 } 7 public class OurClass2Tester{ 8 public static void main(String args[]){ 9 OurClass2 oc = new OurClass2();10 oc.start();11 run();12 }13 static void run(){14 for(int i=0; i<100; i++)15 System.out.print("Shabab.");16 }17 }
Sahalu Junaidu
Unit 19 263
Example 2: Implementing java.lang.Runnable
1 class OurClass3 implements Runnable{ 2 public void run(){ 3 for(int i=0; i<100; i++) 4 System.out.print("Salam "); 5 } 6 } 7 public class OurClass3Tester{ 8 public static void main(String args[]){ 9 OurClass3 oc = new OurClass3();10 Thread th = new Thread(oc);11 th.start();12 run();13 }14 static void run(){15 for(int i=0; i<100; i++)16 System.out.print("Shabab.");17 }18 }
Sahalu Junaidu
Unit 19 264
Example 3: Creating Multiple Threads
1 public class SleepingThread extends Thread { 2 private int countDown = 5; 3 private static int threadCount = 0; 4 private int threadNumber = ++threadCount; 5 public SleepingThread() { 6 System.out.println("Making " + getName()); 7 } 8 public void run() { 9 while(true) {10 try { // don’t wake a sleeping thread before its sleep time expires!11 System.out.println(getName() + " Executing.");12 sleep((long)(Math.random()*5000));13 }catch(InterruptedException ie){14 System.out.println(getName() + " Interrupted.");15 }16 if(--countDown == 0) return;17 } }18 public static void main(String[] args) {19 for(int i = 0; i < 5; i++)20 new SleepingThread().start();21 System.out.println("All Threads Started");22 }}
Sahalu Junaidu
Unit 19 265
Threads: Pictorial View of a Lifetime.
Thread created
new
ready
running
finished
blocked
start()
run()
yield(), or timeexpired
stop(), orcomplete
stop()
suspend(),sleep(), or wait()
stop()
resume(),notify(), ornotifyAll()
Sahalu Junaidu
Unit 19 266
Example 4: A Timer Thread
1 import java.awt.*; 2 import java.awt.event.*; 3 import javax.swing.*; 4 class TimerThread extends JFrame implements Runnable{ 5 private JTextField jtf = new JTextField(10); 6 private JButton jb = new JButton("Start/Stop"); 7 private int counter = 0; 8 private boolean startStop = true; 9 TimerThread(){10 Container cp = getContentPane();11 cp.setLayout(new FlowLayout());12 cp.add(jtf);13 cp.add(jb);14 pack();15 setTitle("A Timer Thread");16 show();17 jb.addActionListener(new ActionListener(){18 public void actionPerformed(ActionEvent ae){19 startStop = !startStop;20 } });}
Sahalu Junaidu
Unit 19 267
Example 4: A Timer Thread (cont’d)
21 public void run(){22 while (true){23 try{24 Thread.sleep(1000);25 }catch(Exception e){}26 if (startStop)27 jtf.setText(“”+counter++);28 }29 }30 public static void main(String args[]){31 new Thread(new TimerThread()).start();32 }33 }
Sahalu Junaidu
Unit 19 268
Example 5: A Visitor Thread
1 import java.util.*; 2 public class VisitorThread extends Thread { 3 private Object []array; 4 public VisitorThread(Object array[]) { 5 this.array = array; 6 } 7 public void run() { 8 Integer temp; 9 this.setName("The Visitor");10 for(int i = 0; i < array.length; i++){11 temp = (Integer)array[i];12 array[i] = new Integer (temp.intValue() + i);13 if(i%3 == 0) Thread.yield();14 }15 System.out.println(getName() + " done!");16 }17 }
Sahalu Junaidu
Unit 19 269
Example 5: A Sorter Thread
1 import java.util.*; 2 public class SorterThread extends Thread { 3 private Object []array; 4 public SorterThread(Object array[]){ 5 this.array = array; 6 } 7 public void run() { 8 int minPos = 0; Object temp; 9 for(int i = 0; i < array.length - 1; i++){10 minPos = i;11 if(i%3 == 0) Thread.yield();12 for(int k = i + 1; k < array.length; k++){13 if(((Integer)array[k]).compareTo(array[minPos]) < 0)14 minPos = k;15 }16 temp = array[minPos];17 array[minPos] = array[i];18 array[i] = temp;19 }20 System.out.println(getName() + " done!");21 }22 }
Sahalu Junaidu
Unit 19 270
Example 5: A Tester Thread
1 import java.util.*; 2 public class TesterThread extends Thread { 3 private static Object []array; 4 public TesterThread(int size) { 5 array = new Object[size]; 6 } 7 public static void main(String args[]) { 8 Random r = new Random(); 9 new TesterThread(100);10 for(int i = 0; i < array.length; i++){11 array[i] = new Integer(r.nextInt(100));12 }13 SorterThread sorter = new SorterThread(array);14 VisitorThread visitor = new VisitorThread(array);15 sorter.start();16 visitor.start();17 for(int i = 0; i < array.length; i++){18 System.out.println(array[i]);19 }20 System.out.println(Thread.currentThread().getName() + " done!");21 }22 }
Sahalu Junaidu
Unit 19 271
Threads Priorities
• As wehave seen, the run( ) methods of the threads in a program will be executed
“simultaneously”
• The programmer can influence the order of threads executions using threads’ priorities
• Every Java thread has a priority in the range Thread.MIN_PRIORITY (a constant
value, 1) and Thread.MAX_PRIORITY (a constant value, 10).
• The default priority is Thread.NORMAL_PRIORITY (a constant value, 5)
• Each new thread inherits the priority of the thread that creates it
• Every thread has a name (including anonymous threads) for identification purposes
– More than one thread may have the same name
– If a name is not specified when a thread is created, a new name is generated for it
Sahalu Junaidu
Unit 19 272
Example 6: Prioritizing the Visitor Thread
1 import java.util.*; 2 public class TesterThread extends Thread { 3 private static Object []array; 4 public TesterThread(int size) { 5 array = new Object[size]; 6 } 7 public static void main(String args[]) { 8 Random r = new Random(); new TesterThread(100); 9 for(int i = 0; i < array.length; i++){10 array[i] = new Integer(r.nextInt(100));11 }12 SorterThread sorter = new SorterThread(array);13 VisitorThread visitor = new VisitorThread(array);14 sorter.start(); visitor.start();15 visitor.setPriority(Thread.MAX_PRIORITY);16 Thread.currentThread().setPriority(Thread.MIN_PRIORITY);17 for(int i = 0; i < array.length; i++){18 System.out.println(array[i]);19 }20 System.out.println(Thread.currentThread().getName() + " done!");21 }22 }
Sahalu Junaidu
Unit 20 273
Further Threads Programming
• Some Terminologies on Multithreading
• Example 1: Threads Synchronization
• Example 2: ‘Salaam Shabab’ Animation
• Example 3: Car Race Animation
• Example 4: Rocket Launching Animation
Sahalu Junaidu
Unit 20 274
Some Terminologies on Multithreading
• Thread scheduling: arranging the threads to be executed in an order that they may take CPU control
• Timeslice: The length of time for which a thread runs and this time may depend on the thread's priority or its use of resources such as memory and I/O
• Preemption: to interrupt and suspend (“swap out”) the currently executing thread in order to start or continue running ("swap in") another thread
• Synchronization: The process of ensuring that that a shared resource is used by only one of the many contending threads at any moment
• Deadlock: A situation where two or more threads are unable to proceed because each is waiting for one of the others to do something
• Starvation: indefinite postponement of the execution of lower-priority threads by higher-priority ones
Sahalu Junaidu
Unit 20 275
Threads Synchronization
• When a block of Java code guarded by the synchronized keyword, it can be executed by only one thread at any time
• A shared resource (implemented by a given code segment) may be corrupted if it is accessed simultaneously by multiple threads.
– E.g., unsynchronized threads accessing the same database
• Such blocks of code are usually called critical sections and must be executed in a mutually-exclusive way
• You can synchronize an entire method or just a few lines of code by using the synchronized keyword
• Note that code that is thread-safe (i.e, guarded by synchronized) is slower than code that is not
Sahalu Junaidu
Unit 20 276
Example 1: Threads Synchronization
1 class BanckAccount{ 2 private int balance; 3 public BanckAccount(int balance){ 4 this.balance = balance; 5 } 6 void doNothing(){ 7 depositWithdraw(10); 8 depositWithdraw(20); 9 depositWithdraw(30);10 }11 void depositWithdraw(int money){12 try {13 balance += money;14 Thread.sleep((long)(Math.random()*1000));15 balance -= money;16 } catch(Exception e){}17 }18 int get(){19 return balance;20 }21 }
Sahalu Junaidu
Unit 20 277
Example 1: Threads Synchronization (cont’d)
22 public class UnsafeBankAccount extends Thread{23 BanckAccount ba;24 public static void main( String[] args ){25 BanckAccount ba = new26 BanckAccount(0);27 for(int i=0; i<9; i++)28 new UnsafeBankAccount(ba).start();29 }30 public UnsafeBankAccount(BanckAccount ba){31 this.ba = ba;32 }33 public void run(){34 doWork();35 }36 public void doWork(){37 System.out.println(getName()+" got balance: "+ba.get());38 ba.doNothing();39 System.out.println(getName()+" got balance: "+ba.get());40 }41 }
• Make depositWithdraw() and get() synchronized to solve this problem
Sahalu Junaidu
Unit 20 278
Example 2: ‘Salaam Shabab’ Animation
1 import java.awt.*; 2 import java.awt.event.*; 3 import javax.swing.*; 4 class AnimationPanel extends JPanel implements Runnable { 5 private Font myFont; 6 private int increment = 1; 7 public int xSize, ySize, yCoord = 0; 8 int delay; 9 Thread animator;10 private boolean onOff=true;11 public AnimationPanel(int delay) {12 xSize=400;13 ySize=350;14 setSize(xSize, ySize);15 myFont = new Font ("Serif", Font.ITALIC, 30);16 animator = new Thread(this);17 animator.start();18 }19 public void setOnOff(boolean onOff) {20 this.onOff = onOff;21 }
Sahalu Junaidu
Unit 20 279
Example 2: ‘Shabab’ Animation (cont’d)
22 public void paintComponent(Graphics g) {23 super.paintComponent(g);24 g.setColor(Color.yellow);25 g.fillRect(0,0,xSize, ySize);26 g.setColor (Color.red);27 g.setFont(myFont);28 if(onOff) {29 g.drawString ("Salaam ", xSize/2-100, ySize/2 + yCoord);30 g.drawString ("Shabab!", xSize/2, ySize/2 - yCoord);31 }32 }33 public void run () {34 while(true){35 yCoord = yCoord + increment;//yCoord min is -150 and max 15036 if((yCoord == (ySize-50)/2 || (yCoord == -(ySize-50)/2)))37 increment = -increment; // increment by -1 now38 try{39 Thread.sleep(delay);40 } catch(InterruptedException e){}41 repaint();42 }43 }44 }
Sahalu Junaidu
Unit 20 280
Example 2: ‘Shabab’ Animation (cont’d)
45 public class SalamShababAnimation extends JApplet{46 private Button myButton;47 private boolean onOffButton = true;48 private AnimationPanel ap;49 public void init() { //validate parsing the parameter "fps"50 int delay = Integer.parseInt(getParameter("fps"));51 delay = (delay<10)? 10 : delay;52 Container cp = getContentPane();53 cp.setLayout(new BorderLayout());54 ap = new AnimationPanel(delay);55 myButton = new Button ("Start/Stop");56 myButton.addActionListener(new ActionListener(){57 public void actionPerformed(ActionEvent ae){58 onOffButton = !onOffButton;59 ap.setOnOff(onOffButton);60 }});61 cp.add(myButton,BorderLayout.NORTH);62 cp.add(ap, BorderLayout.CENTER);63 }64 }
Sahalu Junaidu
Unit 20 281
Example 3: Car Race Animation
1 import java.awt.*; 2 import java.awt.event.*; 3 import javax.swing.*; 4 import java.util.*; 5 class DrivingPanel extends JPanel implements Runnable { 6 private int delay; 7 private Thread animator; 8 private Image car; 9 static final int WIDTH = 600;10 static final int HEIGHT = 200;11 private int xPosition, speed;12 private Random random;13 public DrivingPanel(Image car, int delay) {14 this.car = car;15 this.delay = delay;16 setSize(WIDTH,HEIGHT);17 xPosition = getWidth();18 random = new Random();19 speed = random.nextInt(5);//+1;20 animator = new Thread(this);21 animator.start();22 }
Sahalu Junaidu
Unit 20 282
Example 3: Car Race Animation (cont’d)
23 public void run() {24 while (true) {25 repaint();26 speed = random.nextInt(5)+1;27 xPosition -= speed;28 if (xPosition < -car.getWidth(this))29 xPosition = getWidth();30 try {31 Thread.sleep(delay);32 } catch (InterruptedException e) {33 break;34 }35 }36 }37 public void paintComponent(Graphics g) {38 super.paintComponent(g);39 g.setColor(Color.white);40 g.fillRect(0, 0, getWidth(), getHeight());41 g.drawImage(car, xPosition, getHeight()/2, this);42 }43 }
Sahalu Junaidu
Unit 20 283
Example 3: Car Race Animation (cont’d)
44 public class CarRaceAnimation extends JApplet {45 public void init() { // You should validate parsing the parameter!46 int delay = Integer.parseInt(getParameter("fps"));47 delay = (delay<10)? 10: delay;48 Image car = getImage(getCodeBase(),"car.gif");49 DrivingPanel lane1 = new DrivingPanel(car, delay);50 DrivingPanel lane2 = new DrivingPanel(car, delay);51 Container cp = getContentPane();52 cp.setLayout(new GridLayout(2,1));53 cp.add(lane1);54 cp.add(lane2);55 }56 }
• Download the car image used in the example from here.
• You can also obtain the rocket image for the next example.
Sahalu Junaidu
Unit 20 284
Example 4: Rocket Launcher
1 import java.applet.*; 2 import java.awt.*; 3 import java.awt.event.*; 4 import javax.swing.*; 5 public class RocketLauncher extends JApplet implements Runnable, ActionListener { 6 private Image rocket; 7 private int x, y, sec=10; 8 private Thread myThread; 9 private Timer timer = new Timer(1000,this);10 JTextField tf = new JTextField(5);11 JButton b = new JButton("Start Count Down");12 public void init() {13 rocket = Toolkit.getDefaultToolkit().getImage("rocket.jpg");14 x = 50;15 y = getSize().height-rocket.getHeight(this)-380;16 myThread = new Thread(this);17 tf.setText(" "+sec+" ");18 b.addActionListener(this);19 }
Sahalu Junaidu
Unit 20 285
Example 4: Rocket Launcher (cont’d)
20 public void actionPerformed( ActionEvent ae) {21 if(ae.getSource() == b)22 timer.start();23 if(ae.getSource() == timer)24 if(--sec>0)25 tf.setText(" "+sec+" ");26 else{27 timer.stop();28 myThread.start();29 }30 }31 public void run() {32 while (y-- != -rocket.getHeight(this)) {33 try {34 myThread.sleep(10);35 } catch (InterruptedException e) {}36 repaint();37 }38 }39 public void update(Graphics g){40 paint(g);41 }
Sahalu Junaidu
Unit 20 286
Example 4: Rocket Launcher (cont’d)
42 public void paint(Graphics g) {43 g.drawImage(rocket,x,y,null);44 }45 public static void main(String [] args){46 JFrame frame = new JFrame("My Rocket Launch Pad");47 frame.setSize(400,750);48 Container cp = frame.getContentPane();49 cp.setLayout(new GridLayout(1,2));50 JPanel p = new JPanel();51 JPanel p1 = new JPanel();52 p.setLayout(new BoxLayout(p,BoxLayout.Y_AXIS));53 RocketLauncher applet = new RocketLauncher();54 p.add(applet.b);55 p1.add(applet.tf);56 p.add(p1);57 cp.add(p);58 applet.setBackground(Color.white);59 cp.add(applet);60 frame.setVisible(true);61 applet.init();62 }63 }
Sahalu Junaidu
Unit 20 287
Exercises
1. Modify Example 2 so that when the animation is stopped, the strings Salaam and Shabab remain displayed on the animation screen.
2. Modify Example 2 so that the strings Salaam and Shabab move in opposite direction horizontally rather than vertically.
3. Improve the car race animation by1. Adding a button to control when to start the next race
2. Incorporating up to four cars in the race
3. Displaying the winning car after every race
4. Incorporating different car models
4. Modify each of the preceding examples so that each of them can work as an applet as well as a standalone application.
Sahalu Junaidu
Unit 21
Introduction to Databases
Overview Objectives of this lecture.
History and Evolution of Databases.
Basic Terms in Database and Definitions of Database and DBMS.
Components of A Database System.
Characteristics, Functions and Uses of DBMS.
Limitations, Advantages and Disadvantages of DBMS.
Three aspects to study in DBMS and its Marketplace.
Preview : Database Design and Introduction to SQL.
Sahalu Junaidu
Unit 21
Objectives of this Lecture
Understand the evolution of databases and DBMS
Understand the limitations of file processing systems and how database management systems overcome these limitations.
Understand the concept of database management systems.
Understand the functions, uses and limitations of DBMS
Sahalu Junaidu
Unit 21
History and Evolution of Databases
Early computers were mainly used for scientific and engineering computation (number crunching).
However, it was soon understood that, computers could also be used to store and manipulate information. Thus, the business community where information handling is the main task, began to take interest in computers.
The first popular language for such applications, COBOL (COmmon Business Oriented Language) was developed and it soon became one of the most popular languages, second only to FORTRAN.
In early processing systems, the information was stored as groups of records in separate flat files.
These file processing systems (FPS) consisted of a few data files and many application programs written in COBOL or FORTRAN
However, business processes are dynamic, requiring continuous changes in files and applications. Any slight change in the data would require a corresponding change in the COBOL programs that uses it.
The file processing system has the following limitations.
Sahalu Junaidu
Unit 21
Limitations of FPS and Evolution of DBMS
No relationship between data in different files Data Redundancy Program – Data dependence involving file formats and access techniques Difficulty in representing the data from the user’s view Data Inflexibility
In order to overcome these limitations, a whole new area of Computer science called Database Applications (or simply Data Bases) evolved.
DBMS overcomes limitations
Eliminates separation and isolation of data Reduces Data Redundancy Eliminates dependence between Program and Data Allows for representation of data from the user’s view Increases Data Flexibility
Sahalu Junaidu
Unit 21
What is a Database Management System?
Manages very large amounts of data.
Supports efficient access to very large amounts of data.
Supports concurrent access to very large amounts of data. Example: Bank and its ATM machines.
Supports secure, atomic access to very large amounts of data. Contrast two people editing the same UNIX file --- last to write
``wins'' --- with the problem if two people deduct money from the same account via ATM machines at the same time --- new balance is wrong whichever writes last.
Sahalu Junaidu
Unit 21
Basic Terms in Database Systems
Entity: This is an object (abstract or concrete) about which information is being stored e.g., student, book, car, etc.
Field: This is an attribute of an entity. E.g., name, identification number, etc.
Record: This is a collection of related fields e.g. all the attribute of a student could constitute a record (ID number, name, major GPA, etc)
File: This is a collection of related records e.g., All records about books in a library. A file is usually arranged in a tabular form in which each row represents a record and each column represent a field. A file organized in such a way that the records must be processed one
by one from the beginning to end is called a sequential file. In such a file, two records are separated by an inter-record gap. The
end of the file is indicated by a special character called end-of-file (EOF) marker.
In contrast to sequential files, random access files (also called direct-access files) enable processing of a record without the review of other records. On the record fields is set as a key field or index.
Sahalu Junaidu
Unit 21
Definitions – Database and DBMS Database: This is a collection of related files. For example, all the files that
are used to store information in a library system. Database Management System (DBMS): This is a program that allows users
to define, manipulate, and process the data in a database in order to produce meaningful information
Three main components in a database system: Physical database: This consists of the actual files comprising the
database, usually arranged in some structured manner- to avoid duplication, redundancy and to ensure integrity of the data. The physical database is almost always on a disk, magnetic tape or CD-ROM
Database Management Systems (DBMS): These are programs that provide facilities for creating, accessing and maintaining the physical database. Examples of DBMS are dBASE, ACCESS & SQL Specifically, the DBMS must provide an efficient and convenient environment for users to create, add, retrieve and delete data.
Application Software: These are programs written using the facilities provided by DBMS to allow access to the physical database (or a partition of it) in a user-friendly and user-specific manner.
Sahalu Junaidu
Unit 21
Components of Database Management System
ApplicationProgram
OperatingSystem
DBMSENGINE
File
Physical
memory
File
Sahalu Junaidu
Unit 21
Database Schema
Database Schemas: This is a logical design of a database. It consists of a set of tables of the data types used, giving the names of entities and attributes and the relationship among them.
Schemas are classified as internal – when they correspond to physical database and external when they correspond to data in application programs.
The capability to change the internal schemas as needed without affecting the external schema is called data independence.
Schemas are generally written in a data definition language which generates the schema tables stored in a file called a data dictionary.
The data dictionary is always accessed before any change to the physical data is made. The following figure illustrates some of these concept.
Sahalu Junaidu
Unit 21
DB System: Data Independence
Secondary Storage
Data DictionaryDataFiles
DataDefinitionLanguage
DatabaseSchema
Users
DBMS
(logical)
(physical)
Sahalu Junaidu
Unit 21
Characteristics, Functions and Uses of a DBMS
Characteristics : It is a computerized record-keeping system. It contains facilities that allow the user to . . .
Add and delete files to the system. Insert, retrieve, update, and delete data in existing files.
It is collection of databases. A DBMS may contain many databases that can be used for separate
purposes or combined to provide useful information.Functions : To store data To organize data To control access to data To protect data
Sahalu Junaidu
Unit 21
Advantages and Disadvantages of a DBMS
Uses : To provide decision support
Managers and analysts retrieve information generated by the DBMS for inquiry, analysis, and decision-making.
To provide transaction processingUsers input, update, and process data with transactions that generate information needed by managers and other users or by other departments.
Advantages: Centralized Data reduces management problems. Data redundancy and consistency are controllable. Program - data interdependency is diminished. Flexibility of data is increased. Disadvantages: Reduction in speed of data access time. Requires special knowledge. Possible dependency of application programs to specific DBMS versions. Application Languages need specific interface (Drivers) to interact with
DBMS
Sahalu Junaidu
Unit 21
Three Aspects in DBMS and its Marketplace
Three Aspects to Study in DBMS:
1. Modeling and design of databases. Allows exploration of issues before committing to an implementation.
2. Programming: queries and DB operations like update. SQL = “intergalactic dataspeak.''
3. DBMS implementation.
The DBMS Marketplace: Relational DBMS companies --- Oracle, Informix, Sybase --- are among the
largest software companies in the world. IBM offers its relational DB2 system. With IMS, a non-relational system, IBM is
by some accounts the largest DBMS vendor in the world. Microsoft offers SQL Server, plus Microsoft Access for the cheap DBMS on the
desktop, answered by ``lite'' systems from other competitors. Relational companies also challenged by “object oriented DB” companies But countered with “object relational” systems, which retain the relational core
while allowing type extension as in OO systems.
Sahalu Junaidu
Unit 22
Database Design, SQL and JDBC
Overview Objectives of this Lecture
Logical Database Models
ER Model, Hierarchical and Network data Model and Relational Model
JDBC
SQL
Preview: Data Communications
Sahalu Junaidu
Unit 22
Objectives of this Lecture Understand the use of data modeling
Understand the different types of logical data models
Learn about Relational Data Model in detail
Understand the concept of JDBC
Learn about SQL
Sahalu Junaidu
Unit 22
Why to model data?
A model highlights the important aspects of a subject and obscures unimportant aspects of it.
A data model emphasizes features of interest to the user and makes its interaction with a DBMS transparent.
Physical data models show how the data structures are organized so that their resources are optimized.
Logical data models interprete the data in the context of the application.
The modeling phase of database design is crucial to assure an accurate representation of the user's perspective of the business.
Sahalu Junaidu
Unit 22
Logical Data Models
A logical data model is a design tool used in the design of a database system to emphasize features of interest to the user and makes interaction with a DBMS transparent.
A good logical data model is independent of the DBMS and can be moved from one management system to another.
Popular approaches to logical data models include: 1. Entity-Relationship model 2. Hierarchical and Network models. 3. Relational model.
Next we briefly discuss the Relational model.
Sahalu Junaidu
Unit 22
Relational Model
The most popular logical data model in use today is the relational model which is noted for its consistency, simplicity and data independence.
It is composed of relations, attributes, domains, keys, tuples and their representations.
A relation is a table of rows and columns. Each column of the table is an attribute.
The domain of each attribute is the collection of values that can be assigned to a particular attribute.
A principal key is one or more attribute values that uniquely identify an entity instance.
A tuple is an ordered sequence of elements. Example the sequence (p,q,r,s,t,u) is a 6-tuple. Each row is an entity instance represented by a tuple.
Sahalu Junaidu
Unit 22
Components of Relational ModelRelational modeling has many interchangeable terms for its components as
shown below: Relation, table, file
A two-dimensional table consisting of columns and rows; created from the entities of the object model.
Attribute, column, fieldThe columns of the table, usually defined from the attributes of the object model.
Tuple, row, recordThe rows of the table; derived from the entity occurrences of the object model.
Relations:A Relation is a two-dimensional table containing a set of related data. The true requirements of a relation are that: Each cell must be atomic (contain only one value). Each attribute contains the same type of physical and semantic information in all
its cells. Each tuple is unique; there can be no duplicate rows of data. The order of columns and rows is not significant.
Sahalu Junaidu
Unit 22
Relation
Typically, relations have a representation consisting the relation name, followed by a list of attributes in form of a tuple with the principal key highlighted.
e.g., ADVISOR (AdvId, Adv-Name, Adv-Phone)
The following shows a typical relational data model called an instance table.
RELATION = ADVISOR primary key: AdvId
AdvId Adv Name Adv Phone
66101 Sahalu 333-2111
66102 Al-Ghamdi 405-8888
66103 Sadiq 501-8241
66104 Badhusha 222-2357
Sahalu Junaidu
Unit 22
Relations (cont.)
The following table defines another relation for the entity Student with attributes StuID, StuName, StuPhone and AdvId.RELATION = STUDENT
In relational databases, new relations can be generated from others. For example, the relation “is advised by” can be defined between the relations STUDENT and ADVISOR.
StuId StuName StuPhone AdvId
987654 Al-Amer 452-7634 66104
978956 Al-Quasim 555-3215 66102
993421 Al-Ali 865-3476 66101
981267 Al-Fathah 894-2384 66102
Sahalu Junaidu
Unit 22
Definitions of Relational Terms
Primary keyPrimary keys are essential in relational modeling; one should be specified for each relation. A primary key uniquely identifies a record (or row) in a table; in other words, a particular primary key value returns a record that is identical to no other. A primary key is composed of one column (simple primary key) or a combination of columns (composite primary keys) that provide this unique identification. The best possibilities for primary keys are attributes that seldom change and are familiar to users. The primary key should contain the fewest columns needed to uniquely identify a record.
Simple primary key: Consider the relation ADVISOR where each value of Advisor ID
returns a unique record. Simple primary key AdvId uniquely identifies records. AdvId AdvName AdvPhone
66101 Sahalu 333-211166102 Al-Ghamdi 405-888866103 Sadiq 501-824166104 Badhusha 222-2357Sahalu Junaidu
Unit 22
Definitions of Relational Terms
Composite primary key: Consider the relation STUDENT where each student can take more
than one course. Student ID, Class, or Grade alone does not return a unique record; however, a composite primary key of Student ID-Class does. Composite primary key Student ID-Course defines unique records.
Foreign keyA foreign key is an attribute in a relation that is also a primary key in another relation. This foreign key-primary key match allows references between relations in order to locate information.
StudentID Course Grade
1001 COE312 95
1001 ENG101 90
1005 COE312 85
1006 COE430 87
1006 ICS202 95
1010 COE102 92
Sahalu Junaidu
Unit 22
Definitions of Relational TermsForeign key Example :
Relation ADVISOR where AdvID is the primary key. Relation STUDENT where StuID is the primary key and AdvID is a foreign key.
RELATION = ADVISOR RELATION = STUDENT
AdvId Adv Name Adv Phone
66101 Sahalu 333-2111
66102 Al-Ghamdi 405-8888
66103 Sadiq 501-8241
66104 Badhusha 222-2357
StuId StuName StuPhone AdvIdAdvId
987654 Al-Amer 452-7634 66104
978956 Al-Quasim 555-3215 66102
993421 Al-Ali 865-3476 66101
981267 Al-Helal 894-2384 66102
Sahalu Junaidu
Unit 22
Communication with DB from Java Application
To communicate with the DB from Java application, we need the following.
1. An interface which connects Java application and the DBMS (JDBC - Drivers)
2. A language to communicate (SQL: Structured Query Language)
1. JDBC JDBCTM API provides universal data access from the Java programming language. The
JDBC API is a Java API for accessing virtually any kind of tabular data from relational databases.
To use the JDBC API with a particular database management system, you need a JDBC technology-based driver to mediate between JDBC technology and the database. The latest Java SDK includes a JDBC-ODBC Bridge driver that makes most Open Database Connectivity (ODBC) drivers available to programmers using the JDBC API.
Sahalu Junaidu
Communication with DB from Java Application
2. SQL Structured Query Language is used to write queries to the database in
order to get information from the database and to update the information to the DB
Here we will see some simple queries [their format and some simple examples] SELECT UPDATE INSERT
Java Application
JDBC-ODBC Bridge DriverMS Access
DBMSEngine
DB
Sending query
Result of the query
Unit 22Sahalu Junaidu
Unit 22
Communication with DB from Java Application
SELECT Format:
SELECT <LIST OF COLUMNS> FROM <LIST OF TABLES> [WHERE <CONDITION(S)>] [GROUP BY <GROUPING COLUMN(S)>] [ORDER BY <ORDERING COLUMN(S)>]
Explanation: For <LIST OF COLUMNS>
a * is used to select all the columns of the specified table(s).
Individual columns can be selected by specifying the column names separated by comas.
If columns from different table are needed, then tablename.columnname is specified.
Sahalu Junaidu
Unit 22
Communication with DB from Java Application
For <LIST OF TABLES> A table name or list of table name is used
For <CONDITION(S)> The operators are relational and logical and the
operands are the column names For <GROUPING COLUMN(S)> and <ORDERING
COLUMN(S)>] List of columns are specified
Example: SELECT StuId, StuName FROM STUDENT WHERE AdvId =
“66102” The table Result of the query
978956 Al-Quasim
981267 Al-Helal
Sahalu Junaidu
StuId StuName StuPhone AdvIdAdvId
987654 Al-Amer 452-7634 66104
978956 Al-Quasim 555-3215 66102
993421 Al-Ali 865-3476 66101
981267 Al-Helal 894-2384 66102
UPDATEFormat
UPDATE <TABLE NAME> SET <COLUMN NAME> =
<VALUE> [WHERE <CONDITION>];
--if the Where clause is left out, all rows will be updated according to the Set statement.
Communication with DB from Java Application
Unit 22
Communication with DB from Java Application
Example UPDATE STUDENT SET AdvId = “66109” WHERE
StuId = “993421”
The table before update The table after update
StuId StuName StuPhone AdvId
987654 Al-Amer 452-7634 66104
978956 Al-Quasim 555-3215 66102
993421 Al-Ali 865-3476 66101
981267 Al-Helal 894-2384 66102
StuId StuName StuPhone AdvId
987654 Al-Amer 452-7634 66104
978956 Al-Quasim 555-3215 66102
993421 Al-Ali 865-3476 66109
981267 Al-Helal 894-2384 66102
Sahalu Junaidu
Unit 22
Communication with DB from Java Application
INSERT Format
INSERT INTO <TABLE NAME> [(<COLUMN LIST>)] VALUES (<VALUE LIST>);
Example INSERT INTO STUDENT VALUES (“994433”,”Al-
Ghamdi”,”866-2687”,”66105”)
The table before insert The table after insertStuId StuName StuPhone AdvId
987654 Al-Amer 452-7634 66104
978956 Al-Quasim 555-3215 66102
993421 Al-Ali 865-3476 66101
981267 Al-Helal 894-2384 66102
StuId StuName StuPhone AdvId
987654 Al-Amer 452-7634 66104
978956 Al-Quasim 555-3215 66102
993421 Al-Ali 865-3476 66109
981267 Al-Helal 894-2384 66102
994433 Al-Ghamdi 866-2687 66105Sahalu Junaidu
Unit 23
Introduction to JDBC
Overview Objectives of this lecture
JDBC and its Drivers
Connecting to Databases (Java’s Connection class)
Querying a Database (Java’s Statement class)
Obtaining Query Results (Java’s ResultSet class) Preview: Introduction to Data Communications
Sahalu Junaidu
Unit 23
Objectives of the Lecture
To have an acquintance of JDBC drivers
To know the basic issues required to connect to a database from a Java application
To be able to write simple queries and receive their results using methods in Java programs
Sahalu Junaidu
Unit 23
JDBC Basics
The JDBC (short for Java Database Connectivity) interface is a pure Java API used to execute SQL statements.
The JDBC provides a set of classes and interfaces that can be used by developers to write database applications.
Basic JDBC interaction, in its simplest form, can be broken down into four steps: 1. Open a connection to the database 2. Execute a SQL statement 3. Process the SQL statement’s results 4. Close the connection to the database.
Sahalu Junaidu
Unit 23
JDBC Drivers
As mentioned in Lecture 28, a Java application can communicate to a DBMS using specialized programs called Drivers.
The JDBC supports two database access models: two-tier and three-tier. Using a two-tier model, a Java application talks directly to the database.
This is accomplished through the use of a JDBC driver, which sends commands directly to the database.
With a two-tier database access model, the JDBC driver and the database communicate through a middle-tier system.
Sun Microsystems has defined four JDBC driver types: JDBC-ODBC bridge plus ODBC Driver Native-API Partly-Java Driver JDBC-Net Pure Java Driver Native-Protocol Pure Java Driver
Sahalu Junaidu
Unit 23
Connecting to DBMS from Java As mentioned earlier writing a Java application to communicate with a database
involves:
1. Establishing a connection with a data source
2. Sending queries and update statements to the data source
3. Processing the results
4. Closing the database Establishing a Connection:
Establishing a connection involves loading the driver and then making the connection. Loading the driver or drivers you want to use is very simple and involves just one line of code as follows:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Note: The method forName() generates ClassNotFoundException if JDBC is not installed. This is a checked exception, so we must handle it before the above statement can compile.
Sahalu Junaidu
Unit 23
Establishing a Connection Making the Connection involves creating a Connection object that links the driver
to the DBMS.
Connection con = DriverManager.getConnection(url, "myLogin", "myPassword");
or
Connection con = DriverManager.getConnection(url);
where url = “jdbc:odbc:DataSetName” Since we are using the JDBC-ODBC Bridge driver, the JDBC URL will start with
jdbc:odbc: . The rest of the URL is generally the data source name defined in the configuration of ODBC
The second version assumes you do not need to login to the computer hosting the database file.
Connection con = DriverManager.getConnection(url);
Sahalu Junaidu
Unit 23
Creating JDBC Statements and Sending SQL statements to the
data source The next step after establishing a connection is to create a Statement object using
the Connection object as follows:
Statement statement = con.createStatement();
The Statement object created above has methods which are used to send SQL
statement to the DBMS. Which method is used, depends on the SQL statement being sent. For a SELECT statement, the method to use is executeQuery() . Whereas, for statements that create or modify tables, the method to use is executeUpdate().
String query = "select * from table1";
ResultSet result = statement.executeQuery(query);
Notice that executeQuery() method returns an object of ResultSet which contains the result of the query.
Sahalu Junaidu
Unit 23
Creating JDBC Statements and Sending SQL statements to the
data source The executeUpdate() is similar, except that we are not expecting
result from the data source.
String query2 = "INSERT INTO table1 VALUES (‘a', ‘b', ‘c', 1)";
statement.executeUpdate(query2);
Sahalu Junaidu
Unit 23
Processing Results obtained from data source
The variable result , which is an instance of ResultSet , contains all the rows of the table1 parameter. In order to process each row, we need to go to the row and retrieve its values.
The method next() moves what is called a cursor to the next row and makes that row (called the current row) the one upon which we can operate.
The cursor is initially positioned just above the first row of a ResultSet object, the first call to the method next() moves the cursor to the first row and makes it the current row.
Successive invocations of the method next() move the cursor down one row at a time from top to bottom.
Sahalu Junaidu
Unit 23
Processing Results obtained from data source
The ResultSet object has a get method for each type (getString, getInt, getDouble, getLong, getFloat, etc) which can be used to retrieve the value of a field depending on its type.
For example, the following loop is use to retrieve and print the bookNumber, author and title fields of a books table.
while(result.next()) {
System.out.println(result.getString(“ColumnName1")+
"\t"+ result.getString(" ColumnName2")+
“\t"+ result.getString(" ColumnName3"));
} Note: Most of the methods of the ResultSet object (e.g next())
generate SQLException which is a checked exception, so again we must handle this exception before our program can compile.
Sahalu Junaidu