1.25k likes | 2.34k Views
Concept of Encapsulation. What is encapsulation? - data and functions/methods are packaged together in the class normally with the same scope of the accessibility in the memory Why encapsulation
E N D
Concept of Encapsulation • What is encapsulation? - data and functions/methods are packaged together in the class normally with the same scope of the accessibility in the memory • Why encapsulation - Objects no longer need to be dependent upon any “outside” functions and data after the creation - Provide ADT (Abstract Data Types) - Easier in coding - Promote standards in OOP YG - CS170
Classes vs. Objects • Class is a data structure that encapsulates data and functions. • Data in a class are called member data, class variables, instance variables, or fields. • Functions in a class are called member functions or methods. Constructors are special methods. • Objects are the instance of a class. Creation of the objects and instantiation of the objects are all referring to memory allocation to hold the data and methods of the objects. In Java, all objects are created dynamically using new operator. For example: ClassName ObjName = new ClassName(); YG - CS170
Characteristics of Constructors • A special method that has the same name of the class without return type, not even void. • Constructor will be automatically called whenever an object is created. • Like a method, constructor can be overloaded for the flexibility of the object creation. • A super class constructor can be called by a sub class object as: super(); YG - CS170
get methods • In OOP, particularly in Java, get() means to return one of object’s member data • get() usually has a return type and takes no argument • Use meaningful name for a get() method YG - CS170
set methods • In OOP, particularly in Java, set() means to set object’s member data • set() usually has void return and takes argument(s) to set the member data • set() also checks the validity of the data before it sets • Use meaningful name for a set() method YG - CS170