I wrote Accessors and Mutators methods, but still I cant access private variables! why?

2.9k Views Asked by At

I wrote my class with its private variables and then I wrote the accessor and mutator methods needed to access those variables, but that does not work when I run it after writing the main class. Why does that happening ?check my code here :

public class DateTest{
    public static void main (String [] args){

        Date d1 = new Date();
        Date d2 = new Date();

        d1.month = "February ";
        d1.day = 13;
        d1.year = 1991;

        d2.month = "July";
        d2.day = 26;
        d2.year = 1990;

        d1.WriteOutput();
        d2.WriteOutput();
        }
    }


      class Date {

private String month;
private int day;
private int year;

public String getMonth(){
    return month;
                     }
public int getDay(){
    return day;
                   }
public int getYear(){

    return year;    }

public void setMonth(String m){
    if (month.length()>0)
        month = m;
                      }
public void setDay(int d){
    if (day>0)
     day = d;       }
public void setYear(int y){
     if (year>0)
     year = y;
                          }

   public void WriteOutput(){
    System.out.println("Month " + month + "Day "+ day + " year" + year);
    }
    }

Please guys just be patient with me, I'm really a "novice" programmer

4

There are 4 best solutions below

2
On BEST ANSWER

Java has no syntactic sugars like C# and won't allow you to do calls in from object.property even though you have provided the access methods. Properties are purely a design pattern and are not refleted in syntax of a language itself.

You need to call them explicitly like d1.setMonth("February "); and String val = d1.getMonth();.

0
On

The accessor methods are supposed to be called. That's it.

d1.setMonth("February");
d1.setDay(13);
1
On

private members can be directly accessed only within the members of the same class. DateTest is another class and hence the below is not possible

d1.month = "February ";
        d1.day = 13;
        d1.year = 1991;

        d2.month = "July";
        d2.day = 26;
        d2.year = 1990;

Replace the above code with using corresponding setter methods.

0
On

Always use setters and getters to access the private variables.