Java: Inner classes - How to have access to inner class variables
Hello,
I have a class car and an inner class engine. The inner class shouldn't be visible outside of the class car.
Is there still a way to give a Car an Engine as parameter?
Error: Car.Engine has private access in Car
Here is my code:
public class Main { public static void main(String[] args) { Car car = new Car("VW", "Red", new Car.Engine("Diesel")); }}
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
Like Krakatoa says, if you want to use a private inner class, it should be entirely used for implementation details within the class.
One way to think about this is, you should be able to delete that inner class and replace it with something else and no code outside of the class should be affected.
You can see that the code you tried to write wouldn't satisfy that, because you're building an Engine outside to pass in. So that code would need to be changed if you deleted Engine.
So even after the rewrite Krakatoa proposed, the class is still passing Engine instances outside itself (e.g. getEngineType()).
I think a better rewrite would be to have getEngineType () return a String (this.engine.getType()) and then the setEngine method could be renamed to setEngineType(String type) and inside that create a new Engine instance.
I'd write out the code, except I'm using my phone and it would take too long to type :(
Anyway, hope that helps,
Doug
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
krakatoa
One way to think about this is, you should be able to delete that inner class and replace it with something else and no code outside of the class should be affected.
You can see that the code you tried to write wouldn't satisfy that, because you're building an Engine outside to pass in. So that code would need to be changed if you deleted Engine.
So even after the rewrite Krakatoa proposed, the class is still passing Engine instances outside itself (e.g. getEngineType()).
I think a better rewrite would be to have getEngineType () return a String (this.engine.getType()) and then the setEngine method could be renamed to setEngineType(String type) and inside that create a new Engine instance.
This is top advice and deserves more of the credit really on this question. In particular the dimension Doug mentions that inner code should be replaceable without any effect on the outside world. Clincher.
If you want to re-allocate your points in this one Software Software, then do. Inc girionis' contribution. My kludge is a workaround that Doug pointed out is just a workaround.