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

CAP477 · Unit 2: Object-oriented programming

Inheritance and super

8 practice questions

Key points

  • extends gives single inheritance of classes
  • Constructors run top-down; super(...) must be first
  • Fields are hidden, not overridden
  • private members are not accessible in subclasses

Inheritance lets a subclass reuse and extend a superclass with extends; it models an is-a relationship. Java allows single inheritance of classes (extends A, B is a syntax error) but a class can implement many interfaces. Every class extends Object, directly or indirectly.

Constructors are not inherited, but every constructor starts by calling a superclass constructor. If you do not write super(...), the compiler inserts super(); if the parent has no no-arg constructor, you must call super(args) explicitly as the first statement, or compilation fails. Object construction therefore runs top-down: for C extends B extends A, new C() prints A, B, C.

super keyword: super(...) calls the parent constructor; super.method() calls the parent's version. Example: a child show() calling super.show() prints Pa.show then Ch.show.

What is inherited: public and protected members (and package members within the package). private members exist in the object but are not accessible by name in the subclass.

Fields are not overridden, they are hidden. For Pa p = new Ch(); where both declare name, p.name is "parent" (reference type decides) while ((Ch) p).name is "child".

instanceof tests the type: a Ch object is instanceof Pa and instanceof Object.

Exam pitfall: the subclass constructor never runs before the superclass one.

Try two questions

Question 1 · Tier 3, Apply

Pa and Ch both declare String name ("parent" and "child"). With Pa p = new Ch(); what does p.name give?

  1. child
  2. null
  3. Compile error
  4. parent
Show the answer

D. Field access uses the reference type: parent child.

Question 2 · Tier 3, Apply

Pa has only Pa(int x). Ch extends Pa has a constructor Ch() { }. What happens?

  1. A runtime exception only
  2. It compiles; Pa(int) gets null
  3. Compile error: no matching Pa() constructor
  4. It compiles; Pa(int) gets 0
Show the answer

C. The implicit super() finds no no-arg constructor in Pa.