Hi,
Hope you are doing fine. I have cooded the program in java as per your requirement. The code is clearly explained using comments that have been highlighted in bold. Also, in the main methos I have initialized two objects in order to depict the difference between the parameterized and non parameterized constructors that are used during initialization of an object. You may change the main method as per your requirement.
Program:
//class to store information about a
student
public class StudentData {
//declaring instance variables
//name is a public string variable that stores name of
student
public String name;
// marks is a public double variable that
stores the marks of a student
private double marks;
//department is a private string variable that
stores the department of a student
private String department;
//initializing the variable using a non
parameterized constructor
public StudentData() {
this.name="none";
this.marks=0;
this.department="none";
}
//initializing the variable using a
parameterized constructor
public StudentData(String name, double marks, String
department) {
this.name = name;
this.marks = marks;
this.department = department;
}
//getters and setters for private data
members
//getter for marks
public double getMarks() {
return marks;
}
//setter for marks
public void setMarks(double marks) {
this.marks = marks;
}
//getter for department
public String getDepartment() {
return department;
}
//setter for department
public void setDepartment(String department) {
this.department = department;
}
//method to display the value of each member
variable using a method.
public void display()
{
System.out.println("Name:
"+name);
System.out.println("Marks:
"+marks);
System.out.println("Department:
"+department);
}
public static void main(String[] args) {
//creating new object s1
using non parameterized constructor of StudentData
StudentData s1=new
StudentData();
//creating new object s1
using non parameterized constructor of StudentData
StudentData s2=new
StudentData("Harry",90,"Computer Science");
//printing contents of
s1
System.out.println("S1 before
setting values manually: ");
s1.display();
//setting values to instance
variable of s1 objects.
//since name is public we need not
use a setter to set some value
s1.name="Ron";
//using setters for marks
and department
s1.setMarks(40);
s1.setDepartment("Electronics");
//printing contents of
s1
System.out.println("\nS1 after
setting values manually: ");
s1.display();
//printing contents of
s1
System.out.println("\nValues of S2:
");
s2.display();
}
}
Executable code snippet:
Output:
Get Answers For Free
Most questions answered within 1 hours.