* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download Answers - University of Wolverhampton
Join-pattern wikipedia , lookup
Resource management (computing) wikipedia , lookup
Abstraction (computer science) wikipedia , lookup
Monitor (synchronization) wikipedia , lookup
Scala (programming language) wikipedia , lookup
Exception handling wikipedia , lookup
Object-relational impedance mismatch wikipedia , lookup
Java syntax wikipedia , lookup
Go (programming language) wikipedia , lookup
Design Patterns wikipedia , lookup
Java (programming language) wikipedia , lookup
Java performance wikipedia , lookup
Name mangling wikipedia , lookup
Class (computer programming) wikipedia , lookup
Object-oriented programming wikipedia , lookup
CP2027 2/97 1-8 University of Wolverhampton School of Computing CP2027 Programming in Java- Solutions Examiners Mike Jackson Naomi Wrighton June 1998 2 hours Answer any 4 questions All questions are equally weighted In questions requiring the writing of code, minor errors in syntax will not be penalised CP2027 2/97 2-8 1. (a) Explain the terms: i) Single inheritance; ii) Multiple inheritance. Single Inheritance- A class (say B) is described by extending another class (say A). The IsA test should apply, one should be able to say that a B isA A, but that objects of class B have something extra or different to objects of class A. Given this, objects of class B can inherit all the methods and attributes of class A without having to define them again. (3) Multiple Inheritance A class has two (or more) parent classes, it inherits from both. (1) (4 marks) (b) Explain with an example how inheritance is implemented within Java. There is only single inheritance (1) The keyword is extends (1) (mark given if word just used in example) Methods may be overridden (i.e. redefined in the subclass), if they have exactly the same parameters and return types as in the parent (1 mark given if explained in code)) May use super() to refer to overridden method (1 mark) E.g. class myClass{ private: int varA; …. public: int methodA(int x) void methodQ(int x) …………… } mySubclass extends myClass { //add extra variables int varB; //add extra methods int MethodB(int x); //override old methodQ void methodQ(int x) } Objects of class mySubclass can now be sent messages using any of the methods of myClass (including methodA), and also methodB.(1) If they are sent methodQ the version in mySubclass will be used. (1) 4 for the example. (9 marks) (c) Describe a programming problem where you might make use of inheritance. (6 marks) Up to 6 marks for any reasonable example, they are likely to use the assessment or felines. For 3of the 6 marks need to describe the extra attributes and methods added in the subclass- the other 3 for a reasonable scenario. (d) Discuss the extent to which the concept of an interface in Java provides functionality similar to that provided by a language that provides a multiple inheritance mechanism. An interface gives a list of prototypes for methods that must be provided by any class that implements the interface (2) This can be used to mimic multiple inheritance as a class may inherit from another class and also implement one or more interfaces. (1) CP2027 2/97 3-8 One can think of implementing interfaces as overriding methods as in inheritance-but there is no notion of using things already defined in the interface being implemented(other than constants) , just supplying code to provide the functionality for methods with uniform names. So it gives the flexibility and regularity to aid the user inherent in polymorphism, without the re-use aspects of inheritance.(2) This is none-the-less very useful, particularly to implement functions needed in order interact with a GUI environment, where classes that wouldn’t satisfy the isA test, need to behave similarly in some respects.(1) (Other points : Using interfaces is arguably a better way of providing the same sort of functionality as can be provided by multiple inheritance. Interfaces can extend other interfaces – just adding no redefinition) (6 marks) Explain the following Java terms: (i) Event; An event is something that happens during the running of a program, that will alter the course of what happens next, e.g. a key is pressed, the mouse is clicked. (2)(Events need not emanate directly from the user and new events can be defined by the programmer) (ii) Listener; A listener is an object that listens for particular sorts of events(1). They must be instantiated from classes that implement listener interfaces(1) (iii) Adapter. A class that implements an interface must provide code for all the methods in the interface- this can be very onerous. Adapters provide dummy bodies that do nothing for all the methods in a particular interface. If a listener inherits from an adapter it need only provide code for the appropriate methods, leaving the default bodies for the others.(2) 2. (a) (6 marks) (b) In the context of Java 1.1 describe the operation of an event delegation model. Events are generated from event sources (visual components).(1)) When an event happens an object is created to describe it and the associated listeners are notified. (2)The actionPerformed method of the listener is passed the event object and does whatever is appropriate (i.e. it handles the event)(3) (6 marks) (c) Write code for an applet which would display two buttons labelled “Black” and “Blue”. Include code so that if the user presses a button the applet calls the setBackground() method to set the appropriate back ground colour. The HTML is not required. public class Exam extends Applet implements ActionListener{ public void init(){ Button blackButton = new Button(“Black”); add (blackButton); blackButton.addActionListener(this); Button blueButton = new Button(“Blue”); add (blueButton); blueButton.addActionListener(this); } public void actionPerformed(ActionEvent event) { String command = event.getActionCommand(); if (command.equals(“Black”)) setBackground(Color.black); if (command.equals(“Blue”)) setBackground(Color.blue); 1 1 1 1 1 1 2 2 2 1 CP2027 2/97 4-8 } (13 marks) 3. (a) Explain why support for concurrency is necessary for any programming language that is used to build a Graphical User Interface (GUI). Because the user will want more than one thing to happen (or appear to happen ) at the same time. For example there may be an animation which is running, without concurrency the user would have to wait for it to stop before doing anything else; with concurrency the animation can happen in parallel with a listener waiting for a mouse click or a key press which can be used to stop the animation. (5 marks) (b) Explain in general terms the concept of a monitor, and explain how a monitor is produced in Java. (6 marks A monitor is a set of data with a set of operations on it, where only one operation can access the data at a time. (2) A monitor is modelled in Java by a class (1) The modifier synchronized is added to the method definitions. When a thread invokes a synchronized method on a particular object it automatically obtains a lock for that object. Any other thread which tries to invoke the same or any other synchronised method for that object whilst the first thread holds the lock for the object must wait until the lock is released. The lock is only released when the first thread exits from the synchronised method. (2) Only one synchronised method can be executed at one time on a given object. (1) (c) Describe (with the aid of a diagram) the states a Java thread may enter and the transitions which may cause a thread to change its state. (14 marks) CP2027 2/97 5-8 State transitions New sleep finish sleeping suspend start Blocked resume wait Runnable notify I/O I/O complete Dead stop Diagram 8 (4 for the states, 4 for the transitions) Description 6 A thread in the New state becomes Runnable when its start() method is invoked. (1) From the Runnable state there are a number of events which will place the thread into the Blocked state. (1) A thread can become Runnable again if an appropriate event occurs when it is in the Blocked state. Threads only move from being Blocked to being Runnable when an event occurs that is related to the event that caused them to be Blocked. For example, if a thread is waiting for I/O, it can only become runnable when that I/O is complete. (2) Threads are only eligible for execution when they are Runnable. The JVM selects one thread from the set of Runnable threads to run. (1) A Runnable thread becomes Dead when its stop() method is invoked. (1) CP2027 2/97 6-8 4. (a) Explain the terms: a) Object; An object is an instance of a class- it represents a thing that exists at runtime in the program. (2) b) Class; A class is the definition of all the attributes and methods that objects of a particular class possess. (2) c) Object-oriented. A method of programming (or analysis or design) that views the problem as a set of objects from classes that communicate by sending messages. In an OO solution only objects would exist at run time and all communication (including control structures) would be implemented by message passing. (2) (6 marks) In “How to Program in Java” Deitel and Deitel claim that Java is 100% object-oriented. Discuss this claim with reference to the following Java types: a) variables of type int, float, double; The types are not classes and so variables of these types are not objects (so not pure OO). Wrapper classes exist which parallel these types, and are classes. (names are of course different – normally capitalised) (2) b) arrays; An array is like an Object- but it doesn’t belong to a named class, and so there can’t be any subclasses as there is nothing to extend. (But all methods of class Object may be invoked on an array.) They are instantiated using new, but with the type of the base object (which can be a class or a type), and the number of elements. So again not pure OO. (2) c) strings. Again these are like objects, of class String, but there are two differences: (i) they can be instantiated without using a constructor,- not OO (ii) There is an operator + (concatenate) defined for Strings (not true for any other class- except the wrappers referred to in a.)- this is quite consistent with OO. (2) (6 marks) (b) (c) One of the design goals of the Java development team was to produce a language that was object-oriented. Discuss the importance and advantages/disadvantages of this goal, and to what extent you think it has been met. Indicative points for the answer: Roughly Importance /Advamtages(7),Disadvantages(2), Met(4) The importance is largely to do with safety , managing complexity, and fitting in well with modern developments (e.g. GUIs and client server applications.) Advantages See importance. When used properly (i.e. respecting encapsulation), the programmer can rely on the integrity of the objects. The traditional design virtues of high cohesion and low coupling are automatically provided. Inheritance (and encapsulation) encourages reuse in a controlled manner. Polymorphism gives regular naming of methods- making it easier for the user. For managing complexity it encourages modularity and the ability to think at different levels of abstraction at different times. Possible disadvantages. If encapsulation is not respected then safety is compromised. The extra discipline imposed on the programmer may be found a burden by some- who will circumvent the principles. if possible (this is possible in Java as visibility is in the control of the programmer) For simple applications code tends to be long and complex- may be off putting. Met CP2027 2/97 7-8 From part(b) we know that the type system allows for things which are not objects instantiated from classes. The ability to break encapsulation goes against the pure OO paradigm, as does the fact that there are statements other than the sending of messages. Against this it is impossible to use Java without utilisiing OO to a very large extent. (13 marks) 5. (a) Explain what is meant by an exception in the context of Java programming. Give two examples of a situation that would give rise to an exception. Something that occurs at run-time that ought not to have done. These are events that can be foreseen and special code can be included to handle (or catch) the events. (3)E.g. a letter is input when a number is expected, an attempt to divide by zero.(2) (5 marks) (b) What is the relationship between an exception and an object of class Exception? When an exception occurs (from which a programmer may be expected to recover), an object of class Exception, (or of one of the subclasses of Exception) is created. (3 marks) (c) Describe the syntax that Java provides for handling exceptions. Include in your description an explanation of why all Java programmers need to know about exceptions and how multiple catch blocks should be ordered. Code that might raise an exception is placed within a try block i.e. try {……} (2) the try block is followed by one or more catch blocks, giving the code to executed if an exception is raised (2) The catch blocks have a sort of parameter of an Execution or a subclass of exception. These should be ordered from the most specific to the most general, as the first that matches is used, and any exception will match exception. (3) There is also a finally block which is executed regardless of whether an exception was raised or not. (2) All programmers need to know as input operations can throw an IOException and so any code with inputs must handle the exception (otherwise it won’t compile). (3) (12 marks) (d) Java provides a mechanism whereby a programmer can cause an exception to occur. Describe the mechanism anda scenario where this might be useful. The throw statement is used (1) The exception should be handled by the code that calls the method in the way indicated above (1) Example (3) (e.g. something untoward in a constructor, or even input value out of range.) (5 marks) CP2027 2/97 8-8 6. (a) Describe the differences between a Java applet and a Java application. (4 marks) An applet is a Java program that runs within a browser (1). Every applet inherits from class Applet.(1) An application is a free standing Java program.(1) It must contain a public method main() (1). (b) Write an outline of Java code that is both an applet and an application. (6 marks) Code must provide a class which contains code to create an instance of Frame (1) and adds the applet (1) to it. It must call init() and start(). (2) It is also necessary to implement the AppletStub and AppletContext interfaces. (2) (c) Describe the methods of class Applet which are normally overridden in order to produce an applet which performs a given task. (6 marks) init() is used to initialise variables used within the applet and is called when the applet is loaded. (2) start() is called after init() and whenever a user returns to the page containing the applet (2) stop() is called whenever a user moves off the page containing the applet. It is normally used to pause the processing. (2) (d) Describe the security measures implemented in browsers that prevent an applet from carrying out unwelcome operations on the machine on which the browser executes. (9 marks) The Java runtime system verifies all code it receives to ensure: it doesn’t forge pointers (1) it doesn’t violate access restrictions (1) it uses objects in the way they are supposed to be used (1) Applets actions restricted to its “sandbox” (1) Cannot read or write data outside the sandbox (1) May Disallow all network accesses; (1) Allow access to only the hosts from which the code was imported (1) Allow network accesses but only if they are outside the firewall (1) Allow all accesses (1)