Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Li Tak Sing COMPS311F Introduction 1. Introduction Name: Li Tak Sing ( 李德成 ) Tel: 27686816 Room: A0916 Course."— Presentation transcript:

1 Li Tak Sing COMPS311F Introduction 1

2 Introduction Name: Li Tak Sing ( 李德成 ) Email: tsli@ouhk.edu.hktsli@ouhk.edu.hk Tel: 27686816 Room: A0916 Course Web site: http://plbpc001.ouhk.edu.hk/~comps311f http://plbpc001.ouhk.edu.hk/~comps311f You 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

3 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

4 Assessment policy Two 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

5 Contents of the course Unit 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

6 Unit 1 Object-oriented programming You can download the PDF of the materials of unit 1 at: http://plbpc001.ouhk.edu.hk/~comps311f http://plbpc001.ouhk.edu.hk/~comps311f 6

7 Abstract data type Abstraction: 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

8 Java abstract data type public 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

9 Java abstract data type A bank account public 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

10 Bank account with setter and getter public 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

11 A program that uses Account..... Account account=new Account(); //create a new account account.setBalance(100); //set the balance to 100 System.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

12 Static attributes Attributes 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

13 Static attributes The 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

14 Static attributes The property of a class is defined as static attribute using the static keyword: public class Student { String name; Date birthday; static int averageAge; } 14

15 Static attributes A 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

16 Static attributes Note 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

17 Static attributes However, 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

18 Static attributes public 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

19 Static attributes However, 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

20 Example Student 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

21 Static methods Just 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

22 Static methods Just 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

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

24 Static methods The following code contains errors public class Student { String name; Date birthday; static int averageAge; static void setName(String n) { name=n; } 24

25 Static methods However, 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

26 Main program A 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

27 Main method Since 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

28 Main method public 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

29 Inheritance Consider 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: name address date of birth rank 29

30 Inheritance public 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

31 Inheritance Now, 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

32 Inheritance It should also has additional attributes and methods for a clerical staff. For example, it may be required to store the typing speed. 32

33 Inheritance public 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

34 Inheritance For managerial staff, we need to store professional qualification. 34

35 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

36 Inheritance The 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

37 Inheritance In 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

38 Inheritance public 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

39 Inheritance If we draw the contents of Clerical and Managerial, they look like this: Staff Clerical Staff Managerial 39

40 Inheritance In 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

41 Inheritance However, 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

42 Inheritance Since 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

43 Inheritance public 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

44 Constructor If 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

45 Constructor public 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

46 Constructor When the following code is executed:... B b=new B();... The following would be displayed: the constructor of A is called the constructor of B is called 46

47 Constructor public 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

48 Constructor The 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

49 Constructor public 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

50 Constructor The 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

51 Interface A Java class can have only one super class. That is to say, Java does not allow multiple inheritance. 51

52 Problem of multiple inheritance Assume 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

53 Problem of multiple inheritance A BC D 53

54 Multiple inheritance If we draw the content of B, C, it would look like this: A B A C 54

55 Problems of multiple inheritance So if we look at the contents of D: A B A C D D 55

56 Problems of multiple inheritance So 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

57 Object Object 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

58 Interface As Java does not allow multiple inheritance, then how can we model a real world object that have multiple characteristics? 58

59 Interface For 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

60 Interface So a staff can be classified into four groups: permanent clerical staff temporary clerical staff permanent managerial staff temporary managerial staff 60

61 Interface If multiple inheritance is allowed, we would have a class diagram like this: 61

62 Interface Staff Clerical Managerial PermanentTemporary PermanentClerical TemporaryClerical PermanentManagerial TemporaryManagerial 62

63 Interface We 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

64 Interface For 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

65 Interface So 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

66 Interface So 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

67 Interface We 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

68 Interface Permanent p1=p; // ok, p is a Permanent Staff 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

69 Interface We 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

70 instanceof So 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

71 instanceof Staff 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

72 Interface If we draw the contents of PermanentClerical, it would look like this: ClericalStaff PermanetClerical 72

73 Interface We 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

74 Casting As 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

75 Casting In 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

76 Casting Staff p=new Clerical(.....); Clerical s=(Clerical)p; //ok PermenantClerical p2=(PermenantClerical)p; //runtime error because p is //not a PermenantClerical Managerial m=(Managerial)p; //runtime error because p is //not a Managerial Permanent p3=(Permanent)p; //runtime error because p is not //a Permanent 76

77 Casting Staff p=new PermanentClerical(.....); Clerical s=(Clerical)p; //ok PermenantClerical p2=(PermenantClerical)p; //ok Managerial m=(Managerial)p; //runtime error because p is //not a Managerial Permanent p3=(Permanent)p; //ok 77

78 Accessibility All 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

79 Accessibility public 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

80 Accessibility A 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

81 Accessibility package 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

82 Accessibility The 'protected' access modifier specifies that an item is to be accessible by its subclasses. 82

83 Accessibility package 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

84 Polymorphism In 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

85 Polymorphism 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)); } 85

86 Polymorphism Since 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

87 Polymorphism A a1=new A(); //correct A a2=new B(); //correct, B is also A B b1=new A(); //incorrect, A is not B B 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

88 Dynamic binding binding 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

89 Dynamic binding On 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

90 Binding Consider 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

91 Polymorphism Consider 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

92 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 7 the product is 12 92

93 Dynamic binding From 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

94 Dynamic binding We would say that the binding of which version of meth to invoke is done during runtime. So this is dynamic binding. 94

95 Polymorphism Polymorphism 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

96 Use of polymorphism Consider 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

97 Use of polymorphism Now, 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

98 Square public 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

99 Square Now, 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

100 Circle public 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

101 Circle Again, 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

102 Polymorphism If we do not have polymorphism, then we need to duplicate the code for volumeOfCylinder in Square and Circle. 102


Download ppt "Li Tak Sing COMPS311F Introduction 1. Introduction Name: Li Tak Sing ( 李德成 ) Tel: 27686816 Room: A0916 Course."

Similar presentations


Ads by Google