Page 363 - Computer_Science_F5
P. 363
Computer Science 1. Write a Java class ‘Car’ with Implementation of key OOP features
Exercise 5.3
in Java
The implementation of key OOP features in
a constructor that initialises
Java, including inheritance, encapsulation,
the ‘brand’ and ‘model’
polymorphism, and abstraction, enables
FOR ONLINE READING ONLY
attributes. Demonstrate its
usage in a ‘Main’ class. developers to create modular and reusable
code. These principles help build robust,
2. Create a class ‘Book’ with scalable, and maintainable applications.
attributes ‘title’, ‘author’,
and ‘price’. Implement a Inheritance in Java
parameterised constructor Java allows to borrow (inherit) features
that initialises these attributes. from one class to create a new class. Using
Write a ‘Main’ class to create inheritance, you can create a general class
and display details of multiple
‘Book’ objects. that defines traits common to a set of related
items. This class can then be inherited by
3. Define a class ‘Employee’ other, more specific classes, each adding
with attributes ‘name’ and those things that are unique to it. This
‘salary’. Include a default
constructor that initialises inheritance concept has two key players:
name to “Unknown” and (a) The “Child” class (Subclass): This class
‘salary’ to 0. Demonstrate inherits properties and methods from
creating an ‘Employee’ object another class.
using this default constructor (b) The “Parent” class (Superclass): This
in a ‘Main’ class. is the class whose features are being
4. Discuss the concept of inherited. The child class inherits all of
destructors in Java. Explain the variables and methods defined by
why Java does not have a the superclass and adds its own, unique
‘finalize’ method like C++ elements.
and how garbage collection
handles resource cleanup. (a) Declaration in inheritance
5. Create a class To declare a superclass, the class keyword
‘DatabaseConnection’ followed by the class name is used. Then
that simulates opening a the superclass with its fields and methods
database connection in its is declared. To declare a subclass, the class
constructor and closing it in a keywords followed by the subclass name,
method ‘closeConnection()’. then, the extends keyword followed by the
Illustrate the importance of superclass name is used as shown in Figure
proper resource management 5.22. In order to inherit the features, that is,
using constructors and the new class to inherit from the existing
methods in Java. class, the “extends” keyword is used.
354
for Advanced Secondary Schools
Computer Science Form 5.indd 354 23/07/2024 12:34

