Page 380 - Computer_Science_F5
P. 380
From this program example, the 7. Design a Java class representing a
“get” method returns the value of the bank account with private attributes
variable name. The “set” method takes a for account number, balance, and
parameter “newName” and assigns it to customer name. Implement getter
the name variable. The keyword “this” and setter methods for accessing Chapter Five: Object oriented programming with Java
FOR ONLINE READING ONLY
is used to refer to the current object. In and modifying these attributes,
this case, the name variable is declared ensuring encapsulation principles
as private, it does not grant permission are followed.
to be accessed from outside this class.
Polymorphism in Java
Exercise 5.7 Polymorphism is a core principle in
object-oriented programming, enabling
1. Explain the concept of encapsulation objects to exhibit varying forms or
in Java and why it is important in behaviors depending on the situation. In
software development. Java, polymorphism is realized through
2. Compare and contrast the public, inheritance, method overriding, and
private, and protected access method overloading.
modifiers in Java, highlighting their
roles in encapsulation. Polymorphism allows for the treatment of
3. How does encapsulation contribute objects belonging to different classes as
to the security and integrity of if they are objects of a shared superclass.
Java code? Provide examples to This concept enhances flexibility and
illustrate your answer. extensibility in software design. For
4. Describe the steps involved in instance, imagine a superclass called
achieving encapsulation in a Java “Shape” with subclasses such as
class. Include the declaration of “Circle,” “Rectangle,” and “Triangle.”
attributes, access modifiers, and the While these subclasses inherit common
use of getter and setter methods. characteristics from the “Shape”
5. Discuss the advantages of using superclass, they also have their own
getter and setter methods to access unique implementations for calculating
private attributes in Java classes. area and perimeter.
Provide real-world scenarios where
encapsulation through getter and Inheritance as Polymorphism in Java
setter methods would be beneficial. Inheritance involves a class acquiring
6. Explain the potential risks of the attributes and actions of another
exposing class attributes as public class. Polymorphism, closely associated
fields without encapsulation. How with inheritance, permits subclasses
does encapsulation mitigate these to demonstrate distinct behaviors
risks? while still sharing core features with
371
Student’s Book Form Five
Computer Science Form 5.indd 371 23/07/2024 12:34

