430,432 views
18 votes
18 votes
What needs to be public and what needs to be private?

What needs to be public and what needs to be private?-example-1
User Mike Shultz
by
2.7k points

1 Answer

26 votes
26 votes
In this scenario, the most appropriate implementation of the Car class would be:

public class Car
{
public String make;
public String model;
public Car(String myMake, String myModel) { /* implementation not shown */ }
}
In this implementation, the attributes make and model are both declared as public, which means that they can be accessed and modified by code outside of the Car class. This is appropriate, as the make and model of a car are typically considered to be public information that can be accessed by anyone.

The constructor for the Car class is also declared as public, which means that it can be called by code outside of the Car class. This is appropriate, as the constructor is used to create new instances of the Car class, and this functionality should be available to code outside of the class.

In contrast, if the attributes make and model were declared as private, they would only be accessible within the Car class and would not be available to code outside of the class. Similarly, if the constructor were declared as private, it would only be accessible within the Car class and could not be called by code outside of the class. These declarations would limit the ability of code outside of the Car class to access and use the make, model, and constructor functionality, which would not be appropriate for this scenario.
User Bchang
by
2.9k points