Calling a subclass method for a superclass constructor - java

I have a superclass Class and a subclass SubClass. Our teacher has asked us to put all the class dependent methods in Class and all the independent ones in SubClass. For example, I need to have the search and sort methods in SubClass.
However, in main, the array list that I work with is defined with the Class constructor and it does not let me call the method from the SubClass to search/sort.
How can I fix that?
Keep in mind that search and sort need to be in the subclass. I cannot put them in the super class just so the program would work.
Thanks!

Don't. That's a terrible idea. Because the sub-class hasn't been instantiated when you're in the super constructor. Instead, you have to finish the construction of your instance(s). Then you can call the method with your variable reference.

For just solving problem at hand. You can call the superclass constructor in subclass and instantiate a subclass object. This will let you instantiate the subclass object on which further you can call your sort etc.
public class SuperClass {
//definition
}
public class SubClass extends SuperClass {
SubClass(//arg) {
super(//arg)
}
}

Related

Does object creation of subclass create object of superclass, if yes Is it possible to access it in subclass?

My question is if we can access and use indirectly/implicitly created super class objects when we instantiate a subclass .
Lets say ClassA is super class of SubClassofA and we instantiate SubClassofA in a client class ClientClass using SubClassofA object = new SubClassofA();
Since whole inheritance hierarchy gets instantiated when we create a subclass objects, I was wondering, is it possible to access object of class ClassA in client class?
If not possible, what might be reasons? Wouldn't it save lots of heap memory if we can access super class objects without recreating those?
I might have misunderstood whole concept of constructor chaining and inheritance hierarchy but please let me know your thoughts on this.
public class ClassA {}
public class SubClassofA extends ClassA {}
public class ClientClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
SubClassofA object = new SubClassofA();
//Above construct means that an instance of super class ClassA exists too
// If we can use those super class instances directly, will it result in memeory saving?
//is it even possible to access implicitly created super class objects tied to subclass?
}
}
Since whole inheritance hierarchy gets instantiated when we create a subclass objects, I was wondering, is it possible to access object of class ClassA in client class?
This is something lot of people get confused. If you create object of subclass, that does not mean it create object of super class.
Its just a call to constructor of super class, just to ensure that all the required fields are initialized in super class, but this does not create object of super class.
This question will help you, understanding the concept.
Check Kevin's answer:
It doesn't create two objects, only one: B.
When inheriting from another class, you must call super() in your constructor. If you don't, the compiler will insert that call for you as you can plainly see.
The superclass constructors are called because otherwise the object would be left in an uninitialized state, possibly unbeknownst to the developer of the subclass.

Relating Constructor of Super Class in java

If I create an object of a sub-class with no constructors, then I know that the compiler will implicitly provide a default constructor. What if I create a constructor in the sub-class and try to access the super class constructor using the super keyword, and, now, the super class has no constructor in it. Will the compiler provide a default constructor for the super class as well?
Yes, if there is no specified constructor, there is always default empty constructor
Does the compiler provides a default constructor for the super class also???
The default constructor will be there whether or not there is a subclass that needs it. The default is supplied when the parent is compiled, not later.
...What if I created sub class Constructor and trying to access the super class constructor using the super keyword,and the super class has no constructor in it.
But it does: The default one.
It goes like this.
Lets speak about Object which is the supermost class in java, If you open an editor and just make a class, then it is presumed that It is extending Object. Every class in Java extends from Object. If you do not write your own constructor then Compiler will provide one.
But if you write your own constructor let's say a constructor with one argument, compiler will not provide you with any constructor.
Now lets say taht you extend the above class, then compiler will complain you saying that the superclass does not have a default constructor rather a custom constructor so you need to make one constructor for this child class since first constructor which is called starts from the supermost class that is OBJECT and then proceeds down the line.
Hope this answers comprehensively,
Thanks.
Yes the super always occurs even if you didnt explicit declare
public class FatherTest {
}
public class SonTest extends FatherTest{
public SonTest(String sonName){
super(); // this will always occurs
}
}
If you don't write a constructor for a class, the compiler will implicitly add an empty one for you.
That means this:
public class X {
}
is identical to this:
public class X {
public X() {
// there's also an implicit super(); added here, but that's not directly relevant
}
}
If the super class doesn't have explicit constructor, then an implicit default constructor will be added to it. So your super() will invoke that.
If the super class only have some constructors with parameters. Then super() in the sub-class won't compile. You have to explicitly use one of the defined super-class constructor super(param1, param2, ...), since super() will be called if you don't call it.

Inheritance can't call child class method

Hey i'm trying to call child class method(ChildClass extends SuperClass())
SuperClass s=new ChildClass();
s.childClassMethod();
It doesn't see the ChildClass method the only methods i can call are from SuperClass()
i know it's propably a stupid question but anyway cheers
That's right, you can't see it because s is type SuperClass which doesn't have this method - this would obviously break Polymorphism principle.
So you either have to change the code like ((ChildClass) s).childClassMethod(); or make s as ChildClass type.
Compiler doesn't know what instance this reference would be pointing to at runtime so it will only allow you to access super class's accessible methods at compile time
See
polymorphism
The parent does not know anything about any new methods the child possesses.
public class SuperClass {
// I have no method named "childClassMethod"...
}
public class ChildClass {
public void childClassMethod() {
// Do something.
}
}
SuperClass does not know about childClassMethod(). You would have to provide both classes with an interface or add that method to the parent and override it in the child.
Or, you could simply cast the object to the child class as others have suggested, but this can be unsafe.
((ChildClass) s).childClassMethod()
That is because the super class does not have that method.
If you want the super class to be able to call the method, you need to make it abstract and give it that method.
The subclass is a form of the super class, the super class is not a form of the sub class.

Calling static factory method with unknown class

Hi I have an abstract class which have many subclasses. Id like to make this abstract class' constrcutor private and create factory method. How should this method look like to work in the same way in every sub-class? If I make:
return new AbstractClass();
I get error saying: Class is abstract, cannot be instances... Should I use reflection?
You can access the constructor of the abstract class from the subclasses using the super keyword.
public SubClass() {
super(); // this will call AbstractClass()
// something else that you want to do for this subclass
}
As already pointed out in the comments, you can't use the new keyword with an abstract class. When you use new, you need to know the real type.
You could either implement the factory method in the abstract base class and make it decide which non-abstract subclass to return based on the parameters passed to the create method and/or some internal logic.
Or you could make the factory method itself abstract and implement it in every non-abstract subclass to return an object of that type.

Why do abstract classes in Java have constructors? [duplicate]

This question already has answers here:
Can an abstract class have a constructor?
(22 answers)
Closed 9 years ago.
Why does an abstract class in Java have a constructor?
What is it constructing, as we can't instantiate an abstract class?
Any thoughts?
A constructor in Java doesn't actually "build" the object, it is used to initialize fields.
Imagine that your abstract class has fields x and y, and that you always want them to be initialized in a certain way, no matter what actual concrete subclass is eventually created. So you create a constructor and initialize these fields.
Now, if you have two different subclasses of your abstract class, when you instantiate them their constructors will be called, and then the parent constructor will be called and the fields will be initialized.
If you don't do anything, the default constructor of the parent will be called. However, you can use the super keyword to invoke specific constructor on the parent class.
Two reasons for this:
1) Abstract classes have constructors and those constructors are always invoked when a concrete subclass is instantiated. We know that when we are going to instantiate a class, we always use constructor of that class. Now every constructor invokes the constructor of its super class with an implicit call to super().
2) We know constructor are also used to initialize fields of a class. We also know that abstract classes may contain fields and sometimes they need to be initialized somehow by using constructor.
All the classes including the abstract classes can have constructors.Abstract class constructors will be called when its concrete subclass will be instantiated
Because another class could extend it, and the child class needs to invoke a superclass constructor.
I guess root of this question is that people believe that a call to a constructor creates the object. That is not the case. Java nowhere claims that a constructor call creates an object. It just does what we want constructor to do, like initialising some fields..that's all. So an abstract class's constructor being called doesn't mean that its object is created.
Because abstract classes have state (fields) and somethimes they need to be initialized somehow.
Implementation wise you will often see inside super() statement in subclasses constructors, something like:
public class A extends AbstractB{
public A(...){
super(String constructorArgForB, ...);
...
}
}

Categories

Resources