In this tutorial we will learn how to about java program to display student details using class and object . We will create a class of student then will create object and access these object values using getter and tostring() method .
Java program to display student details using class and object
Firstly , we will create a class MyStudent with two fields rollNo and name . We will create getter , setter of this class and override toString()method in java .
package com.demo;
public class MyStudent {
private int rollNo;
private String name;
public MyStudent() {
super();
}
public MyStudent(int rollNo, String name) {
super();
this.rollNo = rollNo;
this.name = name;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "MyStudent [rollNo=" + rollNo + ", name=" + name + "]";
}
}
Now we created class MianClass , Here we will initialized object myStudent1, myStudent2, myStudent3 of classs MyStudent. In this example we will access value of student using getter and toString() method and display using System.out.println() method in java.
package com.demo;
public class MainClass {
public static void main(String[] args) {
MyStudent myStudent1 = new MyStudent(100, "Php king");
MyStudent myStudent2 = new MyStudent(100, "Java king");
MyStudent myStudent3 = new MyStudent(100, "Html king");
//using to string
System.out.println("myStudent1:"+ myStudent1.toString());
System.out.println("myStudent2:"+ myStudent2.toString());
System.out.println("myStudent2:"+ myStudent3.toString());
//using getter
System.out.println("myStudent1 rollno :"+ myStudent1.getRollNo() +",
Name :"+ myStudent1.getName());
System.out.println("myStudent2 rollno :"+ myStudent2.getRollNo() +",
Name :"+ myStudent2.getName());
System.out.println("myStudent3 rollno :"+ myStudent3.getRollNo() +",
Name :"+ myStudent3.getName());
}
}
In this tutorial we have how to write java program to display student details using class and object . We have also learn getter , Setter and toString() method in this tutorial .