package com.revature;
public class Student{
//private data member
private String name;
//getter method for name
public String getName(){
return name;
}
//setter method for name
public void setName(String name){
this.name=name
}
}
//A Java class to test the encapsulated class.
package com.revature;
class Test{
public static void main(String[] args){
//creating instance of the encapsulated class
Student s=new Student();
//setting value in the name member
s.setName("vijay");
//getting value of the name member
System.out.println(s.getName());
}
}
The above is an example of encapsulation of a class called Student that has only one field with its setter and getter methods.
//A Java class which has only getter methods.
public class Student{
//private data member
private String college="AKG";
//getter method for college
public String getCollege(){
return college;
}
}
The above class is an example of a Read-Only class because it has only a getter to access the college name. If the user tries to change the value of the college name, a compile-time error is rendered.
//A Java class which has only setter methods.
public class Student{
//private data member
private String college;
//getter method for college
public void setCollege(String college){
this.college=college;
}
}
The above class is an example of a Write-Only class because it has only setters to change the value of the college name and cannot read the college name. Even if tried to access outside of this class a compile-time error is displayed only because the variable is declared as private.
There are 4 types of java access modifiers:
There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc. Here, we will learn access modifiers.
class A{
protected void msg(){System.out.println("Hello java");}
}
public class Simple extends A{
void msg(){System.out.println("Hello java");} // Error because Class Simple method msg() is more restrictive that Class A method msg()
public static void main(String args[]){
Simple obj=new Simple();
obj.msg();
}
}
If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.
Create an encapsulated class with 4 fields and the respective methods to access and edit those fields. Then go ahead and create a test class to verify.