Java Encapsulation Concept not clear

后端 未结 12 2349
死守一世寂寞
死守一世寂寞 2020-11-30 03:40

This is basic question but still i don\'t understand encapsulation concept . I did\'t understand how can we change the properties of class from other class.because whenever

相关标签:
12条回答
  • 2020-11-30 03:43

    public static field's are associated with class not with object, it break Object's encapsulation rule.

    Employee class with two encapsulated field empid & empname.

    public class Employee {
        private int empid;
        private String empname;
    
        public int getEmpid(){
            return this.empid;
        } 
        public void setEmpid(int empid){
            this.empid = empid;
        }
        ...
    }
    
    public class EmployeeTest {
          public static void main(String[] args) {
                Employee e = new Employee();
                e.setempId(1);
                Employee e1 = new Employee();
                e1.setempId(2);
          }
    }
    

    Documentation for better understanding on encapsulation

    0 讨论(0)
  • 2020-11-30 03:44

    It seems you are running two different classes separately and assuming the changes done to attributes when you run EmployeeTest will reflect in Employee run. Note that changes will reflect in the same JRE instance. Excuse me in case i have misunderstood your problem.

    EDIT: As per the user input. Here is the code how you can access and update the static member values:

    class Employee {
        public static int empid;
        public static String empname;
    
        public static void main(String[] args) {
            System.out.println("print employe details:" + empid + " " + empname);
        }
    }
    
    // EmployeeTest class
    public class EmployeeTest {
    
        public static void main(String[] args) {
            Employee e = new Employee();
            e.empid = 20;
            e.empname = "jerry";
            Employee.empid = 10;
            Employee.empname = "tom";
            Employee.main(null);
        }
    
    }
    
    0 讨论(0)
  • 2020-11-30 03:55

    The concept of encapsulation is a design technique that relates with information hiding. The underlying principle is to provide protected access to the class attributes, through a well designed interface. The purpose of encapsulation is to enforce the invariants of the class.

    To follow on your example consider the interface of this class:

    class Employee
    
      private final String firstName;
      private final String lastName;    
    
      public Employee(final firstName, final lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
      }
    
      public String getName() {
        return firstName + " " + lastName;
      }
    }
    

    Note that by declaring the attributes as private this class restricts clients from directly accessing the state of employee object instances. The only way for clients to access them is via the getName() method. This means that those attributes are encapsulated by the class. Also note that by declaring the attributes as final and initializing them in the constructor we create an effectively immutable class, that is one whose state cannot be modified after construction.

    An alternative implementation would be the following:

    class Employee
    
      private String firstName;
      private String lastName;    
    
      public Employee(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
      }
    
      public String getName() {
        return firstName + " " + lastName;
      }
    
      public String setName(String firstName, String lastName) {
    
        if (firstName == null) {
          throw new IllegalArgumentException("First name cannot be null");
        }
    
        if (lastName == null) {
          throw new IllegalArgumentException("Last name cannot be null");
        }
    
        this.firstName = firstName;
        this.lastName = lastName;
      }
    }
    

    In this example the object is not immutable but its state is encapsulated since access to it takes place only through accessors and modifiers. Note here how encapsulation can help you protect the invariants of the object state. By constraining modifications through a method you gain a better control of how the object state is modified, adding validations to make sure that any modifications are consistent with the specification of the class.

    0 讨论(0)
  • 2020-11-30 03:55

    The encapsulation is an OOP concept. The class is considered like a capsule that contains data + behavior. The data should be private and should be accessed only using public methods called getters and setters. You may check this encapsulation tutorial for more informations about this concept.

    0 讨论(0)
  • 2020-11-30 03:56

    encapsulation =VARIABLES(let private a,b,c)+ METHODS(setA&getA,setB&getB....) we can encapsulate by using the private modifier. let consider your created one public variable and one private variable in your class... in case if you have to give those variables to another class for read-only(only they can see and use not able to modify) there is no possibility with public variables or methods,but we can able to do that in private by providing get method. so Your class private variables or methods are under your control. but IN public there is no chance....i think you can understood.

    0 讨论(0)
  • 2020-11-30 04:00

    Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface.

    Encapsulation in Java is the technique of making the fields in a class private and providing access to the fields via public methods.

    If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.

    Real-time example: cars and owners. All the functions of cars are encapsulated with the owners. Hence, No one else can access it..

    The below is the code for this example.

    public class Main {
    
      public static void main(String[] args) {
        Owner o1=new Car("SONY","Google Maps");
        o1.activate_Sunroof();
        o1.getNavigationSystem();
        o1.getRadioSytem();
     }
    }  
    //Interface designed for exposing car functionalities that an owner can use.
    public interface Owner {
         void getNavigationSystem();
         void getRadioSytem();
         void activate_Sunroof();
    }
    /*
    Car class protects the code and data access from outside world access by implementing Owner interface(i.e, exposing Cars functionalities) and restricting data access via private access modifier.
    */
    public class Car implements Owner {
                    private String radioSystem;
                    private String gps;
    
                    public Car(String radioSystem, String gps) {
                        super();
                        this.radioSystem = radioSystem;
                        this.gps = gps;
                    }
    
                    public String getRadioSystem() {
                        return radioSystem;
                    }
    
                    public void setRadioSystem(String radioSystem) {
                        this.radioSystem = radioSystem;
                    }
    
                    public String getGps() {
                        return gps;
                    }
    
                    public void setGps(String gps) {
                        this.gps = gps;
                    }
    
                    @Override
                    public void getNavigationSystem() {
                        System.out.println("GPS system " + getGps() + " is in use...");
                    }
    
                    @Override
                    public void getRadioSytem() {
                        System.out.println("Radio system " + getRadioSystem() + " activated");
                    }
    
                    @Override
                    public void activate_Sunroof() {
                        System.out.println("Sunroof activated");
                    }
    }
    
    0 讨论(0)
提交回复
热议问题