Question: The difference between public and private variables? Public variables, are variables that are visible to all classes. Private variables, are variables that are visible only
The difference between public and private variables?
Public variables, are variables that are visible to all classes.
Private variables, are variables that are visible only to the class to which they belong. You should provide functions which can manipulate the private data, such as setter & getter methods.
Example :
public class Car { private String owner; public String model; //need to make setter method to set a value to owner name public void setOwnerName(String ownerName) { owner=ownerName; } //need to make getter method to get owner name value public String getOwnerName() { return owner; } }
------------------------------------------------------------------------------ ------------------------------------------------------------------------------
public class MainClass { public static void main(String[] args) { //make an object (instance) of the class Car bmw=new Car(); bmw.model="bmw"; //can access public variable bmw.owner="ahmad";//error: owner has private access in Car //instead we use the setter bmw.setOwnerName("ahmad"); System.out.println("the owner name is:" +bmw.owner ) ; //error: owner has private access in Car //instead we use the getter System.out.println("the owner name is:" + bmw.getOwnerName()); //it will print: the owner name is: ahmad }}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
