OOPS In Depth and Fundamentals of Design Patterns
OOPS Intro
As we have seen in our previous blog that is why we need classes. To sum it up again, we need classes and objects to make real-world entities or custom data types. A car class can have a color, model, gear mode, etc. This all belongs to ca...
lovepreet.hashnode.dev5 min read
First of all, thank you for sharing your knowledge with the community. I'm not entirely convinced by the explanation of encapsulation though.
By definition, encapsulation serves to hide implementation details from the outside (e.g. from other client classes). However, in the examples you provide, I don't see the definition being met:
public class Student{ private String name; private int marks; Student(){} Student(String name, int marks){ this.name = name; this.marks = marks; } public int getMarks(){ return this.marks; } public String getName(){ return this.name; } public void setName(String t_name){ this.name = t_name; } public void setMarks(int t_marks){ if(t_marks<=100 && t_marks>=0){ this.marks = t_marks; return; }else{ throw new Exception("Enter marks from 0-100 included"); } } }In this example an implementation detail is being exposed, the actual types of the private fields. This breaks encapsulation, why? Let's imagine that tomorrow we decide that the type of the field "marks" will no longer be "int", but, "long", so we simply make the change:
public class Student{ private String name; private long marks; Student(){} Student(String name, int marks){ this.name = name; this.marks = marks; } public long getMarks(){ return this.marks; } public String getName(){ return this.name; } public void setName(String t_name){ this.name = t_name; } public void setMarks(long t_marks){ if(t_marks<=100 && t_marks>=0){ this.marks = t_marks; return; }else{ throw new Exception("Enter marks from 0-100 included"); } } }And this is just an example, of course, Java compilers can perform an implicit conversion from "int" to "long" but when working with complex types, the issue changes and can be more critical.