Member Variable question

I am sure this is a simple question.

I have 2 simple classes

One called package1.Date
and one called package2.DateFormater

In Date I have 3 member variables. day,month and year - all int.

If I include and instantiate Date in the DateFormatter class and try and set the member variables it doesn't like it.

However if I put DateFormater in the same package it is fine.

Help???

Robert

Comments

  • Hi Robert

    By default, member variables are "protected" in Java. This means they can only be accessed by classes in the same package. If you would like visibility of the variables from another package then declare the variable as public i.e. public int day;

    However in Java it is generally recommended that all member variables are declared "private" and access is controlled through public "get" and "set" methods.

    For example:
    [code]
    package package1;

    public class Date {

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

    public int getDay() {
    return day;
    }
    public void setDay(int day) {
    this.day = day;
    }
    public int getMonth() {
    return month;
    }
    public void setMonth(int month) {
    this.month = month;
    }
    public int getYear() {
    return year;
    }
    public void setYear(int year) {
    this.year = year;
    }
    }
    [/code]


    Of course the specifics of the member variable access is up to you. You may decide the Date class is immutable and that will be no setters available. If that is the case consider making member variables "final". This will enforce immutability and introduce some performance benefits.


Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion