Here's an implementation of the Courses class that meets the
requirements mentioned in the prompt:
Source Code..
public class Courses {
private String[]
courseNames;
public Courses() {
System.out.println("I am not enrolled in any course yet");
}
public
Courses(String... courseNames) {
if
(courseNames.length > 0) {
this.courseNames = courseNames;
System.out.println("My enrolled courses are: " +
String.join(", ", courseNames));
} else {
System.out.println("I am not enrolled in any course yet");
}
}
}
The Courses class has a private instance variable
courseNames, which is an array of strings. We have defined two constructors:
A no-arg constructor, which simply displays the message
"I am not enrolled in any course yet".
A parameterized constructor that takes variable arguments
courseNames of type String. If courseNames is not empty, the instance variable
courseNames is set to the input value and the message "My enrolled courses
are: " followed by the names of the courses separated by commas is
displayed. Otherwise, the message "I am not enrolled in any course
yet" is displayed.
To use this class, we can create objects of Courses and call
methods on them as shown below:
// create a Courses object without any course name
Courses courses1 = new Courses();
// create a Courses object with course names
Courses courses2 = new Courses("Mathematics",
"Science", "English");
In the above code, we create two objects courses1 and courses2 of Courses class using different constructors.
The output of the code
would be:
For 1st object.
I am not enrolled in any course yet
For 2nd object.
My enrolled courses are: Mathematics, Science, English
No comments:
Post a Comment