08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class.

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

Based on Java Software Development, 5th Ed. By Lewis &Loftus
09 Inheritance. 2 Contents Defining Inheritance Relationships of Inheritance Rules of Inheritance super and this references super() and this() methods.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Object-Oriented PHP (1)
Road Map Introduction to object oriented programming. Classes
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
CS 2511 Fall  Abstraction Abstract class Interfaces  Encapsulation Access Specifiers Data Hiding  Inheritance  Polymorphism.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Writing Classes (Chapter 4)
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and.
The Java Programming Language
CSCI-383 Object-Oriented Programming & Design Lecture 13.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
JAVA BASICS Prepared by The Smartpath Information Systems
Tuc Goodwin  Object and Component-Oriented Programming  Classes in C#  Scope and Accessibility  Methods and Properties  Nested.
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
SMIE-121 Software Design II School of Mobile Information Engineering, Sun Yat-sen University Lecture.
JAVA Classes Review. Definitions Class – a description of the attributes and behavior of a set of computational objects Constructor – a method that is.
CSSE501 Object-Oriented Development. Chapter 4: Classes and Methods  Chapters 4 and 5 present two sides of OOP: Chapter 4 discusses the static, compile.
Java The Java programming language was created by Sun Microsystems, Inc. It was introduced in 1995 and it's popularity has grown quickly since A programming.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Programming in Java CSCI-2220 Object Oriented Programming.
Chapter 8 Objects and Classes Object Oriented programming Instructor: Dr. Essam H. Houssein.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
IT108 Objects and Classes Part I George Mason University Revised 4/3/2012.
Introduction to Object-Oriented Programming Lesson 2.
Access Modifiers Control which classes use a feature Only class-level variables may be controlled by access modifiers Modifiers 1. public 2. protected.
Classes, Interfaces and Packages
Access Specifier. Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Object Oriented Programming. OOP  The fundamental idea behind object-oriented programming is:  The real world consists of objects. Computer programs.
CS 116 Lecture 1 John Korah Contains content provided by George Koutsogiannakis & Matt Bauer.
YG - CS Concept of Encapsulation What is encapsulation? - data and functions/methods are packaged together in the class normally.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
Topics Instance variables, set and get methods Encapsulation
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
Comp1004: Building Better Objects II Encapsulation and Constructors.
Lecture 9: Object and Classes Michael Hsu CSULA. 2 OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object.
JAVA ACCESS MODIFIERS. Access Modifiers Access modifiers control which classes may use a feature. A classes features are: - The class itself - Its member.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Chapter 11: Abstract Data Types Lecture # 17. Chapter 11 Topics The Concept of Abstraction Advantages of Abstract Data Types Design Issues for Abstract.
Table of Contents Class Objects.
Chapter 3: Using Methods, Classes, and Objects
ATS Application Programming: Java Programming
HIGHLEVEL REVIEW Chapter 9 Objects and Classes
Encapsulation & Abstraction
Outline Writing Classes Copyright © 2012 Pearson Education, Inc.
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Object-Oriented Programming
Final and Abstract Classes
Chapter 7 Objects and Classes
CSG2H3 Object Oriented Programming
Presentation transcript:

08 Encapsulation and Abstraction

2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class Class Members Class Modifiers Member Modifiers Accessibility Scope Defining Encapsulation Principles of Encapsulation Encapsulating a Class Setters & Getters Constructors

3 Objectives Define abstraction Identify levels of abstraction Understand that a class is a form of abstraction Define a Java class Learn how to create objects by instantiating their class Identify class members Identify and define each modifier applicable to a class Identify and define each modifier applicable to class members Define access scope for class and its members Know the purpose of constructors and how to create one for a class

4 Objectives (continued) Define encapsulation Describe the principles of encapsulation Learn how to encapsulate a class Learn how to use setters and getters

5 Defining Abstraction Abstraction is the process of extracting common features from specific examples Abstraction is a process of defining the essential concepts while ignoring the inessential details

6 Different Types of Abstraction Data Abstraction Programming languages define constructs to simplify the way information is presented to the programmer. Functional Abstraction Programming languages have constructs that ‘gift wrap’ very complex and low level instructions into instructions that are much more readable. Object Abstraction OOP languages take the concept even further and abstract programming constructs as objects.

7 Anything that you can describe can be represented as an object, and that representation can be created, manipulated and destroyed to represent how you use the real object that it models. Everything is an Object

8 An object is a self-contained entity with attributes and behaviors Defining an Object information an object must know:  identity – uniqueness  attributes – structure  state – current condition behavior an object must do:  methods – what it can do  events – what it responds to

9 Class as Abstraction A class is an abstraction of its instances. It defines all the attributes and methods that its instances must also have. Person name sex age tellSex() tellAge()

10 A Class acts as the template from which an instance of an object is created. The class defines the properties of the object and the methods used to control the object's behavior. A Class specifies the structure of data as well as the methods which manipulate that data. Such data and methods are contained in each instance of the class. A Class is a model or template that can be instantiated to create objects with a common definition, and therefore common properties, operations and behavior. A Class provides a template for defining the behavior of a particular type of object. Objects are referred to as “instances” of a class. Defining a Class

11 Defining a Java Class A Java Class denotes a category of objects, and acts as a blueprint for creating such objects. It defines its members referred to as fields and methods. The fields (also known as variables or attributes) refer to the properties of the class. The methods (also known as operations) refer to behaviors that the class exhibits. class Person { String name; char sex; int age; void tellSex() { if (sex=='M') System.out.println("I'm Male."); else if (sex=='F') System.out.println("I'm Female."); else System.out.println("I don't know!"); } void tellAge() { if (age<10) System.out.println("I'm just a kid."); else if (age<20) System.out.println("I'm a teenager."); else System.out.println("I'm a grown up."); }

12 Class Members A class member refers to one of the fields or methods of a class. Static members are variables and methods belonging to a class where only a single copy of variables and methods are shared by each object. Instance members are variables and methods belonging to objects where a copy of each variable and method is created for each object instantiated. class Person { static int maleCount; static int femaleCount; String name; char sex; int age; static void showSexDistribution() { if (maleCount>femaleCount) System.out.println("Majority are male."); else if (femaleCount>maleCount) System.out.println("Majority are female."); else System.out.println("Equal number of male and female."); } void tellSex() { if (sex=='M') System.out.println("I'm Male."); else if (sex=='F') System.out.println("I'm Female."); else System.out.println("I don't know!"); } void tellAge() { if (age<10) System.out.println("I'm just a kid."); else if (age<20) System.out.println("I'm a teenager."); else System.out.println("I'm a grown up."); }

13 class Person { static int maleCount; static int femaleCount; String name; char sex; int age; static void showSexDistribution() { // method body here } void tellSex() { // method body here } void tellAge() { // method body here } Instantiating a Class & Accessing its Members Access class variables by setting their values Instantiating a class means creating objects of its own type. The new operator is used to instantiate a class. class MainProgram { public static void main(String[] args) { // instantiating several objects Person p1 = new Person(); Person p2 = new Person(); Person p3 = new Person(); // accessing instance variables p1.name = "Vincent"; p1.sex = 'M'; p1.age = 8; p2.name = "Janice"; p2.sex = 'F'; p2.age = 19; p3.name = "Ricky"; p3.sex = 'M'; p3.age = 34; // accessing static variables Person.maleCount = 2; Person.femaleCount = 1; // accesssing instance methods p1.tellSex(); p1.tellAge(); p2.tellSex(); p2.tellAge(); p3.tellSex(); p3.tellAge(); // accessing static method Person.showSexDistribution(); } Access class methods by invoking their names Create Person objects using the new operator. Sample Output: I'm Male. I'm just a kid. I'm Female. I'm a teenager. I'm Male. I'm a grown up. Majority are male.

14 Class Modifiers ModifierDescription (no modifier)class is accessible within its package only public class is accessible by any class in any package abstract class cannot be instantiated (a class cannot be abstract and final at the same time) final class cannot be extended strictfp class implements strict floating-point arithmetic Class modifiers change the way a class can be used. Access modifiers describe how a class can be accessed. Non-access modifiers describe how a class can be manipulated.

15 Access Modifiers ModifierDescription (no modifier)member is accessible within its package only public member is accessible from any class of any package protected member is accessible in its class package and by its subclasses private member is accessible only from its class Member modifiers change the way class members can be used Access modifiers describe how a member can be accessed

16 Sample Package Class Private features of the Sample class can only be accessed from within the class itself. private Classes that are in the package and all its subclasses may access protected features of the Sample class. protected Only classes that are in the package may access default features of classes that are in the package default All classes may access public features of the Sample class. public Class * Default is not a modifier; it is just the name of the access level if no access modifier is specified. Access Modifiers

17 Member Modifiers Member modifiers change the way class members can be used Non-access modifiers describe how a member can be manipulated ModifierDescription static member belongs to a class final declares a constant variable or method abstract method is declared with no implementation (applied to methods, cannot be combined with other non-access modifiers ) strictfp method implements strict floating-point arithmetic (applied to methods) synchronized method is executed by only one thread at a time (applied only to methods) native method implementation is written in other language (applied only to methods) transient an instance variable is not saved when its object is persisted or serialized (applied only to variables) volatile variable is modified asynchronously by concurrently running threads (applied only to variables)

18 Accessibility Scope ScopeAccess staticstatic code can access static members but not instance members non-staticnon-static code can access both static members and instance members packagea class and its members can be accessed within the package they are declared classclass members can be accessed within the class blocklocal variables can be accessed only within a block Accessibility scope defines the boundary of access to a class and its members

19 Defining Encapsulation Encapsulation is the process of hiding an object’s implementation from another object, while presenting only the interfaces that should be visible.

20 Principles of Encapsulation “Don’t ask how I do it, but this is what I can do” - The encapsulated object “I don’t care how, just do your job, and I’ll do mine” - One encapsulated object to another

21 Encapsulating a Class Members of a class must always be declared with the minimum level of visibility. Provide setters and getters (also known as accessors/mutators) to allow controlled access to private data. Provide other public methods (known as interfaces ) that other objects must adhere to in order to interact with the object.

22 Setters and Getters private char sex; public void setSex(char s) { // validate here sex = s; } public char getSex() { // format here return sex; } Setters and Getters allow controlled access to class data Setters are methods that (only) alter the state of an object Use setters to validate data before changing the object state Getters are methods that (only) return information about the state of an object Use getters to format data before returning the object’s state

23 Encapsulation Example public static void main(String[] args) { // instantiate several objects Person p1 = new Person(); Person p2 = new Person(); Person p3 = new Person(); // access instance variables using setters p1.setName("Vincent"); p1.setSex('M'); p1.setAge(8); p2.setName("Janice"); p2.setSex('F'); p1.setAge(19); p3.setName("Ricky"); p3.setSex('M'); p3.setAge(34); // access static variables directly Person.maleCount=2; Person.femaleCount=1; // access instance methods p1.tellSex(); p1.tellAge(); p2.tellSex(); p2.tellAge(); p3.tellSex(); p3.tellAge(); // access static method Person.showSexDistribution(); } class Person { // set variables to private private static int maleCount; private static int femaleCount; private String name; private char sex; private int age; /* * setters & getters, set to public */ public int getAge() { return age;} public void setAge(int a) { age = a;} public String getName() { return name;} public void setName(String n) { name = n;} public char getSex() { return sex;} public void setSex(char s) { sex = s;} /* * set other methods as interfaces */ public static void showSexDistribution() { // implementation here } public void tellSex() { // implementation here } public void tellAge() { // implementation here } I'm Male. I'm just a kid. I'm Female. I'm a teenager. I'm Male. I'm a grown up. Majority are male.

24 Constructors Constructors are methods which set the initial state of an object Constructors are called when an object is created using the new operator A default constructor is a constructor with no parameters, it initializes the instance variables to default values Restrictions on constructors constructor name must be the same as the class name constructor cannot return a value, not even void only an access modifier is allowed

25 Key Points Abstraction is the process of formulating general concepts by extracting common properties of instances. A class is an abstraction of its instances. A Java Class denotes a category of objects. Class members refer to its fields and methods. Static members are variables and methods belonging to a class. Instance members are variables and methods belonging to objects. Instantiating a class means creating objects of its own type. Class modifiers include: (no modifier), public, abstract, final and strictfp. Member modifiers include: (no modifier), public, protected, private, static, final, abstract, strictfp, synchronized, native, transient and volatile.

26 Key Points (Continued) Encapsulation hides implementation details of a class. Encapsulating a class means declaring members with minimum level of visibility. Setters are methods whose only function is to alter the state of an object in a controlled manner. Getters are methods which only function is to return information about the state of an object. Constructors are methods which set the initial state of an object upon creation of the object.