(Using Encapsulation)
Create a class named 'Student' with 2 instance variables (both set as private)
The 2 variables are: String variable 'name' and integer variable 'roll_no'.
Create a get and set Method for each variable.
Also create a class with Main Method, where you will:
Create an object of the class Student
Allow the user to enter a value for the name and roll_no and accept the values by using
the set Method of each variable
Display the content of the object by using the get Method of each variable
import java.util.Scanner;
class Student {
private String name;
private int roll_no;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the roll_no
*/
public int getRoll_no() {
return roll_no;
}
/**
* @param roll_no the roll_no to set
*/
public void setRoll_no(int roll_no) {
this.roll_no = roll_no;
}
}
public class App {
/**
* The start point of the program
*
* @param args
*/
public static void main(String[] args) {
Scanner keyBoard = new Scanner(System.in);
System.out.print("Enter the student's name: ");
String name = keyBoard.nextLine();
System.out.print("Enter the student's roll no: ");
int roll_no = keyBoard.nextInt();
Student student = new Student();
student.setName(name);
student.setRoll_no(roll_no);
System.out.println("\nThe student's name: " + student.getName());
System.out.println("The student's roll no: " + student.getRoll_no());
keyBoard.close();
}
}
Comments
Leave a comment