Thursday 10 May 2018

Can a private constructor prevent sub-classing of class?

Inheritance is the concept of re usability. Object of one class can get the properties and methods of object of another class by using inheritance. One class can use the methods and properties of other class.

When you want to create a new class and there is already another class that has some of the functionality that you want, you can derive your new class from the existing class.


Class B derived from class A. I.e., B is the sub class and A is the super class.

   Class A{

   }

   class B extends A{

   }

Whenever sub class constructor is called, the super class default constructor called internally by default.

Can a private constructor prevent a class from sub-classing?
A private constructor does not prevent a class from sub-classing.

For example,

Application.java
package com.sample.app;

public class Application {
 private static class ParentClass {
  private ParentClass() {
   System.out.println("I am in parent class");
  }
 }

 private static class ChildClass extends ParentClass {
  public ChildClass() {
   System.out.println("I am in child class");
  }
 }

 public static void main(String[] args) {
  new ChildClass();
 }
}


Output
I am in parent class
I am in child class



No comments:

Post a Comment