Java inheritance
If I have an abstract class in java named Foo and it has a constructor named Bar then I want to know the following.
lets say it Foo
looks something like
public abstract class Foo {
Service serviceFoo
...
}
And Bar
there is
public class Bar extends Foo {
...
}
Also, suppose I have a Foo
named instance Foo
that currently has an serviceFoo
instance
If I then declare:
Foo foo = new Bar();
will create a new instance Bar
that has an instance serviceFoo
or not? For instance. will this field be inherited and instantiated, or just inherited?
a source to share
When you call new Bar();
, the constructor for Foo
is called implicit. If the constructor Foo
instantiates serviceFoo
then there will be Bar
. If it Foo
relies on someone else to instantiate it serviceFoo
, it Bar
will do the same.
Existing instances are either Foo
or are Bar
not relevant to what happens when a new instance is created. Only the code that is executed in the constructor (or passed as a parameter) affects the new object.
a source to share
No, inheritance does not occur between instances; only between class definitions.
When you instantiate new Bar()
, it serviceFoo
will be instantiated according to its declaration in Foo
. In the current case, it has no instance in Foo
, so it will be an empty reference in the new instance Bar
.
Also, you should be aware that all non-primitives in Java are reference types. That is, Foo
it is not Foo
, but a link to Foo
. When you assign new Bar()
Foo
, you completely reassign its reference to the new object.
Edit : one more, minor nitpick - if you already have an instance Foo
named Foo
as you claim then the line
Foo foo = new Bar();
will not compile as this is an override Foo
.
a source to share
When you speak Foo foo = new Bar()
, you are creating a completely new object. This means it Bar
is created from scratch and any instance variables are initialized as well. If it inherits from a superclass, for example Foo
, then those inherited variables are initialized as well.
There is no way to know a Bar()
parameterless constructor without <24> and somehow set it to that value.
If you want to do this, you need to pass the reference to serviceFoo
in the constructor.
Foo foo1 = new Bar();
foo1.serviceFoo = new Service();
// do something with that serviceFoo
Foo foo2 = new Bar(foo1.serviceFoo); // make sure you define this constructor
a source to share
Inheritance means that a child class extends or inherits the class as inheritance.
public class Parent {
public void dostuff() {
System.out.println("i am in parent");
}
}
public class Child extends Parent {
public void dostuff() {
System.out.println("i am in child");
}
}
public class Test {
public static void main(String[] args) {
Parent p = new Parent();
Parent p1 = new Child();
p.dostuff();
p1.dostuff();
}
}
a source to share