Instance Variable Initialization Demo with Constructor - Java

Create a class called Date that includes three pieces of information as instance variables—a month (type int), a day (type int) and a year (type int). Your class should have a constructor that initializes the three instance variables and assumes that the values provided are correct. Provide a set and a get method for each instance variable. Provide a method displayDate that displays the month, day and year separated by forward slashes (/). Write a test application named DateTest that dem- onstrates class Date’s capabilities.
 

Date Class


class date
{
    int day, month, year;
   
    public void displayDate()
    {
        System.out.println("\n"+getday()+"/"+getmonth()+"/"+getyear());
    }
   
    date()
    {
    }
    date(int d, int m, int y)
    {
        setday(d);
        setmonth(m);
        setyear(y);       
    }
    void setday(int d)
    {
        day = d;
    }
    void setmonth(int m)
    {
        month = m;
    }
    void setyear(int y)
    {
        year = y;
    }
    int getday()
    {
        return day;
    }
    int getmonth()
    {
        return month;
    }
    int getyear()
    {
        return year;
    }
}




Test Program



import java.util.Scanner;

class secondapp
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int d, m, y;
       
        System.out.print("\nEnter Day :: ");
        d = sc.nextInt();
        System.out.print("\nEnter Month :: ");
        m = sc.nextInt();
        System.out.print("\nEnter Year :: ");
        y = sc.nextInt();
       
        date dt = new date(d, m, y);
        dt.displayDate();
    }
}

Post a Comment