//A Java class which is a fully encapsulated class.
//It has a private data member and getter and setter methods.package com.lidihuo;
public class Student{
//private data memberprivate String name;
//getter method for namepublic String getName(){
return name;
}
//setter method for namepublic void setName(String name){
this.name=name}
}
//A Java class to test the encapsulated class.package com.lidihuo;
class Test{
public static void main(String[] args){
//creating instance of the encapsulated classStudent s=new Student();
//setting value in the name members.setName("vijay");
//getting value of the name memberSystem.out.println(s.getName());
}
}
Compile By: javac -d . Test.javaRun By: java com.lidihuo.Test
vijay
//A Java class which has only getter methods.public class Student{
//private data memberprivate String college="AKG";
//getter method for collegepublic String getCollege(){
return college;
}
}
s.setCollege("KITE");
//will render compile time error
//A Java class which has only setter methods.public class Student{
//private data memberprivate String college;
//getter method for collegepublic void setCollege(String college){
this.college=college;
}
}
System.out.println(s.getCollege());
//Compile Time Error, because there is no such methodSystem.out.println(s.college);
//Compile Time Error, because the college data member is private.
//So, it cant be accessed from outside the class
//A Account class which is a fully encapsulated class.
//It has a private data member and getter and setter methods.class Account {
//private data membersprivate long acc_no;
private String name,email;
private float amount;
//public getter and setter methodspublic long getAcc_no() {
return acc_no;
}
public void setAcc_no(long acc_no) {
this.acc_no = acc_no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public float getAmount() {
return amount;
}
public void setAmount(float amount) {
this.amount = amount;
}
}
//A Java class to test the encapsulated class Account.public class TestEncapsulation {
public static void main(String[] args) {
//creating instance of Account class Account acc=new Account();
//setting values through setter methods acc.setAcc_no(7560504000L);
acc.setName("Sonoo Jaiswal");
acc.setEmail("sonoojaiswal@lidihuo.com");
acc.setAmount(500000f);
//getting values through getter methods System.out.println(acc.getAcc_no()+" "+acc.getName()+" "+acc.getEmail()+" "+acc.getAmount());
}
}
7560504000 Sonoo Jaiswal sonoojaiswal@lidihuo.com 500000.0