1. University MCA (AI/ML) Semester 2
  2. CAP477
  3. Unit 2

CAP477 · Unit 2: Object-oriented programming

Classes, objects and constructors

8 practice questions

Key points

  • Constructor: class name, no return type
  • Default constructor is lost when you write any constructor
  • this(...) chains constructors; must be first
  • Locals have no default values; fields do

A class is a blueprint with fields (state) and methods (behaviour); an object is an instance created with new. Variables of class type hold references, so Pt q = p; makes two names for one object, and == compares references while equals() (default from Object) also compares references unless overridden.

Constructors have the class name and no return type. They run when new is used. If you write no constructor, Java adds a default no-arg constructor; once you write any constructor, the default disappears, so new Q() fails to compile when only Q(int x) exists.

  • Overloading: several constructors with different parameter lists.
  • Chaining: this(...) calls another constructor of the same class and must be the first statement.
  • Instance fields get default values (0, 0.0, false, null); local variables do not and must be assigned before use (compile error "might not have been initialized").

Initialisation order for new P(): static blocks (once, at class load) -> instance field initialisers and instance blocks -> constructor body. With P() { this(7); }, output of new P(); new P(5); is static, init, P(int) 7, P(), init, P(int) 5.

Parameter passing: Java is always pass-by-value; for objects the reference is copied, so a method can change the object's fields but cannot re-point the caller's variable. Reassigning a primitive parameter has no effect on the caller.

A static counter incremented in the constructor gives each object a unique id (ids 1, 2 and count 2 after two objects).

Exam pitfall: adding a parameterised constructor silently removes the default one.

Try two questions

Question 1 · Tier 3, Apply

Pt p = new Pt(1,2); Pt q = p; q.x = 9; System.out.println(p.x); prints:

  1. 9
  2. Compile error
  3. 0
  4. 1
Show the answer

A. p and q refer to the same object: 9.

Question 2 · Tier 3, Apply

Class P has a static block, an instance initializer block, a constructor P() that calls this(7) and then prints "P()", and P(int v) that prints "P(int) " + v. In what order do lines print for new P();?

  1. P(), P(int) 7, static, init
  2. static, P(int) 7, init, P()
  3. static, init, P(int) 7, P()
  4. init, static, P(), P(int) 7
Show the answer

C. Run on JDK 21: static, init, P(int) 7, P(). The static block runs once when the class loads; the instance block runs in the constructor that does not call this(...), before its body.