How to implement fundamental OOPs concept (Encapsulation) in java???


                                           Encapsulation is wrapping up of data and member functions into a single unit🎁. The single unit is defined as a class.  

  • ·       Create a class “Customer”.
  • ·       Add two members as private. One is name. another one is id.
  • ·       Write four member functions. Two for getting name,id. Two for setting the name and id.
  • ·       Create a main class as”Main9” and save this class as “Main9.java”
  • ·       Define a public static void main() with String[] Args.
  • ·       Create an object for Customer class.
  • ·       Call the set functions to set the value.
  • ·       Using print statements, print the details using get functions.

//Java Program to implement Encapsulation.

class Customer {

    private String name;

    private int id;

    //Get method for name

    public String getName() {

        return name;

    }

    // Set method for name

    public void setName(String name) {

        this.name = name;

    }

    // Get method for Id

    public int getId() {

        return id;

    }

     // Set method for Id

    public void setId(int Id) {

        this.id = Id;

    }

}

public class Main9 {

    public static void main(String[] args) {

        Customer cust = new Customer();

        cust.setName("Jeevan");

        cust.setId(1);

        System.out.println("Name: " + cust.getName());

        System.out.println("Age: " + cust.getId());

    }

}

Open an command prompt.

Set the path.

Compile the program.

C:\raji\blog>javac Main9.java

Run the program.

C:\raji\blog>java Main9

Name: Jeevan

Age: 1

This is way of implementing Encapsulation in java. 

No comments:

Post a Comment