Print Student Details Using constructor
Let's try to create a simple example in java without user input :
➤ Example : student.java;
class Student{
int roll_no;
String name, myclass, gender;
//creating a parameterized constructor
Student(int roll, String nam, String c) {
roll_no = roll ;
name = nam;
myclass = c;
}
//method to display the values
void display(){
System.out.println("My name is "+name+", I study in "+myclass+" class and my roll number is "+roll_no);
}
public static void main(String arg[]){
//creating objects and passing values
Student s1 = new Student(2, "Ankaj", "12th");
Student s2 = new Student(25, "Anmol", "9th");
Student s3 = new Student(1, "Sudeep", "10th");
//calling method to display the values of object
s1.display();
s2.display();
s3.display();
}
}
Output :
My name is Ankaj I study in 12th class and my roll number is 2
My name is Anmol I study in 9th class and my roll number is 25
My name is Sudeep I study in 10th class and my roll number is 1
Comments