Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Case Studies in Software Design - Workshop 2. Intro to Java - Classes and Objects In order to use Java properly, we need to understand how to define classes, methods and objects. The aim of this workshop is to introduce the relevant mechanism and syntax to do just that and to show how these structures are used in some simple applications. We shall also touch on issues of inheritance and polymorphism, but only briefly. We will again be using JBuilder - (one of the issues with classes is knowing what methods are defined within a class. The codeInsight feature of JBuilder is very useful in this respect, as is its Help system). The notes in this document are very terse. As ever, the people at Sun and the Java Developer Connection have provided lot’s of tutorials to expand them. Here are some lecture slides I use on another course to explain the basics of Classes and objects in Java. You may also find them useful. Classes As we have seen already, these are defined very simply using the syntax: class Classname { /* insert body of class; internal data, private methods & public methods */ } Example: BankAccount, Account Access Control to the elements of a class is determined through the use of the access specifier keywords such as public, private or protected. Public Classes & Inner Classes The keyword class can itself be preceded by the word public to indicate that its methods are accessible by external objects. Typically, within a finally developed application consisting of many classes, there will be one public class which contains the main method launching the application. However, as will be pointed out in the lectures, during the development process, it may be useful for each class to have its own main to support testing and debugging The default is that any class is public. A class can itself be defined using inner classes (classes defined within another class). Used for example in JBuilders handling of ActionListeners in GUI development (Anonymous Adapters) Constructors As we have said, classes can be thought of as datatypes and objects are declared as An example of instances of that type. As with other datatypes it is useful to initialise an object polymorphism when it is created. This is achieved using a special type of method referred to as a constructor. Such methods are defined by having the same name as that of the class, however there can be many different versions of the constructor according to the quantity & type of parameters. There is a default constructor which is automatically defined, but it only "sets up" the object without setting any initial values. An example of both uses of constructors is seen in the BankAccount3 class: BankAccount3 ba3 = new BankAccount3(); Account sam = ba3.new Account("Sam Taylor", "Some place", "123456", 0.0); Importing Classes For simple (small) applications, all class definitions can be kept within the same file (eg. Account & BankAccount). However, the convention is to keep them in separate files, but in the same directory. By default, all files containing class definitions which Essentially, a package is a are in the same directory are "compiled" if javac is applied to the main class. “protected” folder eg. for the BankAccount & Account classes, javac BankAccount.java will (directory). See for access both classes. example the folders created by JBuilder when An additional level of structuring of applications is provided by the you create a project. notion of a package which allows files containing Java classes to be grouped together. To access classes in other packages, they must be imported: import packageName.ClassName; (import packageName.*;//imports all classes within package.) To place a class in a package, its definition must be prefaced by the keyword package followed by the name of the package. Once a class is in a package, it automatically has access to all other classes in that package. However, javac must be told where to find this package using the classpath option. Methods As we have already discussed in Workshop 1, methods are defined & implemented within a class (and so belong to it). Methods are very similar to functions in C++ and have very similar definitions. The 2 key differences are that: 1. methods are classified as public or private (or protected) 2. the only way a value can be passed back is using the return statement. Technically, all Java methods are pass_by_value (tho' we have to be careful about what value!) The precise syntax.... accessSpecifier returnType methodName(paramType paramName,......) { //Body of statements implementing method } eg. public void displayDetails() { System.out.println("Name : "+ name); System.out.println("Address : "+ address); System.out.println("Account Number : "+ accountNumber); System.out.println("Balance : "+ balance); } Objects Objects are created by declaring them as instances of a class. Java will allow you to declare without initialising, but it is always safest to use the new keyword. This is followed by the constructor of the class involved. Having created an object, methods can then be invoked. This is achieved by using the infamous "dot" notation eg. sam.displayDetails(); invokes the displayDetails() method of the sam object. sam.displayDetails(); if (sam.inCredit()) System.out.println("in Credit"); else System.out.println("overdrawn"); sam.setName("Samuel Taylor"); Exercises. 1. Look at the code for some simple case studies. First identify which classes have main() methods, what other classes are used by that class and how methods are invoked. Try to compile and run this code. Note the use of inner classes and separate classes. What are the differences between the various TaxClassXX files? Note: a useful feature of JBuilder - find an object and a method invocation by that object (clue sam.incredit()). Delete the method and the "dot" and then put the "dot" back in. You should then see a listing of all the methods associated with that object..... 2. In Convert.java, convert the remaining code into methods (eg. getInches( ), convert(feet, inches). What happens if you change the access modifier on the c_in( ) method to be public (ie. you lose the private static keywords)? How can you fix this? What happens if you put the c_in( ) & c_out() methods in a separate class? 3. This code is a simple simulation of a printer Queue. In it: A user creates a printJob and sends it to the Printer. there the Job is stored until it is its turn to be printed. To simulate the activity of the printer simple, text-based i/o is used. Various versions of the application are developed, starting from a fairly "procedural" approach (SimpleSim) to an OO version (Simulator_v4). Look at each of Sim* classes and identify which OO features are used where (eg. which classes, which objects, which messages, how...) Modify Simulator_v4 so that the "Delete a Print Job" option works. 4. Here is one version of a O's & X's game. Modify it so it will work with the Console class. Define & implement a Board class which encapsulates all the behaviour/responsibilities of the board. Inheritance in Java The following discussion is also based on a very trivial simulation of a PrinterQ system. I suggest you first run the system under JBuilder (create a new project and add all of the files to it then "Run"). You will be repeatedly prompted for the name of the owner of a job (just enter a simple string) until you enter the string "enuf" (without the inverted commas). The system will then output the details of the jobs entered. Things you should note: 1) The Sim.java file contains the main method. You should study this and notice all the method invocations (ie by which class are they ultimately serviced). There is one bit of naughtiness. The Integer.toString(Job.count) is accessing a (static) class level variable which should really be private. Exercise: Fix this! Declare count to be private and define a public method getCount( ) which will return that value. 2) use of Inheritance and the Vector & Object classes in Java PrinterQ is a specialisation of the more general Queue class. Notice the use of the keyword extends in the definition of the PrinterQ class to indicate this. Queue itself is based on Vector class defined in the java.util package. Vectors are basically dynamic arrays ie. if they fill up, you can specify that they should grow. How this is specified is thro' the use of the Vector constructor. Queue also uses the superclass Object in its definition. The simplest way to think of this is that all objects (int, double, string, user defined classes etc) in Java is a subclass of Object. By defining operations at the Object level, we're working at a very high level of abstraction and so we can use this class to define eg. Queues of Jobs, Appointments, Messages etc.... This generallity is achieved by using the method calls of the objects themselves eg. in the displayQ method there is a call to the toString( ) method. This is a method associated with every instance of Object (and hence every object) in Java. In fact, in Job we override the default implementation (ie. define our own version). Job is a very simple class having a few fields (you can add more if you want!) and methods. Note the use of the class level variable count to give the jobs an identity number and to keep track of the number of objects generated. Exercise Define two subclasses of Job - BWJob & ColourJob. Jobs on a BWPQ should be of type "B&W" Jobs on a ColourPQ should be of type "Colour" The type of the job should be entered in from the keyboard after the name of the owner and appropriate items added to the printerQ. Modify your system so that a) a B&W job has a "this is a B&W job" message printed before its other details. b) a Colour job has a "this is a colour job" message printed before its other details. Further, define a printJob( ) method which will print the first job on a printerQ (ie displays the details of the job and then deletes that job from the queue). You should also put up a small text based menu allowing you to select the option of adding or printing an item. Next refine the printJob( ) method so that B&W jobs are printed before colour ones. Self study: We have covered the main concepts of Classes, Objects & Methods in this session, however there are a couple of implementation subtleties that you should be aware of. These are covered in the for example chapters (3 & 7 of Horstmann's book "Computing Concepts with Java2"). You should ensure that you understand the concepts of: the implicit parameter this. Objects as reference. Copying Objects. the nullkeyword. Check out the OO material in the Java Tutorial from Sun or look at the tutorials at the Java Developer Connection.