Java Classes and Objects
Task : Developing basic Java classes with attributes and methods.
Write a class Student that has the following attributes:
- int id
- String name
- double cgpa
There is a set method and a get method for each of the attributes. There is also a main method in this class. Inside the main method create one object of the Student class and demonstrate all the methods.
Answer and Code
import java.lang.*;
public class Student
{
private int id;
private String name;
private double cgpa;
public void setid(int id)
{
this.id=id;
}
public void setname( String name)
{
this.name=name;
}
public void setcgpa( double cgpa )
{
this.cgpa=cgpa;
}
public int getid()
{
return id ;
}
public String getname()
{
return name;
}
public double getcgpa()
{
return cgpa;
}
public void display()
{
System.out.println(“ID: “+id);
System.out.println(“NAME: “+name);
System.out.println(“CGPA: “+cgpa);
}
public static void main( String args[])
{
Student s= new Student ();
s.setid(47991-2);
s.setname(“Biswas, Swarup”);
s.setcgpa(3.15);
System.out.println(“ID : ” +s.getid());
System.out.println(“Name : ” +s.getname());
System.out.println(“CGPA : ” +s.getcgpa());
}
}