Writing a simple class with accessors and mutators
I am very much a newbie to Java. I have been asked to Write a java class for a very simple Course class, named Course, that has the data members name and credit hours (e.g. "Programming and Logic I", 4). Your class needs to include the accessor (i.e. get) and mutator (i.e. set) methods for each attribute and at least one overloaded constructor which initializes the data members name and credit hours.
This is what I have so far, but I believe I am so far off and my brain just doesn't want to work right now.
public class Course {
public String courseName;
public int creditHours;
public Course(String courseName, int creditHours) {
this.courseName = courseName;
this.creditHours = creditHours;
public String getCourseName() {
return courseName;
}
public int ge开发者_Go百科tCreditHours(){
return creditHours
}
public void setCourse(String course)
{
this.course = course;
}
public void setHours(String hours)
{
this.hours = hours;
}
}
}
Your syntax is just a bit off. In Java, constructors are declared as methods of a class almost like any other methods. Try
public Course {
private String courseName;
private int creditHours;
public Course() {
courseName = null;
creditHours = 0;
}
public Course(String courseName, int creditHours) {
this.courseName = courseName;
this.creditHours = creditHours;
}
// ... and your getters and setters, which look fine except for one missing semicolon
}
First of all, your constructor should end after you initialize your variables. Then you have your method implementations after that, within the class brackets. You should also make your variable declarations private. Only the methods will be public or available externally.
Secondly, your setter methods should be setting your variable names. In other words
this.courseName = course;
instead of
this.course = course;
you don't have a this.course.
Hope this helps.
精彩评论