Self-check questions
Write your answers first, then open the answers to check them.
- Explain the difference between a class and an object using your own example.
- What is the difference between an attribute and a method?
- What does the
newkeyword do? - List three rules for constructors.
- Why does Java not have destructors like C++? What is used instead?
- Is
int add(int a)anddouble add(int a)valid overloading? Why?
Show answers
A class is a blueprint; an object is one actual thing built from it. Example: the class
Phonedescribes a brand, a model and a battery level, and the methodscall()andcharge(). My phone and your phone are two objects of that class, each with its own values.An attribute stores data, the state of an object (for example
marks). A method is code that defines behaviour (for examplegetGrade()); it can read and change the attributes.newallocates memory for a new object on the heap, runs the constructor to initialise it, and returns a reference to the object, which is usually stored in a variable.Any three:
- The name is exactly the class name.
- It has no return type, not even
void. - It runs automatically when an object is created with
new. - It can take parameters and can be overloaded.
- If you write no constructor, Java supplies a default no-argument one; once you write any constructor, it does not.
Java frees memory automatically with the garbage collector, so programmers never destroy objects themselves, and the moment of collection cannot be predicted. Resources such as files and connections are released with a
close()method instead, usually called automatically by try-with-resources (AutoCloseable). The oldfinalize()method is deprecated.No. Overloaded methods must have different parameter lists. Both have
(int a); only the return type differs, so the compiler reports that the method is already defined.
Practice exercises
- Create a Rectangle class with width and height, a constructor, and methods
area()andperimeter(). Create three objects and print their results.Hint
Javaclass Rectangle { double width, height; Rectangle(double w, double h) { width = w; height = h; } Rectangle(double side) { this(side, side); } // square (exercise 3) double area() { return width * height; } double perimeter() { return 2 * (width + height); } } - Create a Car class with model, speed, and methods
accelerate(int amount)andbrake(int amount)so that speed never becomes negative. Test with a trace table.Hint
In
brake(int amount), subtract the amount, then setspeed = 0if the result is below zero (or useMath.max(0, speed - amount)). - Add an overloaded constructor to Rectangle that creates a square from one value.
- Write a class Printer with overloaded
print()methods for an int, a String and a double. - Create a Student copy constructor. Show with a test that changing the copy does not change the original.
- Write a lab report that lists three test cases for your Car class (normal, boundary, invalid) with expected and actual outputs.