简体   繁体   中英

How to return class - type in a method

I have a class

public class Engine {

    Double engineSize;
    public Engine(){
        this.engineSize = 1.0;
    }
    public Double getEngineSize() {

        return engineSize;
    }
}

I have another class:

public class ModelT {

    public Engine getEngine() {

        return null;
    }}

Now I want to pass this test:

@Test

public void shouldHaveTheCorrectEngineSize(){
    assertThat(modelT.getEngine().getEngineSize(), is(1.0));
}

I have the difficulty how can I return the Engine type in a method, I tried several ways but knowledge is limited because I am beginner to java.. Could you please tell me how could i do this? and what is the name of concept that i could further read on..

You need to store an instance of Engine in your ModeT class:

public class ModelT {

   private Engine eng;      
  ModelT( Engine eng){
       engine = eng;
  }

    public Engine getEngine() {

        return eng;
    }}

then in you Main - create an Engine object and pass in to modelt:

 Engine eng = new Engine();
  ModelT car = new Modelt(eng);

Maybe i'm not understanding your question but your test never will return ok because in your ModelT method getEngine you are returning a null..

Try with below code:

public class ModelT {
    public Engine getEngine() {
        return new Engine();
    }
}

It's a little hard to see what you're trying to achieve.

You could look into instanceof to get the class of Engine.

You might want to look into inheritance and the various ways you can relate classes.

https://www.tutorialspoint.com/java/java_inheritance.htm

Your getter will make more sense if you associate the Engine class with the ModelT and by associating I mean using a Composition relationship

public class ModelT {
    private Engine myEngine;
    //some setter, DI or Constructors here 
    public Engine getEngine() {

        return myEngine;
    }
}

how could I return the value of public double getEngineSize() in the class ModelT??

you have somewhere:

ModelT foo = new ModelT();
Engine e = foo.getEngine();
double s = e.getEngineSize();

This test will never pass, because you return null in the getEngine() method. If you call getEngineSize() on null , you will receive a NullPointerException

You need to do something like this:

public class ModelT {

    public Engine getEngine() {

        return new Engine();
    }
}

Then you will be able to use your Engine .

Because of your questoin about how to learn the basics in Java, I would recommend you the Java-Basics from Oracle directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM