Default constructor that creates an empty object of that class - java

I'm having issues understanding why this isn't working and how to solve it. I am trying to create an empty restaurantlist object in my constructor.
This is the problem below:
The RestaurantList class should be used to store all the Restaurant objects. This class should inherit from the LinkedList<
Restaurant> class.
The class needs to provide a default constructor that creates an empty RestaurantList object.
public class RestaurantList extends LinkedList<Restaurant> {
//Default constructor
public RestaurantList() {
RestaurantList rList = new RestaurantList();
}
Exception in thread "main" java.lang.StackOverflowError

You are calling the constructor of RestaurantList within the constructor of ResturantList. This will end up in creating infinite calls to this constructor.

The constructor is referencing itself in the constructor.
An empty constructor would return an empty RestaurantList object.
public RestaurantList() {}

You are recursively calling the constructor inside the constructor. Every time you do that, you're creating a new stack frame, and since the stack is not endless, while your code is, you end up overflowing the stack.
There's no sense in calling new RestaurantList() inside the constructor. Maybe you've meant to call the parent constructor using super()?

Just have a blank/empty constructor for RestaurantList(). Your implementation is currently recursive. Hence, the stackoverflow !
Thanks for the opportunity to answer about stackoverflow in Stackoverflow :-)

You can also do a static method to provide an instance.
public class MyClass {
..
..
public static MyClass getInstance() {
return new MyClass();
}
}
You would call it thus:
MyClass mc = MyClass.getInstance();

Related

What's the constructor here?

The text of an exercise from a well known and basic Java programming textbook follows:
'Sometimes we would like a class that has just a single unique instance. Create a class Merlin that has one attribute, theWizard, which is static and of type Merlin. The class has only one constructor and two methods, as follows:
* Merlin —a private constructor. Only this class can invoke this construc-
tor; no other class or program can create an instance of Merlin
* summon —a static method that returns theWizard if it is not null; if theWizard is null, this method creates an instance of Merlin using the private constructor and assigns it to theWizard before returning it.
* consult—a non-static method that returns the string "Pull the sword
from the stone" '
Were you able to understand what the author is asking in the point 'Merlin -a private constructor' ? I know what a constructor is as well as what a private method is. But here what's the answer ? I thought of something like
public class Merlin {
private static Merlin theWizard;
/*public Merlin()
{
???
}*/
private Merlin()
{
this();
}
public static Merlin summon(Merlin theWizard) {
if (theWizard == null) {
theWizard = new Merlin();
return theWizard;
}
public String consult() {
return "Pull the sword from the stone";
}
}
and of course JavaBeans says 'private Merlin()' is recursive. So what do I do ? The next exercise is related to the above one and could help you to understand what the answer is; here it is:
Create a program that tests the class Merlin described in the previous exercise.
Use the toString method to verify that a unique instance has been created.
Thank you very much for all that you will be able to tell me.
This is an instance of the Singleton Pattern; in your case, just replace this() with super() to use the superclass's constructor (technically, if you don't place a super constructor call, the compiler will insert one for you; so you could just remove it).
Food for thought:
why is the Merlin class private?
why is the Merlin class static?
where's the rest of your code?
Get rid of this():
public class Merlin {
private static Merlin theWizard;
private Merlin() {}
...
}
this followed by parens is the syntax used to call a constructor of the same class, since you are not specifying any arguments inside the parens then you're referring to the no-argument instructor, which is the constructor this is being called from, so the constructor would call itself recursively until it runs out of stack space. The IDE is checking for this problem and trying to warn you about it.
Calling super() in the constructor is allowed (it calls the no-argument constructor in the superclass, which here is java.lang.Object) but not required, the compiler will insert a call to super if you don't.
By the way you can't have multiple overloads of a constructor or method with the same argument list. You can't have a public no-arg constructor and a private no-arg constructor.
The author is trying to describe a class that has control over how its instances are created, it makes its constructor private so that only the class itself is allowed to instantiate an object of that class.

Java NullPointerException when extending parent class

I'm getting NullPointerException whith below code.
Parent.java
public abstract class Parent {
public Parent(){
parentFunc();
}
public abstract void parentFunc();
}
Child.java
public class Child extends Parent {
ArrayList<String> list = new ArrayList<String>();
#Override
public void parentFunc() {
list.add("First Item");
}
}
when I create and instance of Child like new Child() I'm getting NullPointerException
Here is my console output
Exception in thread "main" java.lang.NullPointerException
at Child.parentFunc(Child.java:8)
at Parent.<init>(Parent.java:5)
at Child.<init>(Child.java:3)
at Main.main(Main.java:8)
I know that exception occurs because of Child.parentFunc() which called in parent constructor, but I really got confused. So I wonder what is going on
What is the order of creation;
When list variable is created
When constructors are called
When functions are created and called which called in constructors
When list variable is created?
It will be created once constructor of Child class runs.
When constructors are called?
When you try to make an object using new Child(), constructor is called for Child and it internally calls super() which calls the superclass constructor Parent().Note that the very first statement in Child() constructor is super().
The system will generate no-arguement constructor for you like this:
public child()
{
super();// calls Parent() constructor.
//your constructor code after Parent constructor runs
}
When functions are created and called which called in constructors
Clear out a bit what are you trying to ask .
Order Of Execution:
Parent Constructor->Child Constructor-->List
When parent constructor invoked the function called , You list not initialized and defailu value to the Object null is there,
#Override
public void parentFunc() {
list.add("First Item"); // list not yet initialized
}
You have an implicit Child() constructor. It calls Parent(), Parent() calls parentFunc() which is called in the sub-class. At that moment your list is still null and you get the NullPointerException (NPE).
See also:
Java Constructor and Field Initialization Order
It's usually a bad idea to call abstract methods from a constructor, as you exposed yourself to this kind of problem.

easy to refactor a static method call from an abstract class

I have lots of refences to this
MyAbstractClass.myStatic()
And I want to change them to non static method of an normal class, that is
myOtherClass.myMethod()
is there an easy way to do this using intellij ?
If MyOtherClass has a no-parameter constructor and you're OK calling it on a new instance every time, you could change the original method to
public void myStatic() {
new MyAbstractClass().myStatic();
}
and then inline the method. Similarly, if MyAbstractClass could hold a public static instance of MyOtherClass then the original method could be inlined.

Java jframe use of functions of main

I have been coding for few days with swing, but im getting to a problem ...I have functions and variables from different classes that are set in the main class that runs the program and calls the jframe.The problem i have is how do i call the functions in the main class in the jframe code that is set as a new class named as
public class login_sistema extends javax.swing.JFrame
I have tried puting the methods from main as static methods still i cant call the methods this way ...If you could help me i would be appreciated ...
I have tried puting the methods from main as static methods still i cant call the methods this way ...If you could help me i would be appreciated ...
Static methods are the last thing you should be using. It sounds like you want to have one object call the methods of another object, and to do that the first object must have a valid reference to the second object. This can be achieved by passing it through the first object's constructor parameter or via a setXXX(...) method.
For instance if the first object creates the second object, it could pass a reference to itself, this into the second object's parameter. e.g.,
The MainClass:
public class MainClass {
private OtherClass otherClass;
public MainClass() {
otherClass = new OtherClass(this);
}
}
the OtherClass:
public class OtherClass {
public MainClass mainClass;
public OtherClass(MainClass mainClass) {
this.mainClass = mainClass;
}
public void someOtherClassMethod() {
// now we can call methods with the MainClass reference
mainClass.someMainClassMethod();
}
}
For more details on your particular problem, consider telling us more about it and showing code.

What is the use of creating a constructor for an abstract class in Java?

I would like to know what purpose a constructor for an abstract class serves; as we do not instantiate abstract classes, why would we ever need such a constructor?
there will be times when you have some common initialization of instance variables that all the inheriting classes need to set up. You do instantiate an abstract class when you extend it and that concrete class has a constructor that will either supply the parameters to the constructor of the abstract class.
They can still be invoked by constructors of classes that inherit from that one, making code refactoring a good use for having a constructor in the abstract class.
If you have uninitialised final fields in an abstract class, you'll need to initialise them in a constructor.
E.g.
abstract class A {
final int x;
}
will not compile without a constructor that assigns to x.
If your class doesn't declare a constructor, javac will make a no-arg, do-nothing constructor for you. Then, when your subclass is initialized, it will call the generated no-op constructor and life is good.
However, if your class declares any constructor, javac will NOT make one for you. In that case, the subclass constructor needs to explicitly call the constructor of the parent class. Otherwise, you'll fail to initialize members of the parent class, as the above answer mentions.
Constructors for abstract classes are used by subclasses (invoked from subclass constructors using super(params) ).
You should make these constructors protected to make that clear.
You don't instantiate abstract classes but the constructor is invoked when a subclass is instantiated.
The use could be to initialize common attributes ie.
import java.util.List;
import java.util.ArrayList;
abstract class BaseClass {
protected List list; // visible from subclasses
public BaseClass() {
System.out.println("to abstract...");
// common initialization to all subclasses
list = new ArrayList();
list.add("a");
list.add("a");
list.add("a");
}
}
class ConcreteClass extends BaseClass {
public ConcreteClass(){
// The list is initialized already
System.out.println("now it is concrete and the list is: = "+ this.list );
}
}
class TestAbstractClass {
public static void main( String [] args ) {
BaseClass instance = new ConcreteClass();
}
}
Output
$ java TestAbstractClass
to abstract...
now it is concrete and the list is: = [a, a, a]
De-duplicating common knowledge/behaviour.
E.g. a Car: all your cars will be constructed out of a body and four wheels and an engine. So you do this part of the construction in the constructor for the abstract Car class by calling functions like Body(), Wheel(int x), Engine(). Each particular car class will have their own implementation of Body(), Wheel() and Engine() - but they all will do the same steps to construct the car from them, so there is no need to duplicate those steps in each of those classes. In this case you implement that common behaviour in the ancestor.
I agree, Constructors are created assuming there will be instances. If you have lot of common code you can think of creating a Constructor but it is much better to put it in a init() method.

Categories

Resources