Encapsulation Exercise -1

1. Write a Java program to create a class called Person with private instance variables name, age. and country. Provide public getter and setter methods to access and modify these variables.

Solution:

class Person{
    private String name,country;
    private int age;

    //setter for name
    public void setName(String name){
        this.name=name;
    }
    //getter for name
    public String getName(){
        return name;
    }

    //setter for age
    public void setAge(int age){
        this.age=age;
    }
    //getter for age
    public int getAge(){
        return age;
    }

    //setter for country
    public void setCountry(String country){
        this.country=country;
    }
    //getter for country
    public String getCountry(){
        return country;
    }

}

public class Program
{
    public static void main(String[] args) {

        Person p1=new Person();
        p1.setName("Kailash Singh");
        p1.setAge(20);
        p1.setCountry("India");

        System.out.println("Name: "+p1.getName());
        System.out.println("Age: "+p1.getAge());
        System.out.println("Country: "+p1.getCountry());
		
	}
}

Leave a Comment