The difference between public and private variables? Public variables, are varia
ID: 3600462 • Letter: T
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 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
}}
Explanation / Answer
Hi, I have added setters and getters.
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 String getOwner() {
return owner;
}
public String getModel() {
return model;
}
public void setOwner(String owner) {
this.owner = owner;
}
public void setModel(String model) {
this.model = model;
}
}
##########
public class MainClass {
public static void main(String[] args) {
//make an object (instance) of the class
Car bmw=new Car();
bmw.setModel("bmw"); //can access public variable
bmw.setOwner("ahmad");//error: owner has private access in Car
//instead we use the setter
bmw.setOwnerName("ahmad");
System.out.println("the owner name is:" +bmw.getOwner() ) ; //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
}}
/*
Sample run:
the owner name is:ahmad
the owner name is:ahmad
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.