0

So I have a subclass that inherits from another class. I want to create an object of the subclass Test and have its properties carry over to another class called Engine (explained below).

package comulap;


public class Test extends Comulap {


    public String fudge = "fudge";

    public static void main(String[] args){
        Test c = new Test();
    }

}

This is the superclass Comulap

package comulap;

import comulap.core.Engine;

public class Comulap {

    public String fudge;


    Engine engine;

    public Comulap(){

        engine=new Engine(this);
    }
}

And this is the engine class which I want to use the Test methods and attributes:

package comulap.core;

import comulap.Comulap;

public class Engine {

    Comulap comulap;

    public Engine(Comulap c){
        comulap=c;
        System.out.println(comulap.fudge);
    }

}

However, when I run this, the engine object thinks fudge is null as if just a regular Comulapobject is being passed, not a Test class. How do I pass the Test class through in the regular Comulap class constructor not just a standard Comulap class?

James Clarke
  • 29
  • 1
  • 5
  • 1
    You define a new, different member variable `fudge` in `Test`. Instead set `fudge` in a constructor of `Test` and don't define it (again). – Michael Butscher Sep 09 '18 at 22:09
  • Variables are not polymorphic, and you will want to instead not hide the fudge variable as you're doing but instead set and get it via setters and getters – Hovercraft Full Of Eels Sep 09 '18 at 22:10
  • I just realised this mistake, fixed it by assigning fudge in the test constructor, however this still returns null in the engine object – James Clarke Sep 09 '18 at 22:13
  • Did you 1) get rid of the re-declaration of the variable in Test? 2) Are you using getters and setters to access it? 3) Are you correctly assigning it in the constructor? In the super constructor as well? – Hovercraft Full Of Eels Sep 09 '18 at 22:17
  • Also, you're trying to access the fudge String in Engine's constructor which is called within the Comulap construtor -- so you're trying to assess the state of the Comulap object ***before*** it has been fully constructed, something that you should *never* do. – Hovercraft Full Of Eels Sep 09 '18 at 22:32

0 Answers0