2

whan I write a class like this:

public class MyClass{
    public void print(){
    system.out.println("Hi")
   }
}

I can instantiate the class in the main even though It has no constructor written by me, is that because it inherits from Object anyway ?

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • it is because when no constructor is provided in the class a default no parameter constructor is added, see [JLS 8.8.9](https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.8.9) – SomeJavaGuy May 19 '16 at 07:02

1 Answers1

1

Constructors are not inherited. But if no constructor is explicitly declared, the java compiler implicitly adds a default constructor.

See the Java Language Specification:

8.8.9. Default Constructor

If a class contains no constructor declarations, then a default constructor is implicitly declared.

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123