Suppose you have class car in Java. This class car has inner classes: speed, mileage, parts, identifications each with their own respective variables etc... some maybe with their own inner classes.
Java code (example, not real java):
public class car {
public class speed {
String inmiles;
public class metric {
String inkm;
}
}
public car(arguments...){
speed.inmiles = argument1;
speed.metric.inkm = argument2;
}
}
If you declare a car object with the new
keyword in the main class (method), and want to provide the constructor with arguments to fill the inner classes' variablese, do you have to declare the inner classes in main as well?
Accessing the inner classes from within the car class does not work sadly, regardless whether the inner classes and variables are set to public.
As per my comment, please note that class names should start with an uppercase letter to make it easier to distinguish between class and variable access. So Car
, Speed
and Metric
should be used and thus Speed.inmiles
would indicate inmate
is meant to be a class variable and if it isn't you'd see the error more easily.
That being said, your code needs to create instances and then assign values to their fields/instance variables.
Very simplified example based on your code:
public class Car {
Speed speed;
public class Speed {
String inmiles;
Metric metric;
public class Metric {
String inkm;
}
}
public Car(String speedInMiles, String speedInKm){
//create the instance of Speed first
speed = new Speed();
speed.inmiles = speedInMiles;
//create the instance of Metric
//since Metric is an inner class of Speed you need an instance of Speed first
//so we'll use the "speed" instance created earlier here
speed.metric = speed.new Metric();
speed.metric.inkm = speedInKm;
}
}
Finally one design advice (there are more but I'll restrict myself :) ): don't use String
for basically numeric values but use e.g. double inMiles
etc. Also note that inKm
could be calculated from inMiles
so I'd not pass that separately.