1 Provide Java code for a simple class of your choice Be sur
1. Provide Java code for a simple class of your choice.
Be sure to include at least one constructor, two methods and two fields. The fields should be private.
2. Create a test class to constuct and call the methods of your class.
3. Describe your class and demonstrate your code functions properly.
Solution
//http://ideone.com/Kptsty
class Student{
private int id;//id field or data member or instance variable
private String name; //name field or data member or instance variable
public Student(){ //Default constructor with no argumeents
id=0;
name=\"\";
}
public Student(int id,String name){//constructor with arguments setting id and name field.
this.id=id;
this.name=name;
}
public void setName(String name){//setter method to set name field.
this.name=name;
}
public String getName(){//getter method to get name field.
return name;
}
public void setId(int id){//setter method to set id field.
this.id=id;
}
public int getId(){//getter method to get name field.
return id;
}
public String toString(){//returns concatenated string with id and name
return id+\",\"+name;
}
}
class TestStudent{
public static void main(String args[]){
Student s1=new Student();//creating an object of Student
System.out.println(s1.toString());//accessing member through toString() method.
s1.setId(10);s1.setName(\"Chegg\");//setting member fields through setter method.
System.out.println(s1.toString());
}
}
Output refer url http://ideone.com/Kptsty
This is sample program which demos how to create class and insitate an objects of it. Calling there methods to set the value.
Refer the code comments for more details on there usage.
