• Post Reply Bookmark Topic Watch Topic
  • New Topic

Inheritance in Java  RSS feed

 
chamini prashakthi
Ranch Hand
Posts: 120
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When we use inheritance in java can we inherit constructor of the super class by the sub class?
In one of tutorial it says,
A subclass inherits all the members (fields, methods, and nested classes) from its
superclass.
Constructors are not members, so they are not inherited by subclasses, but
the constructor of the superclass can be invoked from the subclass.
But insome where the same tutorial said that,

If a class is inheriting the properties of another class, the subclass automatically acquires
the default constructor of the superclass.

So I want to know that does the sub class can inherit the constructor of the super class?
 
Henry Wong
author
Sheriff
Posts: 23188
124
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
chamini prashakthi wrote:
So I want to know that does the sub class can inherit the constructor of the super class?


Well, I don't know if it can be called inheritance. The constructor is responsible for it's portion of the initialization of the instance -- and it calls the constructor of the super class to initialize the superclass portion.

Additionally, if you don't define a constructor, then one is created, that simply calls the superclass' no-arg constructor.  Again, I don't know if this can be called inheritance.

Henry
 
Stephan van Hulst
Saloon Keeper
Posts: 7377
130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Inheritance means that you can access something on a class, without the class having to have declared it, because one of its supertypes already declared it.

Let's say I have a class A:

We extend A, and only declare a new constructor:

From another class in the same package as A and B, we can access the following of B:

We can not access private fields, methods and classes because they're both private to A, AND they're not inherited. We also cannot access the parameterless constructor on B, because B doesn't have any because it didn't inherit it from A. B can access A's parameterless constructor using the super keyword, but it doesn't actually inherit it.

So, to recap, a class inherits all members from its super-types, except private members. A class never inherits constructors.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!