Li Tak Sing COMPS311F Introduction 1. Introduction Name: Li Tak Sing ( 李德成 ) Tel: 27686816...

Post on 19-Jan-2018

214 views 0 download

description

Text books There are two textbooks: Introduction to JAVA Programming 9 th Edn, by Y. Daniel Liang, Pearson Education. Concepts of Programming Languages, 9 th Edn, by Robert W. Sebesta, Pearson Education You do not need to by any of the textbooks if you have your own Java textbook or programming languages textbook. 3

Transcript of Li Tak Sing COMPS311F Introduction 1. Introduction Name: Li Tak Sing ( 李德成 ) Tel: 27686816...

Li Tak Sing

COMPS311FIntroduction

1

IntroductionName: Li Tak Sing (李德成 )Email: tsli@ouhk.edu.hkTel: 27686816Room: A0916Course Web site:

http://plbpc001.ouhk.edu.hk/~comps311fYou can find course schedule, handle out,

assignments there. You will also need to submit the assignments via a link found there.

You can also download all the course materials of the distance learning version of the course at the website.

2

Text booksThere are two textbooks:

Introduction to JAVA Programming 9th Edn, by Y. Daniel Liang, Pearson Education.

Concepts of Programming Languages, 9th Edn, by Robert W. Sebesta, Pearson Education

You do not need to by any of the textbooks if you have your own Java textbook or programming languages textbook.

3

Assessment policyTwo tests

Test 1: (15%)Test 2: (15%)

Examination (70%)In order to pass the course, the total score

and the score in the examination must both be greater than 40.

4

Contents of the courseUnit 1: Object-oriented programming (3 weeks)Unit 2: Multithreading (3 weeks)Unit 3: Networking and Web services (3 weeks)Unit 4: Database programming (2 weeks)Unit 5: Web Programming (3 weeks)Unit 6: XML (3 weeks)Unit 7: Security (3 weeks)Unit 8: Programming paradigms and languages

(2 weeks)Unit 9: Variables, types, expressions and

assignment statements (2 weeks)Unit 10: Control structures (2 weeks)

5

Unit 1 Object-oriented programmingYou can download the PDF of the materials

of unit 1 at: http://plbpc001.ouhk.edu.hk/~comps311f

6

Abstract data typeAbstraction: to describe an object using the

most important information only. For example, there are thousands of

components of a car. However, if you are asked to describe a car, you would not describe it in terms of all of its component. Rather, you would just select a few important components to describe it. For example, a car is something that has wheels, steering wheels, engine and seats.

7

Java abstract data typepublic class car { Wheel wheel[]=new Wheel[4]; SteeringWheel steeringWheel; Engine engine;}

This is an abstract data type of a car The car is described in terms of three of its main

components: wheel, steering wheel and the engine. Java programs are collections of classes All program codes are stored inside classes Java is a strong typing language which means that all errors

regarding typing will be reported. You also need to declare the type of all entities before they can be used.

8

Java abstract data typeA bank accountpublic class Account { int balance;}

This class now only contains data, no program code. This class contains one field called balance which is an integer. Usually when you define a class, you also define some procedures to manipulate the attributes of the class. They are called methods in OO terms. For example, we can have two methods, one to get the balance, the other to set the balance.

9

Bank account with setter and getterpublic class Account { int balance; void setBalance(int b) { balance=b;} int getBalance() {return balance;}}

For method setBalance, a parameter is passed into the method which is an integer named b. In fact, the method also have access to another entity, which is the bank account itself. Each method of a class is associated with an instance of the class. So in the code inside the method setBalance, we have accessed b, which is passed as a parameter, and we have accessed balance, which an attribute of the instance of Account.

For method getBalance, it does not have any parameter, so the code inside getBalance can only access the content of the associated Account.

10

A program that uses Account.....Account account=new Account(); //create a new accountaccount.setBalance(100); //set the balance to 100System.out.println(account.getBalance()); //print the //balance....

In the above code, a new instance of Account, account, is created. Then the setBalance method of account is called with 100 as the parameter. Then, 100 is assigned to the balance attribute of account.

11

Static attributesAttributes model the properties of an

instance of a class. However, there are properties that are those of the whole class, not just an instance.

For example, assume that we have a class for OUHK student.

12

Static attributesThe attribute name, birthday is of course a

property of a particular instance of the class Student.

However, the average age of all students is not a property of any particular student. Instead it is the property of all students. In Java term, we can say that the average age of all students is the property of the class Student.

13

Static attributesThe property of a class is defined as static

attribute using the static keyword:public class Student { String name; Date birthday; static int averageAge;}

14

Static attributesA static attribute is the property of a class,

not that of a particular instance. So it is referenced using the name of the class:

....Student s=new student();s.name="Chan Tai Man";Student.averageAge=23;....

15

Static attributesNote that it is ok to access a static attribute

through either an object or the class. So both of the following two statements are correct:

s.averageAge=24;Student.averageAge=32;

16

Static attributesHowever, even if you access a static

attribute using an instance of the class, the accessed attribute is still nothing to do with that instance.

The name of the class is not needed if you want to access a static attribute of a class inside a method of the same class.

17

Static attributespublic class ABC { static int def; public void meth() { def=4; }}

The static attribute def of ABC is referenced inside the method meth of ABC. There is no need to specify the class name ABC here.

18

Static attributesHowever, if you like, you can replace def

in the above program by any of the followings:this.def (This is only valid if it is used

inside a method of ABC)ABC.def (This is valid anywhere in your

program)

19

ExampleStudent s1=new Student();Student s2=new Student();

s1.name="Chan";s1.averageAge=20;s2.name="Lee";s2.averageAge=23;System.out.println(s1.name+" "+s1.averageAge+"

"+s2.name+" "+s2.averageAge);

The output is: Chan 23 Lee 23

20

Static methodsJust like static attributes, we can also have

static methods. A static method can access all static

attributes of the class. A static method cannot access non-static

attributes as the static method does not have an associated instance.

21

Static methodsJust like static attributes, a static method

should be accessed through the name of the class. But you can still access it through the name of an object or using 'this' or even without any qualifier if inside a method of the same class. However, in all cases, the static method is still not associated with any instance of the class.

22

Static methodspublic class Student { String name; Date birthday; static int averageAge; static void setAverageAge(int i) { averageAge=i; }}

23

Static methodsThe following code contains errorspublic class Student { String name; Date birthday; static int averageAge; static void setName(String n) { name=n; }}

24

Static methodsHowever, the following code is correct:public class Student { String name; Date birthday; static int averageAge; static void setName(Student s, String n) { s.name=n; }}

A static method cannot directly access non-static attributes of the class. But it can access it through an instance of the class.

25

Main programA main program in Java must be a public

and static method of a class in the following form:

public class Student { .... public static void main(String st[]) { .... }}

26

Main methodSince a main method is a static method, it

can only access static attributes and methods of the class.

If you want to access non-static attributes, you need to create an instance of the class first and then access them through the instance.

27

Main methodpublic class Student { String name; Date birthday; static int averageAge; public static main(String st[]) { Student s=new Student(); s.name=“Chan Tai Man”; averageAge=23; s.averageAge=23; Student.averageAge=23; }}

28

InheritanceConsider the staff of a company.We want to have a class to model all the

staff of a company. The common attributes of all of these staff are:nameaddressdate of birthrank

29

Inheritancepublic class Staff { private String name; private String address; private Date dateOfBirth; private String rank; public Staff(String _name, String _address, Date _dateOfBirth, String _rank) { name=_name; address=_address; dateOfBirth=_dateOfBirth;

rank=_rank; } public String name() {return name;} public String address() {return address;} public Date dateOfBirth() {return dateOfBirth;} public String rank() {return rank;}}

30

InheritanceNow, the staff can be further classified as

clerical staff, managerial staff. Do we need a blank new class to model a clerical staff?

Obviously, a clerical is also a staff and therefore it should have all the attributes and methods of a staff.

31

InheritanceIt should also has additional attributes and

methods for a clerical staff. For example, it may be required to store the typing speed.

32

Inheritancepublic class Clerical { private String name; private String address; private Date dateOfBirth; private String rank; public Clerical (String _name, String _address, Date _dateOfBirth, String _rank, int _typingSpeed) { name=_name; address=_address; dateOfBirth=_dateOfBirth; rank=_rank; typingSpeed=_typingSpeed; } public String name() {return name;} public String address() {return address;} public Date dateOfBirth() {return dateOfBirth;} public String rank() {return rank;} private int typingSpeed; public void setTypeingSpeed(int s) {typingSpeed=s;} public int typingSpeed() {return typingSpeed;}}

33

InheritanceFor managerial staff, we need to store

professional qualification.

34

public class Managerial { private String name; private String address; private Date dateOfBirth; private String rank; public Managerial (String _name, String _address, Date _dateOfBirth, String _rank, String _professionalQualification) { name=_name; address=_address; dateOfBirth=_dateOfBirth; rank=_rank;

professionalQualification=_professionalQualification; } public String name() {return name;} public String address() {return address;} public Date dateOfBirth() {return dateOfBirth;} public String rank() {return rank;} private String professionalQualification; public void setProfessionalQualification(s) {professionalQualification=s;} public String professionalQualification() {return professionalQualification;}}

35

InheritanceThe disadvantage of having these Clerical

and Managerial classes:lots of code has been duplicated. So if we

want to add an attribute to all staff, say, the date that the staff jointed the company, then it has to be updated in two places instead of one.

The code does not show the relationship between Staff, Clerical and Managerial. It seems that they are classes with no relationship at all.

36

InheritanceIn fact, we need a mechanism so that we

can create Clerical, Managerial based on Staff.

This is done in Java using the 'extends' keyword.

37

Inheritancepublic class Clerical extends Staff { private int typingSpeed; public void setTypeingSpeed(int s) {typingSpeed=s;} public int typingSpeed() {return typingSpeed;}}

public class Managerial extends Staff { private String professionalQualification; public void setProfessionalQualification(s) {professionalQualification=s;} public String professionalQualification() {return

professionalQualification;}}

38

InheritanceIf we draw the contents of Clerical and

Managerial, they look like this:

Staff

Clerical

Staff

Managerial

39

InheritanceIn the above examples, Clerical is said to

inherit all attributes and methods of Staff with some additional attributes and methods.

So, although we did not state it explicitly, a Clerical object would still has the name attribute, the dateOfBirth attribute, etc.

Staff is said to be the super class of Clerical. Clerical is said to be the derived class, or the sub class of Staff.

40

InheritanceHowever, the latest Clerical and Managerial

classes are not without problems.In staff, it has a constructor which accepts

several parameters. So if Clerical is also a staff, then how can a Clerical be constructed in order to initialize the embeded Staff inside Clerical?

41

InheritanceSince Clerical is also a Staff, therefore in

the constructor of Clerical, we need to invoke the constructor of Staff in order to initialize the attributes of Staff.

This is done by using the 'super' keyword.

42

Inheritancepublic class Clerical extends Staff { private int typingSpeed; public void setTypeingSpeed(int s) {typingSpeed=s;} public int typingSpeed() {return typingSpeed;}

public Clerical(String _name, String _address, Date _dateOfBirth, String _rank, int _typingSpeed) { super(_name, _address, _dateOfBirth, _rank);

typingSpeed=_typingSpeed; }

}

43

ConstructorIf a class B is extended from a class A,

when an instance of B is created, we must first create an instance of A and then use this A to create a B.

Therefore, in the constructor of B, we must execute the constructor of A first.

If we do not execute the constructor of A in the constructor of B explicitly, then Java will invoke the default constructor of A for you.

44

Constructorpublic class A {public A() { System.out.println("the constructor of A is called"); }}

public class B extends A {public B() { System.out.println("the constructor of B is called"); }}

45

ConstructorWhen the following code is executed:...B b=new B();...

The following would be displayed:the constructor of A is calledthe constructor of B is called

46

Constructorpublic class A {public A(int i) { System.out.println("the constructor of A is called "+i); }}

public class B extends A {public B() { System.out.println("the constructor of B is called"); }}

47

ConstructorThe program has a syntax error. Since we

do not invoke the constructor of A in the constructor of B, so Java invokes the default constructor of A. The default constructor has no parameter. Unfortunately, A does not have that constructor, so it result in syntax error.

In order to solve the problem, we need to call the constructor of A explicitly.

48

Constructorpublic class A {public A(int i) { System.out.println("the constructor of A is called "+i); }}

public class B extends A {public B() { super(3); System.out.println("the constructor of B is called"); }}

49

ConstructorThe super constructor must be the first

statement in constructor of a subclass.If the super constructor is not called in the

constructor of a subclass, then the default constructor of the superclass will be called. In this case, if the superclass does not have the default constructor, an error will be reported.

50

InterfaceA Java class can have only one super class.

That is to say, Java does not allow multiple inheritance.

51

Problem of multiple inheritanceAssume that we have a class A. A has two

subclasses B and C. Now, if multiple inheritance is allowed, then we may have the case that a class D which is the subclass of both B and C.

52

Problem of multiple inheritance

A

B C

D

53

Multiple inheritanceIf we draw the content of B, C, it would look

like this:

A

B

A

C

54

Problems of multiple inheritanceSo if we look at the contents of D:

A

B

A

C

D

D55

Problems of multiple inheritanceSo we can see that now inside an object of

D, there are actually two instances of A and this is actually physically meaningless.

That is why Java does not allow multiple inheritance. That is to say, all class can have only one superclass.

In Java, if you do not use the 'extends' keyword in declaring a class, then Java assumes that you want to extend the class from Object.

56

ObjectObject is the root class of all classes in

Java. So all java objects are actually instances of Object.

So Object is the only class in Java that does not have a superclass.

57

InterfaceAs Java does not allow multiple inheritance,

then how can we model a real world object that have multiple characteristics?

58

InterfaceFor example, consider the staff example we

mentioned earlier. All the staff can be classified as permanent staff and temporary staff.

For a permanent staff, we would record the date when he/she jointed the company.

For a temporary staff, we would record the date that the contract ends.

59

InterfaceSo a staff can be classified into four groups:

permanent clerical stafftemporary clerical staffpermanent managerial stafftemporary managerial staff

60

InterfaceIf multiple inheritance is allowed, we would

have a class diagram like this:

61

Interface

Staff

Clerical Managerial Permanent Temporary

PermanentClerical

TemporaryClerical

PermanentManagerial

TemporaryManagerial

62

InterfaceWe can do this using interface.

As the name implies, an interface only define the interface of a class of objects. It does not give any actual implementation of the objects.

63

InterfaceFor example, consider the following

interface

public interface Permanent { public Date dateJoining();}

The above statements define an interface called Permanent. This interface has a method called dateJoining but it does not give the implementation of the method.

64

InterfaceSo we can use this interface to define a

PermanentClerical class:

public class PermanentClerical extends Clerical implements Permanent { private Date dateJoining; public Date dateJoining() {return dateJoining;}public PermanentClerical(String _name, String _address, Date _dateOfBirth, String _rank, int _typingSpeed, Date

_dateJoining) { super(_name, _address, _dateOfBirth, _rank,_typingSpeed); dateJoining=_dateJoining; }}

65

InterfaceSo we can see that the above code

implements the method dateJoining defined in the interface Permanent.

Now, a PermanentClerical object is a Clerical object and also a Permanent object. So we can pass a PermanentClerical object to methods that accepts either a Clerical object, a Staff object, or a Permanent object.

66

InterfaceWe can also have the following statements:

PermanentClerical p=new PermanentClerical("Chan Tai Man","ABC Street",

new Date(78,1,2),"CO", 80,new Date(99,3,12));

Clerical c1=p; //ok, p is a Clerical

67

InterfacePermanent p1=p; // ok, p is a PermanentStaff s1=p; // ok, p is a Staff

Note that Permanent is an Interface, there we cannot create a Permanent object using the new keyword:Permanent p1=new Permanent();

However, it is ok to declare a variable or attribute of type Permanent and assign a Permanet object to it.

68

InterfaceWe cannot create a Permanent object

directly, but we can create a PermanentClerical object and then assign this object to a variable of type Permanent.

69

instanceofSo we can see that when you are given a

variable of type Staff, it can actually refer to a Staff, a ClericalStaff, a PermanentClerical or a Managerial etc. So, how do we know the actual identity of the object referenced by a variable? This is done by the operator 'instanceof'.

70

instanceofStaff p=new PermanentClerical("Chan Tai Man","ABC Street", new Date(78,1,2),"CO", 80, new Date(99,3,12));if (p instanceof Staff) { System.out.println("p is an instance of Staff"); //true}if (p instanceof Permanent) {System.out.println("p is an instance of Permanent"); //true}if (p instanceof Clerical) {System.out.println("p is an instance of Clerical"); //true}if (p instanceof Managerial) {System.out.println("p is an instance of Managerial"); //false}

71

InterfaceIf we draw the contents of

PermanentClerical, it would look like this:

ClericalStaff

PermanetClerical

72

InterfaceWe can see that in the last diagram, there

is no block corresponds to the interface Permanent. This is because Permanent is only an interface and does not provide any data to be stored there.

73

CastingAs stated earlier, a Staff variable can

actually refers to a Clerical object. So if this is the case, how can we access this object as a Clerical object?

Staff p=abc.method(); // this method returns a Staff object which is // actually a Clerical object.int s=p.typingSpeed(); //error as p is a Staff variable and therefore we

cannot //access the typingSpeed method.

74

CastingIn order to access the typingSpeed method,

we need casting:Clerical c=(Clerical)p;int i=c.typingSpeed();

Note that if p is really not a Clerical, then a runtime error will be reported.

75

CastingStaff p=new Clerical(.....);

Clerical s=(Clerical)p; //okPermenantClerical p2=(PermenantClerical)p; //runtime error because p

is //not a PermenantClericalManagerial m=(Managerial)p; //runtime error because p is //not a Managerial

Permanent p3=(Permanent)p; //runtime error because p is not //a Permanent

76

CastingStaff p=new PermanentClerical(.....);

Clerical s=(Clerical)p; //okPermenantClerical p2=(PermenantClerical)p; //okManagerial m=(Managerial)p; //runtime error because p is //not a Managerial

Permanent p3=(Permanent)p; //ok

77

AccessibilityAll private attributes and methods of a

class are not accessible even in a subclass of that class.

All public attributes and methods of a class are accessible in its subclass.

78

Accessibilitypublic class A { public int i=0; private int j=0;}

public class B extends A { public void method() { int k=i+1; //correct int m=j+1; //error because j is not accessible. }}

79

AccessibilityA class and its subclass does not have to

be in the same package.So if an item of a class does not have an

access modifier, it would not be accessible in a subclass if the subclass is not in the same package as its superclass.

80

Accessibilitypackage package1;public class A { public int i=0; private int j=0; int k=0;}

package package2;public class B extends package1.A { public void method() { int m=i+1; //correct int n=j+1; //error because j is not accessible. int p=k+1; //error because A and B are not in the same package. }}

81

AccessibilityThe 'protected' access modifier specifies

that an item is to be accessible by its subclasses.

82

Accessibilitypackage package1;public class A { public int i=0; private int j=0; protected int k=0;}

package package2;public class B extends package1.A { public void method() { int m=i+1; //correct int n=j+1; //error because j is not accessible. int p=k+1; //correct }}

83

PolymorphismIn the same class, we can have two

methods with the same name as long as they have different signatures. This is called overloading.

When a class B is a subclass of class A, class B can has a method that has the same signature of a method in A. This is called overriding.

84

Polymorphismpublic class A { public void meth(int i, int j) { System.out.println("the sum is "+(i+j)); }}

public class B extends A { public void meth(int i, int j) { System.out.println("the product is "+(i*j)); }}

85

PolymorphismSince B is a subclass of A, this means that

an object of B is actually also an object of A. For example, in the staff example earlier, a Clerical object is also a Staff object.

So if we have a variable of type A, it can be assigned to an object of B or an object of A.

86

PolymorphismA a1=new A(); //correctA a2=new B(); //correct, B is also A

B b1=new A(); //incorrect, A is not BB b2=new B(); //correct

From this, we can see that a variable of A can actually refer to an object of B or an object of A.

A variable of B in this example can only refer to an object of B.

87

Dynamic bindingbinding means the assignment of a value to

an item.dynamic refers to something that happens

during the execution of a program.So dynamic binding means the assignment

of a value to an item during the execution of a program.

88

Dynamic bindingOn the other hand, static binding refers to

the assignment of a value to an item before the program is executed.

For example, the range of a byte in Java is from -128 to 127. Here, the value is -128 to 127, the item is the range of a byte. This assignment happened well before the execution of any program. So this binding is static.

89

BindingConsider the following Java code:

int i=4;here, the type of i is int. This binding

happens before the program is executed, so this binding is static.

the value of i is set to 4. This binding happens after the program is executed, so the binding is dynamic.

90

PolymorphismConsider again the following program:public class A { public void meth(int i, int j) { System.out.println("the sum is "+(i+j)); }}

public class B extends A { public void meth(int i, int j) { System.out.println("the product is "+(i*j)); }}

91

Polymorphism...A a=new A();a.meth(3,4);

a=new B();a.meth(3,4);....

The output of the program fragment is:the sum is 7the product is 12

92

Dynamic bindingFrom this example, we can see that when

the method a.meth() is first called, the version defined in A is called. However, in the second case, the version defined in B is called.

So you can see that although the same variable 'a' is used, the actual version of meth() to be invoked changed according to the actual type of the object that it refers to.

93

Dynamic bindingWe would say that the binding of which

version of meth to invoke is done during runtime. So this is dynamic binding.

94

PolymorphismPolymorphism refers to the case when a

method is invoked, the actual version to be invoked would depend on the actual type of the object.

This has to be done with dynamic binding.

95

Use of polymorphismConsider a class that models different

geometrical shapes. The class:public class Shape { public double area() { // we do not know how to find the area yet. return 0; } public double volumeOfCylinder(double h) { //this method return the

volume of //the cylinder using this shape as the base. return area()*h; }}

96

Use of polymorphismNow, we have a class that represents all

squares. Obviously a square is a shape. So Square should be subclass of Shape. However, now we know how to calculate the area of a Square. So we have:

97

Squarepublic class Square extends Shape { private double length; public Square(double length) { this.length=length; } public double length() {return length;} public double area() {return length*length;}}

98

SquareNow, can we still use the

volumeOfCylinder() method of Shape to find the volume of the cylinder using the square as the base?

....Square square=new Square(4);double volume=square.volumeOfCylinder(3);....

99

Circlepublic class Circle extends Shape { private double radius; public Circle(double radius) { this.radius=radius; } public double radius() {return radius;} public double area() {return Math.PI*radius*radius;}}

100

CircleAgain, we can still use the volumeOfCylinder

method of Shape to find the volume of the cylinder which uses the circle as the base:

....Circle c=new Circle(3);double vol=c.volumeOfCylinder(2);....

101

PolymorphismIf we do not have polymorphism, then we

need to duplicate the code for volumeOfCylinder in Square and Circle.

102