Docsity

Exploring Object-Oriented Programming Concepts in Java, Summaries of Computer science

Toggle sidebar
bg1
3
COMPUTER SCIENCE TRIPOS Part IAโ€“ 2018 โ€“ Paper 1
Object-Oriented Programming (RKH)
Consider the following Java class.
1 public class Child extends Parent {
2
3 public int x=0;
4
5 public boolean equals(Object obj) {
6 if (this == obj) return true;
7 if (!super.equals(obj)) return false;
8 if (getClass() != obj.getClass())
9 return false;
10 Child other = (Child) obj;
11 if (x != other.x) return false;
12 return true;
13 }
14 }
(a) Explain why it is bad practice for member variables such as xto be public.
[2 marks]
(b) For each of the lines 6โ€“12, explain its purpose. Illustrate your answer with
examples. [7 marks]
(c) What could result from a call to c.equals(null), assuming cis a reference to
aChild object? [3 marks]
(d) What would be the consequences of replacing the equals signature with
public boolean equals(Child obj)? [4 marks]
(e) Explain why Child should also override the hashCode() method. [4 marks]
1

Partial preview of the text

Download Exploring Object-Oriented Programming Concepts in Java and more Summaries Computer science in PDF only on Docsity!

COMPUTER SCIENCE TRIPOS Part IA โ€“ 2018 โ€“ Paper 1

Object-Oriented Programming (RKH)

Consider the following Java class.

1 public class Child extends Parent { 2 3 public int x=0; 4 5 public boolean equals(Object obj) { 6 if (this == obj) return true; 7 if (!super.equals(obj)) return false; 8 if (getClass() != obj.getClass()) 9 return false; 10 Child other = (Child) obj; 11 if (x != other.x) return false; 12 return true; 13 } 14 }

(a) Explain why it is bad practice for member variables such as x to be public. [2 marks]

(b) For each of the lines 6โ€“12, explain its purpose. Illustrate your answer with examples. [7 marks]

(c) What could result from a call to c.equals(null), assuming c is a reference to a Child object? [3 marks]

(d ) What would be the consequences of replacing the equals signature with public boolean equals(Child obj)? [4 marks]

(e) Explain why Child should also override the hashCode() method. [4 marks]