user3212568
user3212568

Reputation: 55

New to Java, trying to use Date as attribute

I'm completely new to Java and i'm trying to create a simple class named Message to print simple text messages.

When I try to use the class in my main code, it always errors when I include the date. When I leave the date out of my constructor it works fine.

What i've got so far:

import java.util.Date;

public class Message {

    private String sender;
    private Date curdate;
    private String message;

    // constructor when empty
    public Message() {
        sender = "unknown";
        curdate = curdate;
        message = "unknown";

    }

    // constructor with 3 values
    public Message(String s, Date d, String m) {
        sender = s;
        curdate = d;
        message = m;
    }

    public String getSender() {
        return sender;
    }

    public void setSender(String s) {
        this.sender = s;
    }

    public Date getDate() {
        return curdate;
    }

    public void setDate(Date d) {
        this.curdate = d;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String m) {
        this.message = m;
    }

    public String toString() {
        return sender + " " + curdate + " " + message;
    }

}

Upvotes: 1

Views: 110

Answers (2)

java seeker
java seeker

Reputation: 1266

you should understand difference between java object and referrence.

private Date curdate; #this is just a java referrence

you did not assign any Date object to curdate reference.

please assign curdate=new Date()

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201487

Your empty constructor is wrong

public Message() {
    sender = "unknown";
    // curdate = curdate; /* curdate = {undefined} */
    curdate = new Date();
    message = "unknown";
}

Upvotes: 1

Related Questions