We help IT Professionals succeed at work.
Get Started

Java: Inner classes - How to have access to inner class variables

Software Software
on
113 Views
Last Modified: 2020-03-10
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"));
    }
}

Open in new window


public class Car {
    private String brand;
    private String color;
    private Engine engine;


    public Car(String brand, String color, Engine engine){
        this.brand=brand;
        this.color=color;
        this.engine=engine;
    }

    public Engine getEngineType(){
        return new Engine(engine.getType());
    }


    public void setEngine(Engine engine){
        this.engine=engine;
    }

    private class Engine{
        private String type;

        public Engine(String type){
            this.type=type;
        }

        public String getType() {
            return type;
        }
    }
}

Open in new window

Comment
Watch Question
CERTIFIED EXPERT
Commented:
This problem has been solved!
Unlock 1 Answer and 5 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant

An Experts Exchange subscription includes unlimited access to online courses.

Get Started
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE