Search code examples
javaencapsulation

Encapsulation and passing primitives to methods


I have questions regarding encapsulation rules and difference between next two classes

class Phone { 
    public String model; 
    double weight; 
    public void setWeight(double w){
        weight = w;
    }
    public double getWeight(){
        return weight;
    }
}

class Home {
    public static void main(String[] args) {
        Phone ph = new Phone();
        ph.setWeight(12.23);
        System.out.println(ph.getWeight());
    }
}

In the book for Java for I OCA certification this is example of well encapsulated class and from set and get method we can access weight variable and pritns 12.23.

but what confused me is next class:

class Employee { 
    int age; 
    void modifyVal(int age) {  // even if parameter is d instead age prints the same
        age = age + 1;        // even if parameter is d instead age prints the same
        System.out.println(age); 
    }
}

class Office {
    public static void main(String args[]) { 
        Employee e = new Employee();
        System.out.println(e.age);
        e.modifyVal(e.age);
        System.out.println(e.age);
    }
}

It print: 010

meaning that method modifyVal cannot access age variable. Can somebody explain why variable havent change after applying the modufyVal method and what is the difference?


Solution

  • It's because of this line:

    age = age + 1; //it's overwriting age parameter and not accessing age instance variable
    

    If it was like that it would modify the age instance variable

    this.age = age + 1;