




























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An in-depth explanation of encapsulation in object-oriented programming (oop) using java. It covers the relationship between classes and objects, the concept of encapsulation, and the use of access modifiers to control access to class variables and methods. Examples and code snippets to illustrate the concepts.
Typology: Lecture notes
1 / 36
This page cannot be seen from the preview
Don't miss anything!





























Classes
Classes
Classes
Classes and Objects s1:String "Programming" s2:String "Java" s3:String "ive-ty" String (class)
class TestStringClass { public static void main(String s[]) { String s1 = new String("Programming"); String s2 = new String("Java"); String s3 = new String("ive-ty"); System.out.println(s1.toUpperCase()); System.out.println(s2.toUpperCase()); System.out.println(s3.toUpperCase()); } } Classes and Objects In this example, String is class. s1, s2 and s3 are the objects (or references to objects, precisely speaking). Each of them has different state but same behavior.
Example
Example
Example Employee emp1 = new Employee(); Employee emp2 = new Employee(); Memory emp num : 0 getNum setNum emp num : 0 getNum setNum emp num : 0 getNum setNum
Example emp1.setNum(12651); emp2.setNum(36595); emp1.getNum() returns 12651 emp2.getNum() returns 36595
Memory emp num : 12651 getNum setNum emp num : 12651 getNum setNum emp num : 36595 getNum setNum emp num : 0 getNum setNum
Encapsulation
Encapsulation
A BAD Example class PublicDataEmployee { public int num; } class PrintPublic { public static void main(String[] args) { PublicDataEmployee emp1 = new PublicDataEmployee(); PublicDataEmployee emp2 = new PublicDataEmployee(); emp1.num = 12651; emp2.num = 36595; System.out.println("num of emp1 : " + emp1.num ); System.out.println("num of emp2 : " + emp2.num ); } }
java PrintPublic num of emp1 : 12651 num of emp2 : 36595
A GOOD Example class PrivateDataEmployee { private int num; public int getNum() {return num;} public void setNum(int newNum) {num=newNum;} } class PrintPrivate { public static void main(String[] args) { PrivateDataEmployee emp1 = new PrivateDataEmployee(); PrivateDataEmployee emp2 = new PrivateDataEmployee(); emp1.setNum(12651); emp2.setNum(36595); System.out.println("num of emp1 : " + emp1.getNum() ); System.out.println("num of emp2 : " + emp2.getNum() ); } }
java PrintPrivate num of emp1 : 12651 Num of emp2 : 36595