Task 1. Review Exercise

  • What is encapsulation? Why is it a useful feature?
  • What is the public interface of a class? How does it differ from the implementation class ?
  • What is an instance method, and how does it differ from a static method?
  • What is a constructor? How many constructors can a class have? Can you have a class without constructor? If a class has more than one constructor, which of them gets called?
  • What is the difference between the number zero, the null reference, the value false, and the empty String?
  • What happens if you try to open a file for reading that doesn’t exist? What happens if you try to open a file for writing that doesn’t exist?
  • If a program is started with the command: > java MyProgram - i input.txt - o output.txt
  • How many strings are stored in the array of the main method (String[] args)? What are the values of args[0] and args[1]?
  • What is the difference between throwing an exception and catching an exception?
  • What is a checked exception? What is an unchecked exception? Give an example for each. Which exceptions do you need to declare with the throws reserved word?
  • What is the purpose of the finally clause? Give an example of how it can be used.
  • Identify the superclass and subclass in each of the following pairs of classes
    • Employee, Manager
    • GraduateStudent, Student
    • Person, Student
    • Employee, Professor
    • Vehicle, Car
  • Suppose the class Sub extends the class Sandwich. Which of the following assignments are legal?
Sandwich x = new Sandwich();
Sub y = new Sub();
a. x = y;
b. y = x;
c. y = new Sandwich();
d. x = new Sub();
  • Draw an inheritance diagram that shows the inheritance relationship between the classes: Person, Instructor, Employee, Classroom, Student, Object
  • How does a class cast such as (ChoiceQuestion)q differ from a cast of number values such as (int)x?
  • Suppose C is a class that implements the interfaces I and J, and suppose i is declared as: i = new C();
  • Which of the following statements will throw an exception? a. C c = (C) i; b. J j = (J) i; c. i = (I) null;

Task 2. Programming Exercise

2.1. Use the code shown on slide 8 of the lecture notes on Inheritance Part One to write the Question class. The Question class implements these four methods: setText(String questionText), setAnswer(String correctResponse), checkAnswer(String response), and display() to display the question.

Use the code shown on slide 19 to write the ChoiceQuestion class which is a subclass of Question class.The ChoiceQuestion class adds a new instance variable ArrayList< String > choices, adds a new method addChoice(String choice, boolean correct), and overrides the method display().

Finally, use the code shown on slide 20 to write the QuestionDemo class which contains the main method and tests the Question and ChoiceQuestion classes. The main method creates an object of Question class and an object of ChoiceQuestion class. It also calls the presentQuestion(Question q) method to show question text, to extract user response from console, and to check whether the response is correct.

Note, although this task is effectively duplicating the code from slides, please take time to understand the inheritance and polymorphism. Some following tasks are extending this one.

2.2. Add a class NumericQuestion to the question hierarchy of slide 6 (Inheritance part one). If the response and the expected answer differ by no more than 0.01, then accept the response as correct. Modify the QuestionDemo class to test the NumericQuestion. An example is given below:

> What is the value of square root of 2?
> Your answer:
> 1.41
> true

Programming tip: similar to the ChoiceQuestion, NumericQuestion is a subclass of Question. Hence, you only need to implement the difference between NumericQuestion and Question. Specifically, you need to add a new instance variable (double type) to store the correct answer, and override the checkAnswer(String response) method to compare numerical values.

2.3. Modify the checkAnswer method of the Question class so that it does not take into account upper/lowercase characters. For example, the response to JAMES gosling should match an answer of James Gosling . Use the QuestionDemo to test this new Question class.

2.4. Provide toString methods for the Question, ChoiceQuestion, and NumericQuestion. Modify the QuestionDemo class to test the toString methods of those three classes. Refer to the lecture notes (Inheritance part two) for example output of toString method.

2.5. Write a program that reads data from the following webpage http://csvision.swan.ac.uk

and calculate the total occurrence of this word, Vision or vision , as a single word. Each time a match is found, the program prints out the found word, Vision or vision . The main method can be in the same class. Your program is expected to read the URL address from the command line, e.g.

> java KeywordSearch http://csvision.swan.ac.uk
> Vision
> Vision

> vision

> Number of occurrence: YOUR_RESULT_NUMBER

YOUR_RESULT_NUMBER is an integer number indicates the number of times your program successfully identifies the match of the keyword.

Hints: You may find the code for the second task of Lab Work 2 useful in that it also reads a URL address from the command line, opens a webpage to read, and handles the MalformedURLException. As for searching the keyword, you can take one of the following two different approaches.

  • One is to use the default whitespace of the scanner to carry out word by word extraction using the combination of hasNext() and Next() methods in a while loop. Each time you have a word available, you may compare it to Vision and vision so that you catch both variations using the equals() methods of the String class.
  • The other approach is to use delimiter to search the keyword. The idea is first to set the delimiter pattern to match the keyword (beware of the variations, i.e. Vision and vision ), move the scanner position by calling the next() method, and then change the delimiter pattern to default again (useDelimiter( \s+ )) so that by calling the next() method again the returned String is the keyword. You then alternate the two delimiters until reach end of the webpage. Task 2 of lab work 2 is an example of alternating two delimiters. Have a look at the lecture slides on delimiter to understand how to cope with uppercase and lowercase (you may need the square brackets, [ ], in specifying delimiter pattern), and you may also need to include the default whitespace ( \s+ ) in your delimiter pattern in order to find Vision or vision as single words, rather than part of some other words, e.g. VisionAnd .

2.6 Write a program CopyFile that copies one file to another. The file names are specified on the command line. For example, > java CopyFile report.txt report.sav

2. 7 Implements a superclass Person. Make two classes, Student and Instructor, that inherit from Person. A person has a name and a year of birth. A student has a major, and an instructor has a salary. Write the class declarations, the constructors, and the methods toString for all classes. A test program is supplied below (available to download from Blackboard) that tests classes and methods.

/** This class tests the Person, Student, and instructor classes. */ public class PersonTester{ public static void main(String[] args){ Person p = new Person("Perry", 1959); Student s = new Student("Sylvia", 1979, "Computer Science"); Instructor e = new Instructor("Edgar", 1969, 65000); System.out.println(p); System.out.println("Expected: Person[name=Perry,birthYear=1959]"); System.out.println(s); System.out.println("Expected: Student[super=Person[name=Sylvia,birthYear=1979],major=Computer Science]"); System.out.println(e); System.out.println("Expected: Instructor[super=Person[name=Edgar,birthYear=1969],salary=65000.0]"); }}

Challenge Tasks

c.1. Add a class MultiChoiceQuestion to the question hierarchy shown on slide 6 (Inheritance part one) that allows multiple correct choices. The respondent should provide all correct choices, separated by spaces. Provide instructions in the question text.

c.2. Based on Task 2.1., add a method addText(String questionText) to the Question superclass and provide a different implementation of ChoiceQuestion that calls addText rather than storing an array list of choices.

c.3. Extend the Task 2.5 so that the program can search the keyword vision or Vision not only on the webpage as specified in Task 2.5 but also on the webpages that are immediately linked to that page. You need to print out the keyword, vision or Vision , in the console every time a match is found, and print out the total number of occurrences.

Academic Honesty!
It is not our intention to break the school's academic policy. Posted solutions are meant to be used as a reference and should not be submitted as is. We are not held liable for any misuse of the solutions. Please see the frequently asked questions page for further questions and inquiries.
Kindly complete the form. Please provide a valid email address and we will get back to you within 24 hours. Payment is through PayPal, Buy me a Coffee or Cryptocurrency. We are a nonprofit organization however we need funds to keep this organization operating and to be able to complete our research and development projects.