This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Java Constructor Inheritance
When creating subclasses,
Why do I have to create a constructor and write super in every ctor?
If my behavior is similiar to the superclass shouldnt I expect to inherit them as well?
Constructors aren't inherited because you're not creating an instance of the superclass, you're creating an instance of a new class. There's no way to know which superclass constructor you want to call.
To be fair, the default (no arg constructor) always exists. It's the specific arg ctors that you're referring to, I'm assuming.
In reality, java always creates new constructors for your subclasses, but only for the default, no parameters constructor. If your class has constructors other than the default (no parameters) constructor, you have to define them again... Constructors are not meant to be behaviour methods but rather object initialization (which may change for subclasses with new attributes)
Default no argument Constructor is inherited and called by default. In case you like to call another one, you can use super() . In case default constructor can not be used, you have to use one4 of accessible super constructors
Constructors have the same name as the class name and if you're able to inherit them into the subclasses, they can no longer be constructors of subclasses. The default parameterless constructor is always inherited though.
Constructors are invoked to create objects from the class blueprint, ie, to initialise the data members of a class. If a subclass were to inherit a constructor,then while calling a subclass you need to have the knowledge about the parent class' data members too. That is not what one would see in real life scenario. For example, if you create an object of type Ferrari, you would definitely be interested about initialising parameters like speed,acceleration and you would not bother about initialising the parameters of a Car object, even though Ferrari inherits from Car. Therefore, while calling the constructor of a Ferrari, you would only and only be bothered about the members of Ferrari and not the members of its parent class. I hope to have made my point clear.
Related
default constructor invoke no_argument constructor in super class reference
and this last constructor used to instantiate object from this class,How ? i mean what does superclass constructor body exactly do ?
example
public class Child extend Fragment {}
if i tried to instantiate this class Child
Child a = new Child() ;
while compiling compiler invoke no-argument constructor in Fragment class .
in android.app package i found that no-argument constructor has no body
public Fragment() {}
Question how could this constructor be useful ? it do nothing !
P.S
i mean by
how could this constructor be useful?
how does it instantiate its class although it empty , where is the code that instantiate super class?
Question how could this constructor be useful ? it do nothing !
The purpose of a constructor, whether empty or not, is to provide an instance of the class. The constructor body, if it exists, may further do additional operations necessary when first creating the instance.
The constructor may not be doing anything itself but it returns an instance, on which you may further call public methods defined in the class.
For example, in your mentioned Fragment class, let's suppose there is an attach() method. If the attach() method is non-static, you will need to create an instance (using the empty constructor) to call the attach() method on it irrespective of whether the constructor does anything or not.
how does it instantiate its class although it empty
A constructor doesn't need any code in its body to be instantiated.
Calling new ClassName() (with appropriate parameters, if any) is enough. It is the job of JVM to create the object at runtime. You don't need to write any specific code inside a constructor for that. That extra code, if you wish, can help the instance start off with a specific state by setting some fields or calling methods, etc.
where is the code that instantiate super class?
A constructor in a subclass (or any class, for that matter) only generates an instance of that class. It doesn't need to instantiate its super class. You may call the super class constructor (using super()) if it has some important initialization code, but it's not compulsory. Also, subclasses don't inherit constructors from super classes. But they do inherit the public and protected fields and methods.
Regarding the Fragment class, you have have some confusion regarding its use which can be clarified here.
The syntax for calling a superclass constructor is
super();
or:
super(parameter list);
Question how could this constructor be useful ? it do nothing !
The super constructor could be used to initialized properties common for all subclasses. If it's empty it still can be used by reflection API.
Fragment.class.getConstructor().newInstance();
or
Child a = new Child() ;
a.getClass().getSuperclass().getConstructor().newInstance();
the last line explicitly invokes a constructor of the superclass.
an empty constructor (aka default constructor) means only that an instance can be created without any further work. This can be due to framework requirements or the instantation is ok with the default values for the attributes.
If the empty constructor is the only constructor in the class, it is not required to write it, its there by default.
Although if there are other constructors (with parameters), one must explicitly state the default constructor.
This question is mainly in reference to Luiggi's answer to this SO question:
Why can you not inherit from a class whose constructor is private?
I understand that Java enforces that every subclass constructor must call one of its superclass's constructors. If all the superclass's constructors are private, this is obviously not possible. So, if a subclass theoretically could inherit from a superclass with private constructors, the result would be that you couldn't call a constructor on the subclass.
But what if I never intend to create an instance of the subclass anyway? For example, what if my subclass only adds static fields and methods, and I'm only interested in using the static fields and methods of the superclass? Then I don't need a constructor for the subclass.
what if my subclass only adds static fields and methods, and I'm only
interested in using the static fields and methods of the superclass
In that case you don't need inheritance - use composition!
You should seal your class by declaring it as final. Then it is guaranteed that no sub-classes can be made
If only adding subclasses and can only create the parent class, the child "class" is really just a helper class without adding any functionality/responsibilites/etc. to the parent. In many respects, it's meaningless.
A subclass of this sort would not be a legitimate subclass. Even if all of its fields and methods were declared static, it would inherit all of the fields and methods of all of its superclasses, all the way back up to Object. And there are non-static methods in Object. So this subclass would have some set of non-static methods (and possibly fields) in its declaration.
This subclass could then be used as a type of a field, variable, type parameter or method argument (i.e. anywhere a type can be used). The compiler would have to keep track of the fact that this particular type could only be used in some restricted sense. (Imagine a method that returned a value of this subclass for example).
There are, I'm sure, many more gotcha's for this sort of thing.
So, bottom line, it would make writing a compiler really hard.
I have an abstract super class and several subclasses that inherit fields defined in the super class, but each subclass has different values for those fields. When the subclass is called, I use the constructor to set the fields appropriately.
Should I use direct references to do this field = value, or should I use the super class set methods setField(value);?
I'd rather keep the fields private, so I want to avoid direct references.
The other alternative is to call the super constructor, which would allow me to use direct references in the super class constructor super (T value) and in the super class SuperClass(T value){ field = value}. Would this be the best way? I could even use set methods inside the super constructor, but this seems like it would be redundant.
One great advantage and one great reason why abstract superclasses are used is to save coding time and make your class architecture that much easier.
Therefore, if you have a superclass that has common fields with subclasses, then you should take a second look at your architecture.
To solve your problem, remove any redundant fields that are in the subclasses but already exist in the superclass. Whenever you want to utilize the fiels, simply use the superclasses reference. Call for instance the superclasses constructor to set the values for the fields etc.
Whenever you want to retrieve the fields, call "super.getValue(...)" etc
In general, you should make them private and access them using getters and setters. If subclasses are allowed to set them directly, they could violate the contracts of the superclass by setting invalid values.
And if the subclasses differ only in the values of those superclass fields, then you shouldn't use subclasses at all; just create instances of the superclass with different values.
I have recently been moving through a couple of books in order to teach myself Java and have, fortunately, mostly due to luck, encountered very few difficulties. That has just changed.
I read a section on the following under inheritance and the whole superclass subclass setup
-- When a new superclass object is created, it is, like all objects, assigned a reference (superReference in this example)
-- If a new subclass object (with the defining subclass extending the superclass) is created, and then the superReference reference is set to refer to that instead of the original object, it is my understanding that, since the reference is made for a superclass, only members defined by the superclass may be accessed from the subclass.
First - is this correct?
Second: If I am overriding a method and therefore have one in the super and one in the sub, and I create a superclass object and then assign its reference, as I did above, to a subclass object, by the principle called something like Dynamic Method Dispatch, a called overridden method should default to accessing the subclass method right?
Well, my question is:
If a reference to a superclass-object is retooled for a subclass-object and will deny direct object.member access to subclass-defined members, only supporting superclass-defined members, how can, if a superclass reference is retooled for a subclass object, an overridden method apply to the subclass-object if access is limited by the superclass-originated-reference-
If you try like:
class SuperClass{
int intVar = 0;
void method(){
//in super class
}
}
class SubClass extends SuperClass{
int intVar = 2;
void method(){
//in sub class
}
}
Then
SuperClass obj = new SubClass();
int val = obj.intVar;// this is taken from SuperClass as variables are decided on reference basis
//if both superclass and subclass contain the same variable it is called shadowing
obj.method();// it is taken from the SubClass as it is method overriding
//and is decided at runtime based on the object not the reference
Check comments. Hope this helps.
only members defined by the superclass may be accessed from the subclass.
First : This is just plain wrong. The subclass may access it's own member without a problem. However once you have assigned a subclass instance to a super class variable (reference) the you can only call methods or members made accessible from the super class only. Is this what you meant to say?
Second : Methods that will be executed are the methods in the instance (object). Not the methods in reference (variable) type. So yes overridden methods will always be executed.
Third : A subclass may override a method but not a instance property. Whatever member variables are in the super class will be in the subclass as well. And you can override methods in the subclass just so long as you keep their existing access modifier or use a more accessible access modifier.
In Oracle documentation doesn't mention that or at least it is not clear or explicitly explained. This behaviour seems to me like virtual methods in C++ with the difference that in such language it is clear through the use of the keyword virtual preceding the methods defined in the base or parent class (superclass in java) and that must be redefined in the child class. In C++ there are not virtual variables, just virtual methods.
In that case, when we have a pointer (reference) to a base class that points to an instance of a child class and there are methods with the same signature and variables with the same name in both the parent and child classes, the definitions of the methods that will be executed are those of the parent class if they are not preceded by the keyword virtual, on the other hand the definitions in the child class will be executed for the methods declared as virtual.
In the case of the variables, the ones in the base class are taken and not the ones in the child classes.
Resuming, the similarities are:
-In java, variables are taken based in the reference
-In C++ there are not virtual variables
So in the case we are talking about, hidding variables in the child classes or subclasses are not taken but the hidden
-In java, methods are taken based on the object or instance
-In C++ virtual methods must be redefined in the child classes and those are taken
What do we we call a constructor, if it is not a member of a class as stated in Oracle doc: http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
I think the term "member" was defined to exclude constructors for the sake of convenience. Constructors, even public ones, are not inherited; members are inherited (unless they are static and/or private). It would be awkward when talking about the rules of inheritance to always have to say "members except constructors".
From the Java Language Specification, ยง8.2:
Constructors, static initializers, and instance initializers are not members and therefore are not inherited.
Just call constructors "constructors".
Its a special method that every class has, which is called after creation of the object. in JVM its called using invokespecial so, lets just call it a special method?
And since there is just 1 special method in Java - they all call it "constructor"
All the doc is saying is that the constructor is not inherited by default. Since the constructor is a method that is invoked on the construction of the object in the memory heap, then once you create a subclass that inherits from a super class, the constructor of the super class is not invoked by default.
For instance if you have a class Vehicle and a subclass Car, assume the Vehicle constructor is as follows:
public Vehicle(String vehName) {
this.vehName = vehName;
}
Then, even though your class Car inherits from class Vehicle, the vehName member (field) will not be set as the constructor above does.
So you will need to do something like this:
public Car(String vehName) {
super(vehName);
}
Hope that helps
In Java, a class body (the area between braces) can contain the following key items: (1) Fields (2) Methods (3) Other Classes (nested classes) (4) Constructors (5) Initializers
An object created from a particular class shall take the shape that is similar to the blueprint (class) from which it's created. Now, if you look at items that can be contained in a class body, only item (1) to (3) help in determining what sort of object can be created from a particular class definition.
Constructors and initializers only play part in actual creation of the object (e.g. initialization of already defined fields), but do not determine what shape/state that object shall carry, and what behaviors it will display.
For this reason, to me, it make sense to call item (1) to (3) class members (i.e. class members are those items within a class body that determine how an object created from the class looks like and behave); whereas constructors and initializers are not members because their absence in a class definition does not affect a class state and behavior.
As such, only class members can be inherited as the whole point behind inheritance is to enable a subclass reuse state and behavior of its superclass.
A Constructor is a method which is in a class which is used to create a new instance of that class.
Being a member of a class just means that the item in question is in the class.
Constructor is a method which name is same as the class. It is used to initialize the object of class. It's implicit in action. Parametric constructor initialize object with different value.