Download presentation
Presentation is loading. Please wait.
Published byOwen Newman Modified over 9 years ago
1
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
2
Contact information Email: tsli@ouhk.edu.hktsli@ouhk.edu.hk Office: Rm A0936 Tel: 27686816 Course Web Site: http://plbpc001.ouhk.edu.hk/~mt311f http://plbpc001.ouhk.edu.hk/~mt311f Assignment submission: http://plbpc001.ouhk.edu.hk/tma/login.htm
3
Continuous assessment Two assignments each carries 25% of the final continuous assessment score. Two test that carries 25% of the final continuous assessment score. According to OUHK rules, you need to pass the continuous assessment in order get a pass in the course.
4
Software Netbeans and JDK 5.5 MIT Scheme Strawberry Prolog
5
Textbooks Java Programming: Advanced Topics, by Joe Wigglesworth and Paula McMillan, 3rd Edn, Thomson Concepts of Programming Languages, by Robert Sebesta, 8 th Edn, Addison Wesley, 2003.
6
Overview of the course This course have two modules – Java Application development – Programming Languages
7
Java Application Development Object-oriented Programming in Java Graphical User Interface Network Programming with Java Java Security
8
Programming Languages Introduction to Programming Languages Variables, Data Types, and Expressions Control Structures, Subprograms, and Implementation of Subprograms Object-Oriented Programming Languages Functional and Logic Programming Languages
9
Object-Oriented Programming in Java Object-oriented programming has the following characteristics – Abstract data type – Encapsulation – Polymorphism – Inheritance
10
Tutorials You will be given a tutorial sheet each time detailing what you have to do. You need to write Java programs in the first semester. You will use Netbeans as the IDE.
11
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 describes 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.
12
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.
13
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.
14
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.
15
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.
16
'this' Every method of a class is associated with an instance of that class. For example, in the method setBalance of Account, we can access the attributes of the object that is associated with the method. However, what can we do to access the object itself instead of just an attribute?
17
'this' We can do that by using the 'this' keyword. The setBalance method can be rewritten here using the 'this' keyword: void setBalance(int b) { this.balance=b;} Usually, we do not need the 'this' keyword if we just want to access the attributes of the associated object.
18
'this' You need to use 'this' in the following situation: – there is a name conflict so that you want. example: public class ABC { int a; void meth(int a) { this.a=a; }
19
'this' – You want to pass the associated object to another method: public class ABC {... void method(..) { DEF def=new DEF(); def.meth(this);... }
20
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.
21
Static attributes The attribute name, birthday are of course properties 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.
22
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; }
23
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 student=new student(); student.name="Chan Tai Man"; Student.averageAge=23;....
24
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: student.averageAge=24; Student.averageAge=32;
25
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.
26
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.
27
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)
28
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.
29
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.
30
Static methods public class Student { String name; Date birthday; static int averageAge; static void setAverageAge(int i) { averageAge=i; }
31
Static methods The following code contains errors public class Student { String name; Date birthday; static int averageAge; static void setName(String n) { name=n; }
32
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.
33
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[]) {.... }
34
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.
35
Main method public class Student { String name; Date birthday; static int averageAge; public static main(String st[]) { Student student=new Student(); student.name="Li Tak Sing"; averageAge=23; student.averageAge=23; Student.averageAge=23; }
36
Compile a Java program The class must be stored in a file called Student.java compile using the command javac Student.java A file Student.class will be generated To run the program, use the command java Student
37
Java programs When a Java program is compile, the product is a file with extension.class. The file is in the format known as bytecode. Bytecode is not machine code. That is to say, it is not directly executable in any computer. Instead, it needs an interpreter to interpret the code and then execute it accordingly.
38
Java programs The interpreter is called a virtual machine or VM in short. This property has two consequences: – It runs slower than those programs that are directly compiled to machine code like C++. – The same bytecode programs can be executed in many different platforms as long as a VM is available. This is the reason why Java is so popular on the Internet.
39
Methods The name of a method together with the types of its parameters are called the signature of the method. For example, the method: public void meth1(int abc, String def) The signature of the method is the name meth1, the parameter types which is first an integer and then later a string.
40
Methods The return type of a method is the type of the value to be returned after calling the method. Consider the following class:
41
Methods public class MethodClass { int a=2; public int sum(int b) { return a+b; } public static void main(String st[]) { int p=4; MethodClass mClass=new MethodClass(); int result=mClass.sum(p); System.out.println("sum of "+2+"+"+b+" is "+result); }
42
Signature of a method No two methods of a class can have the same signature. However, two methods of a class can have the same name provided that the parameter types are different. So a class can have the following methods:
43
Overloading Methods public class ABC { public void myMethod(int a) {..... } public void myMethod(String a) {...... } When you call myMethod of an object of ABC, the actual method to be called will be dependent on the type of the parameter.
44
Overloading methods Consider the following code:..... ABC abc=new ABC(); abc.myMethod(3); // this would call the version that accepts an integer abc.myMethod("abc"); // this would call the version that accepts a string.....
45
Constructor A constructor is like a method except that – it should have the same name as the class; – it should have no return type. A constructor will be called when you use the 'new' keyword to create an instance of a class.
46
Default Constructors If you do not provide any constructor, the Java will create a default constructor for it.
47
Default Constructors When the default constructor is executed, all its attributes will be initialized according to the following rules: – if the attribute is numerical, like int, byte, float etc., the attribute is assigned the value of 0. – if the attribute is a class variable, then it is initialized to "null" which represent that the variable is not referring to any object yet. – if the attribute is boolean, then it will be assigned the value of false.
48
Default Constructors public class ABC { int a; float b; boolean c; ABC d; public static void main(String st[]) { ABC abc=new ABC(); //default constructor System.out.println(abc.a+" "+abc.b+" "+abc.c+" "+abc.d); }
49
Default Constructors The output of the above program is: 0 0.0 false null
50
Default Constructors If you want to initialize the attributes to other value, you can do it like this: public class ABC { int a=1; float b=2; boolean c=true; ABC d=null; public static void main(String st[]) { ABC abc=new ABC(); System.out.println(abc.a+" "+abc.b+" "+abc.c+" "+abc.d); }
51
Default Constructors The output of the above program is: 1 2.0 true null
52
Constructors The above method has a problem in that all instance of ABC would be the same when they are just created, i.e., the attribute a will definitely be 1, the attribute b will be 2.0 etc. If we want to have the attributes initialized to different values depending on different situations, we need to write our own constructors.
53
Constructor A constructor is a piece of code that will be executed when a new instance of class is created. Just like methods, a constructor can have a number of parameters. Just like methods, you overload a constructor provided that these constructors have different signatures. Unlike methods, a constructor cannot have return value.
54
Constructors public class ABC { int a=1; float b=2; boolean c=true; public ABC(int aa) { a=aa; } public ABC(float bb) { b=bb; } public ABC(boolean cc) { c=cc; }
55
Constructors... ABC a1=new ABC(); //error, now ABC does not have a default // constructors ABC a2=new ABC(10); //a2.a=10, a2.b= 2.0, a2.c = true ABC a3=new ABC(10.0); //a3.a=1, a3.b=10.0, a3.c= true ABC a4=new ABC(false); //a3.a=1, a3.b=2.0, a3.c=false.
56
Constructors Consider a change in ABC: public class ABC { int a=1; float b=2; boolean c=true; public ABC(float bb) { b=bb; } public ABC(boolean cc) { c=cc; }
57
Constructor... ABC a1=new ABC(); //error, now ABC does not have a default // constructors ABC a2=new ABC(10); //a2.a=1, a2.b= 10.0, a2.c = true ABC a3=new ABC(10.0); //a3.a=1, a3.b=10.0, a3.c= true ABC a4=new ABC(false); //a3.a=1, a3.b=2.0, a3.c=false.
58
Garbage collection When you create a new object, it takes up the computer's resources. So as you create more and more objects, it is possible that all the computer's resources are used up. So it is necessary to release those resources that have been taken up by objects that will never be used again.
59
Garbage Collection Consider the following code: for (int i=0;i<10;i++) { ABC abc=new ABC();.... } In each loop, an ABC is created. Assume that once the loop is finished, these ABCs are no longer used and referenced, then the resources taken up by these ABCs can be released to other use.
60
Garbage collection In Java, this is done by a process called garbage collection. From time to time, the process will check whether there are resources that are taken up by objects that are no long used. It will then release the resources back to the system.
61
Finalize When the garbage collection process is releasing the resource taken up by an object, it is possible that this object is holding some important information. For example, this object may have an opened file with some contents that have not been written to the file properly. So by releasing the resources held by the object may result in loosing this contents.
62
Finalize In order to prevent this from happening, we need to have some code to close the file before the resources are released. We need to use the finalize method for this purpose.
63
Finalize The finalize method must have no parameters and no return type. So it is always declared as: public void finalize() When the garbage collector is going to release the resource of an object, it will invoke the finalize method of the object first.
64
Finalize So it is the programmer's responsibility to put the code in the finalize method to do whatever it need to do before the resources are released, for example, close a file or close a network connection. However, in real Java applications, you rarely use the finalize method because it is usually good habit to close a file when you are done with the file. Not to wait until the object is garbage collected.
65
Packages A package is a collection of classes. It is very similar to directories in a file system. In a file system, a directory can have a number of other directories and files. So a package can contain a number of other packages and classes.
66
Packages For example, you have been using the following command many times: System.out.println("...."); Actually, System is a class defined in Package java.lang. So here, java is a package, lang is also a package that is defined in java and then System is a class defined in lang. Then, out is a static object of the class System. println is a method of the object out.
67
Packages So actually, the above statement can be changed as: java.lang.System.out.println("...");
68
Packages The following statement in a java file define the package that the class is in: package myPackage; When a class is defined in myPackage, then the class file should be put under a directory called myPackage.
69
Packages Consider the following java file: package abc.def; public class MyClass { public void method() {.... } static int aStaticVariable=2; }
70
Packages After compilation of the file, the MyClass.class file should be put in the following directory: abc/def When other programs wants to use MyClass, it can be referred to as: abc.def.MyClass
71
Packages If you do not want to use that long name, you can have the following statement: import abc.def.MyClass; This statement will tell the compiler where to find MyClass and therefore we can simply refer to the class by using MyClass, not the full name.
72
Packages The way of using the import keyword is: import abc.def.*; This statement inform the compiler to look for all classes in the package abc.def, not just MyClass as that in the last statement. So all classes defined in the directory abc/def can be used without the need of the full name.
73
Packages So, when you want to use a class ABC in a package def.ghi, you can do either of the following ways: – use the full name: def.ghi.ABC – include the statement: import def.ghi.ABC; and then you can refer to the class as ABC in the program. – include the statement: import def.ghi.*; and then you can refer to the class as ABC.
74
Packages There are three situations where you do not need to specify the package at all: – The code that uses the class is in the same package of the class. – The class belongs to the package java.lang. This package hold the most fundamental classes of Java and therefore there is no need to use either the import statement or the full name for classes in that directory. – The class does not belong to any package.
75
Packages That is why when you use System.out.println(".."), you do not need to preceed it with java.lang.
76
Packages When you create a project in Netbeans, you will be asked about the package name. Then, usually, when you create a class, the class will be placed in that package.
77
Where to find a package We know that when a class ABC is defined in a package def.ghi, then ABC.class should be found in the directory def/ghi. However, how can the Java system knows where is def/ghi? The is done by either using the environment variable called CLASSPATH or you can set the classpath when you run the java command: java -classpath=... ABC
78
Where to find a package The other way is that Java will look for the current directory. ABC.class is actually at: /jkl/mno/def/ghi/ABC.class, Then, in order for the Java interpreter to find the class, we can set the classpath to /jkl/mno or we run the command at the directory /jkl/mno.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.