OOP writing exam 试题答案整理

本文最后更新于:2024年10月25日 下午

What is the biggest difference between object-oriented programming and procedural programming? Compare how data is accessed by functions in procedural programs and by methods in object-oriented programs. What effect does this have on the number of parameters required for methods? (2022 Resit a) (2021 Resit Q1 3)

  • Lecture 01

    The biggest difference is that we structure our programming using classes and objects instead of function.

    Procedural Programming use global data to functions and data is often passed between functions as parameters. OOP store data together methods, methods are used to operate data, data is accessed by a object.

    OOP methods don’t need require as many parameters because they can have access to data in object’s internal state.


What format is Java code compiled into? Explain the purpose of the Java Virtual Machine (JVM) in executing Java code. How does this make Java programs portable between different architectures and operation systems? (2020 Final Q1 h)

  • Lecture 01 P8

    Java bytecode.

    JVM can interpret and execute the bytecode.

    It will work an any system with a JVM installed.


Is Java a compiled or interpreted programming language? How does this process work? What are the benefits of this approach? (2021 Resit Q2 b) (2021 Final Q1 b)

  • Lecture 01 P8

    Java is both compiled and interpreted.

    The text we write is compiled into bytecode. An interpreter called JVM can execute the bytecode.

    It makes Java almost as fast as compiled languages.


Does Java use static or dynamic typing? Does Python use static or dynamic typing? What is the difference between the two? What are the benefits of static typing? (2021 Resit Q1 a) (2021 Final Q1 a)

  • Lecture 02

    Java is static, Python is dynamic.

    In Static language, the type of variables are know before compile. We can’t change the type of variable we are using. In dynamic language, the type of variables are determined at runtime.

    Find our mistakes more easily.


Explain the difference between an expression and a statement. Name and explain the use of one of the statements in Java you have learned, give an example showing the statement being used. Can a piece of code be both a statement and an expression? Give an example. (2022 Resit b) (2021 Resit Q1 e)

  • Lecture 02 P42

    A statement is a piece of code that does something. An expression is a piece of code that can be calculated
    to give us a result. int number; It be used to declare a int named number. Yes. int number = 5;


What are the main differences between arrays in Java and Lists in Python? How can we find the size of an array in Java (Include an example of finding the size)? Give an example of declaring and constructing an array to remember 10 int values. (2021 Resit Q1 d) (2021 Final Q1 d)

  • Lecture 02 P56

    Arrays in Java have a fixed size and all values in a array must be the same type. Lists in Python have a flexible size and cloud have different type of values.

    Using arrayName.length

    1
    2
    int numbers = new int[10];
    int length = number.length;

Java has many rules about what names we can use for classes, methods and variables (known as identifiers). In addition to this programmers should also follow a number of conventions for identifiers. For each of the following, list the conventions (not the rules) that you should follow: (2021 Final Q1 c) (2020 Final Q1 e) (2020 Resit Q1 d)

(i) All identifiers (ii) Class identifiers (iii) Variable identifiers (iv) Constant identifiers

  • Lecture 02 P29

​ All identifiers: can contain letters,digits and underscore. cannot start with a digit, cannot contain spaces, they are case sensitive.

​ Class identifiers: start with an uppercase letter, more than one word use camel case.

​ Variable identifiers: start with a lowercase letter, more than one word use camel case.

​ Constant identifiers: use all uppercase letter, separate words with underscores (‘__’)


Given the variables listed below, calculate the type of data that would be returned as the result of each of the following expressions? Explain each of your answers. • An int named i (2020 Final Q1 a) (2020 Resit Q1 a)

• A long named l

• A short named s

• A String named t

• A float named f

• A double named d

(i) i + d (ii) l - i * s (iii) i / s (iv) l + i + t (v) s < i

  • Lecture 02 P11

    i. i + d

    • result is a double
    • Explanation: The int would be implicitly promoted a double for the addition operation.

    ii. l -i *s

    • result is a long
    • Explanation: i * s is a short, and l - short is a long

    iii. i/s

    • result is a short
    • implicitly promoted

    iv: l + i + t

    • result: String
    • it is String operators. Numbers will automatically be converted to string

    v. s < i

    • result: boolean
    • Belongs to the comparison operator

What is the implicit parameter? Given the following example of comparing two date objects (birthday and today), which is the implicit parameter? (2022 Resit c) (2021 Resit Q2 d) (2020 Final Q1 c) (2020 Resit Q1 c)

1
today.sameDate(birthday);

Rewrite the following method to show the implicit parameter in the code using the keyword this:

1
2
3
4
5
6
public void summate (int a ) {
count = count + a;
if ( count > 28) {
return sum () ;
}
}
  • Lecture 03 P39

    The object we use to call method is know as implicit parameter. In example, today is implicit parameter.

    1
    2
    3
    4
    5
    6
    public void summate (int a ) {
    this.count = this.count + a;
    if ( this.count > 28) {
    return this.sum () ;
    }
    }

Explain the difference between the two examples below. What is the output in each example? (2021 Final Q1 e)

1
2
3
4
int x = 120;
int y = x;
y++;
System.out.println(x + " " + y);
1
2
3
4
Date today = new Date(1, 3, 2019);
Date tomorrow = today;
tomorrow.incrementDay();
System.out.println(today.getDay() + " " + tomorrow.getDay());
  • Lecture 3 P47

    First one is primitive variables, they are stored directly in memory. The value of 120 is stored in the variable x. The value of x is then copied into y. When y is incremented, only the value of y changes. So output is 120 121

    Second one is object variables. When tomorrow is assigned the value of today both references point to the sameDate object. So when tomorrow is incrementDay, the today also is changed. Output is 2 2


Explain in your own words the OOP concept cohesion. Describe high and low cohesion. Which is considered good? Why? (2022 Resit d) (2020 Resit Q1 h)

  • Lecture 04 P34

    Cohesion in programming is about how much the elements of a component belong together. It measures the strength of relationship between method in class. High cohesion is better. High cohesion is related to robustness, reliability, reusability, easy to understand AND maintain. But low cohesion is not.


Explain the difference between the following pieces of code (Assuming s is a String variable). Will they always return the same result? Why? (2022 Resit e) (2020 Final Q1 b)

1
s == " Hello ";       s.equals ("Hello");
  • Lecture 05 P40

    == compare the memory address of two string. equals is a method of String be used to compare 2 string whether same.

​ No. == not always worked, when dynamically create String.


Explain the concept of a ‘black box’ in programming. How does encapsulation allow us to achieve this concept in Java? (2020 Final Q1 d )

  • Lecture 06 P18

    Black box is a system which can know what it can do but not need to know how it work. Such as A car, we know how to drive it, but don’t know why.

    Encapsulation is achieved through the use of access modifiers to restrict access to class member, such as public private.


What effect does the keyword final have on a variable? Explain the difference between a final primitive variable and a final object variable. (2022 Resit Q2 a) (2021 Resit Q2 b)

  • Lecture 06 P38

    Final variables can be assigned only once, it would never change. Final primitive variable and final object variable couldn’t be changed after initialization. But final object variable could be modified. Such as A final ArrayList could add element.


What is encapsulation? Why is it useful in Object-Oriented Programming? How do we implement encapsulation in Java? (2021 Resit Q2 a) (2021 Final Q2 a) (2020 Resit Q1 j)

  • Lecture 06 P17

    Encapsulation is the combination 2 ideas: 1. Grouping together of instance variable and methods into classes. 2. Ability to restrict access to some of the objects components.

    It provides a way to protect internal of object. Easy to maintain and test.

    Encapsulation is achieved through the use of access modifiers to restrict access to class member, such as public private. If other class need to access variables always call getter and setter.


What is the function of the keyword final in Java? What effect does it have on a variable? What effect does it have on a method? What effect does it have on a class? (2020 Resit Q1 b)

  • Lecture 06 P38 & Lecture 08 P63

    Final is used in declaration variable, method or class is “final” and cannot be changed.

    Final variables can be assigned only once, it would never change.

    Final class is one that cannot be extended.

    Final method cannot be overridden by subclasses. It means when class is extended, the final methods cannot be overridden.


What is the function of the keyword static in Java? What effect does it have on a variable? What effect does it have on a method? Give an example of using the static method hello in the class Mess. The signature of the method is hello(int n, String s) (2021 Fina Q2 b)

  • Lecture 06 P32

    static in Java is used in declaration class variable and class method.

    Class variable share a single value over all object, only created in memory once.

    Class method not connected to objects, cannot use instance variables. It allows other to use this method without create object.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    public class Mess {
    pubilc static void main(String[] args) {
    Mess.hello(2,"you");
    }

    public static void hello(int n, String s) {
    System.out.println(n + s);
    }
    }

Describe how Interfaces can be used to enable code reuse in Java. Describe in detail how an interface would be defined and implemented to make reusable code. (2022 Resit Q2 b) (2021 Resit Q2 c) (2021 Final Q2 c) (2020 Final Q1 f)

  • Lecture 07 P16

    Interface is a list of action an object can do. Its methods focus on behave like an “X”. An interface specifier what an object can do not how.

    Defined an interface and implemented.

    1
    2
    3
    4
    5
    6
    7
    public interface InterfaceName {
    pubilc void requiredMethod
    }

    Public class className implements InterfaceName {

    }

Explain the idea of polymorphism in your own words. You should illustrate using an example with some code showing its use. (2021 Final Q2 e)

  • Polymorphism means that we can store object in different type, and when executing methods each object may execute different versions of the same method according to their type.

    1
    2
    3
    4
    5
    6
    7
    public int add(int a, int b) {
    return a + b;
    }

    public String add(String a, String B) {
    return a + b
    }

What is an immutable object? What changes must we make to a class to make its objects immutable? (2021 Final Q2 d)

  • Lecture 08 P69

    An object is considered immutable if its state cannot change after it is constructed.

    All instance variables and class variables are declared as final and private. Setter methods are not provided. Subclasses are not allowed to override, usually this is done by declaring the class as final. Instance variables that refer to objects cannot be changed.


Explain the phrase “prefer composition over inheritance” in your own words. How is this achieved in a Java class? Give one benefit and one drawback of choosing to create a class using composition instead of inheritance. (2022 Resit Q2 c) (2021 Resit Q2 e)

  • Lecture 08 P77

    It means whenever possible you should define classes using composition instead of inheritance. It is a general rule of good design.

    Composition can be achieved by creating objects of other classes within a class and using them to provided desired function.

    Benefit: More code reuse.

    Drawback: Implementing many forwarding methods. We need to add many forwarding methods, getter and setter.


Given the following two examples of nested classes (a and b). Explain the difference between the two examples. Write the code required to create an object based on the nested class for each example.(2021 Final Q3 b)

image-20231219152840199

  • Lecture 09 P25

    Static nested class is not connect to an instance of the outer class and so it cannot access the instance variables of the outer class. They can be constructed without an instance of the outer class.

    1
    2
    3
    4
    5
    6
    // a
    C.object = new C();
    C.D nestedObject = object.new D();

    // b
    E.F nestedObject = new E.F();

What is a lambda function? When can we use a lambda function in Java? Define a lambda function to implement the Calculator interface defined below. The lambda function should calculate the product of these numbers multiplied by 2 (i.e a ∗ b ∗ 2). What parts of the syntax of a lambda function are optional? (2022 Resit Q2 d) (2021 Resit Q3 a) (2021 Final Q3 a)

1
2
3
interface Calculator {
int performCalculation (int a , int b ) ;
}
  • Lecture 09 P28

    Lambda is a simple way to represent anonymous inner classes. They could be used when interface require a single method.

    Calculator lam = (a,b) -> {a * b *2}

    Variable type, round brackets when only a single parameter, curly braces when only a single statement are optional.


Explain the concept of inversion of control. What is required in our code to make this work? Why is this necessary when we are programming a graphical user interface? (2022 Resit Q2 e) (2020 Final Q1 g)

  • Lecture 10 P9

    It give control to framework, the framework will decide the code will be executed.

    We must implement specific methods, typically in classes that have extended a class in the framework.

    That’s because we can not know when our code should be executed.


What is a callback method? List the steps we must complete to cause a message to be printed on the screen whenever the user clicks the mouse.(2021 Resit Q3 b)

  • Lecture 10 P46

    A callback method is a method that we implement knowing that it will be called whenever a particular event happens.

    1. Implement the MouseListen interface.
    2. Define the code to print on screen and the listener to call when the mouse is clicked.
    3. Draw the window again by calling the repaint method.

What is a Stack Trace? Explain the order that a stack trace is printed in and why. (2022 Resit Q3 a) (2021 Resit Q3 e) (2020 Final Q1 i)

  • Lecture 11 P14

    When an exception happens, a stack trace tells us what frames were on the stack at exact moment that the exception happened.

    The order of stack trace is stack frames are removed, due to the principle of stack LIFO.


What is the difference between the information in a text file and a data file? Give an example of both storing the integer value 123. What would happen if I try to use readLine from a BufferedReader to read information from a data file containing integer values? (2022 Resit Q3 b) (2020 Resit Q1 i)

  • Lecture 12 P11

    Text file are used only to store text information, this data is represented using ASCll codes. Easy to understand. Data file contain only data in binary. Difficult to understand.
    Text: 123

    Data: 1111011

    readLine can result in loss of procession or unexpected characters.


Describe the difference between traditional testing and unit testing. How do we know when we have enough code coverage in our testing? (2022 Resit Q3 c) (2021 Resit Q3 c) (2021 Final Q3 c) (2020 Resit Q1 f)

  • **Lecture 13 P5 **

    Traditional testing means running the program and seeing the result. Unit testing is testing each component of the system individually.

    Code coverage is measured by tools and expressed as a percentage of the total code.


What is code coverage? With respect to code coverage, explain each of the following coverage criteria: (2020 Final Q1 j)

• Function coverage

• Statement coverage

• Branch coverage

• Condition coverage

  • Lecture 13 P49

    Code coverage is a measurement of the code that has been tested.

    • Function coverage: Has each function in the application been called by test?
    • Statement coverage: Has each statement in the application been called by test?
    • Branch coverage: Has each branch of each control structure been executed by the test?
    • Condition coverage: Has each Boolean sub-expression evaluated both to true and false?

What is the purpose of code documentation (e.g. Javadoc)? Write a suitable javadoc comment for the following method. Parameters, return types and exceptions should be specified correctly (you can list yourself as the author). (2022 Resit Q3 d)

1
2
3
4
5
6
7
8
9
10
11
12
13
public int converToInteger(String s) {
if(s == null || s.length() == 0) {
throw new IllegalArgumentException("Input is not valid!");
}
int result = 0;
for(int i =0; i < s.length(); i++) {
if(s.charAt(i) < '0' || s.charAt(i) > '9') {
throw new NumberFormatException("Input is not a number!");
}
result = result * 10 + (s.charAt(i) - '0');
}
return result;
}
  • Lecture 14 P5

    Code Documentation is for explaining what code does, it is useful for others to use our code without having to read the code.

    1
    2
    3
    4
    5
    6
    7
    /**
    * Convert a string to an integer.
    * @param s The String to be converted to an integer.
    * @return The integer value represented by the string.
    * @throws IllegalArgumentException If the input string is null or empty.
    * @throws NumberFormatException If the input string is not a valid number string.
    * @author Le Liu

Explain how generics improves type checking in the compiler. Give an example of a situation where an error would not be detected without generics. (2022 Resit Q3 e) (2021 Final Q3 d)

  • **Lecture 15 **

    Generic allows for writing code that can work with variety of data type while proving strong type checking at compile time. If a parameter is not correct, the compiler will show an error.

    Given a stack only for storing int. If we push a element not be int, error will show until we pop() it. We can’t find error when push it.


When does Java know what type a generic object will be using? Give an example of the code required to construct an object based on the generic class named GC. The object should use integer values for the parameters type. The class has a constructor that takes no parameters. (2021 Final Q3 e) (2020 Resit Q1 g)

  • Lecture 15

    During compile-time.

    1
    2
    GC<Integer> g = new GC<>();
    g.setvalue(5);