Encapsulation and Constructors

Slides:



Advertisements
Similar presentations
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Advertisements

H OW O BJECTS B EHAVE. O VERVIEW Methods use object state Arguments and return types in methods Java passes by value Getters and Setters Encapsulation.
Road Map Introduction to object oriented programming. Classes
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
ECE122 L6: Problem Definition and Implementation February 15, 2007 ECE 122 Engineering Problem Solving with Java Lecture 6 Problem Definition and Implementation.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
1 Fall 2007ACS-1903 Chapter 6: Classes Classes and Objects Instance Fields and Methods Constructors Overloading of Methods and Constructors Scope of Instance.
Encapsulation CMSC 202. Types of Programmers Class programmers – Developers of new classes – Goal: Expose the minimum interface necessary to use a new.
Classes and Class Members Chapter 3. 3 Public Interface Contract between class and its clients to fulfill certain responsibilities The client is an object.
Writing Classes (Chapter 4)
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Mason Vail.  A data type definition – “blueprint for objects”  Includes properties and/or methods ◦ “instance” data / methods – specific to one object.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
RECITATION 4. Classes public class Student { } Data Members public class Student { private String name; public String id; }
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
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.
08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
OOP with Java, David J. Barnes/Eric Jul Defining Classes1 Object State and Complexity Objects maintain a state. State is represented by a set of attributes.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Objects and Classes.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
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.
Classes - Intermediate
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.
Comp1004: Programming in Java I Variables - Primitives, Objects and Scope.
OOP Basics Classes & Methods (c) IDMS/SQL News
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
Comp1004: Building Better Objects II Encapsulation and Constructors.
COMP Information Hiding and Encapsulation Yi Hong June 03, 2015.
Comp1004: Environments The Java Library. Coming up Recap – Encapsulation – Constructors – Loops – Arrays – ArrayList – Iterators The Java Library – Implementation.
Basic Class Structure. Class vs. Object class - a template for building an object –defines the instance data that the object will hold –defines instance.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Java 5 Class Anatomy. User Defined Classes To this point we’ve been using classes that have been defined in the Java standard class library. Creating.
Comp1004: Building Better Objects I Methods. Coming up Methods and Parameters – Why Parameterise? – Call by value, call by reference Return Types – Methods.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
Objects as a programming concept
Classes and OOP.
Creating Your OwnClasses
Lecture 9 Concepts of Programming Languages
Defining Your Own Classes Part 1
Classes and Objects Encapsulation
COMP 110 Information hiding and encapsulation
Corresponds with Chapter 7
Ch 4: Writing Classes Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: Classes and Objects.
Chapter 4: Writing classes
Outline Writing Classes Copyright © 2012 Pearson Education, Inc.
Chapter 9 Objects and Classes
Dr. Bhargavi Dept of CS CHRIST
Announcements Program 2 is due tomorrow by noon Lab 4 was due today
CS100J Lecture 7 Previous Lecture This Lecture Java Constructs
Outline Anatomy of a Class Encapsulation Anatomy of a Method
COP 3330 Object-oriented Programming in C++
Object-Oriented Programming
Chapter 9 Objects and Classes
OO Programming Concepts
Classes and Objects CGS3416 Spring 2019.
Object-Oriented Design AND CLASS PROPERTIES
ITE “A” GROUP 2 ENCAPSULATION.
Object-Oriented Design AND CLASS PROPERTIES
Chapter 7 Objects and Classes
CSG2H3 Object Oriented Programming
Lecture 9 Concepts of Programming Languages
Object-Oriented Design AND CLASS PROPERTIES
Presentation transcript:

Encapsulation and Constructors Comp1202 Encapsulation and Constructors

Coming up Recap Accessor Methods Encapsulation Constructors Variables, Scope and Methods Accessor Methods Getters and Setters Encapsulation public and private Constructors

Recap

Scope public class Account{ int balance = 100; public void withdrawFiver(){ balance = balance -5; } public void withdrawTenner(){ int tenner = 10; balance = balance – tenner; Member variables are visible in all the methods of a class. They are created when an object is created, and destroyed when the object is garbage collected

Scope public class Account{ int balance = 100; public void withdrawFiver(){ balance = balance -5; } public void withdrawTenner(){ int tenner = 10; balance = balance – tenner; Member variables are visible in all the methods of a class. They are created when an object is created, and destroyed when the object is garbage collected Local variables are only visible in the method in which they are declared. They are created when the method is invoked, and destroyed when it ends.

Primitives vs. References Objects Defined? defined in Java defined in Classes Stored? stored directly in variables a reference is stored in the variable Passed? Pass by copy Pass by reference a int int a; a = 10; Elephant b; b = new Elephant(); 10 b Elephant

Methods and Parameters public class Account{ int balance = 100; public static void main(String[] args){ Account myAccountObject = new Account(); myAccountObject.withdraw(5); myAccountObject.withdraw(10); } public void withdraw(int amount){ balance = balance - amount; Values passed into a method are called arguments Values received by a method are called parameters. Within the method they can be used like any other local variable

Methods and Parameters public class Account{ int balance = 100; int overdraft = 100; public static void main(String[] args){ Account myAccountObject = new Account(); myAccountObject.withdraw(5); int funds = getAvailableFunds(); System.out.println(funds); } public void withdraw(int amount){ balance = balance - amount; public int getAvailableFunds(){ return balance + overdraft; You can use a return type to return a single value from a method

Overloading Methods can take multiple parameters public class Account{ int balance = 100; public static void main(String[] args){ Account myAccountObject = new Account(); myAccountObject.withdraw(5); myAccountObject.withdraw(10, "ATM"); } public void withdraw(int amount){ balance = balance - amount; public void withdraw(int amount, String desc){ System.out.print(“Withdrew £”); System.out.print(amount); System.out.print(“ via ”); System.out.println(desc); Methods can take multiple parameters Several Methods can have the same name as long as their signatures (types and order of parameters) are different.

Accessor Methods and Encapsulation

Getters and Setters Programming convention Puts a method between users of an object and the data inside the object int a = student.age; int a = student.getAge(); student.age = 20; student.setAge(20);

aka These are more formally known as Accessors and Mutators. You’ll find them a lot The library classes that Java provides follow this convention often.

But Why Do It? What reason is there to write this extra code, when you can use the class variables directly? public int getAge(){ return age; }

Encapsulation This is the idea that a class should be responsible for managing itself And should present a clean interface (set of methods) to the outside world An interface that does not reveal the inner workings of the class

Encapsulation This is the idea that a class should be responsible for managing itself And should present a clean interface (set of methods) to the outside world An interface that does not reveal the inner workings of the class This means that you can change the way that the class works, without changing any other parts of the program Results in cleaner, more portable code, that is more maintainable and reusable.

For example Take this example class where age is modelled as an int public class Student { int age = 20; //code omitted public static void main(String[] args){ Student s1 = new Student(); System.out.println(s1.getAge()); } public int getAge(){ return age; Take this example class where age is modelled as an int

For example Take this example class where age is modelled as an int public class Student { //int age = 20; Calendar dateOfBirth; //code omitted public static void main(String[] args){ Student s1 = new Student(); System.out.println(s1.getAge()); } //public int getAge(){ // return age; //} public int getAge(){ Calendar rightNow = Calendar.getInstance(); int a = calculateAge(rightNow, dateofBirth); return a; Take this example class where age is modelled as an int We might change the way that age is implemented – e.g. to make it based on the current date. Because we used an Accessor we do not need to alter main

Enforcing Good Behaviour So we have used methods to hide the way that our class is implemented But what happens if we forgot and accidently access the variable directly? Or if someone else uses our class in their program and ignores the accessor methods?

Private public class Student { //int age = 20; private Calendar dateOfBirth; //code omitted public static void main(String[] args){ Student s1 = new Student(); System.out.println(s1.getAge()); } //public int getAge(){ // return age; //} public int getAge(){ Calendar rightNow = Calendar.getInstance(); int a = calculateAge(rightNow, dateOfBirth); return a; The private keyword tells Java that only methods in this class can access this variable.

Private public class Student { //int age = 20; private Calendar dateOfBirth; //code omitted public static void main(String[] args){ Student s1 = new Student(); System.out.println(s1.getAge()); } //public int getAge(){ // return age; //} public int getAge(){ Calendar rightNow = Calendar.getInstance(); int a = calculateAge(rightNow, dateofBirth); return a; The private keyword tells Java that only methods in this class can access this variable. And yes, public means the opposite – that all other methods can access it!

Encapsulation (Summary) The idea that classes look after themselves and hide their internal workings Is a key concept in Object Oriented Programming And is enforced using the public or private keywords* Which can be applied to both member variables and methods *There is also a protected keyword (we come to that later!)

A Hint Good OO programmers are paranoid If you want to make good encapsulated classes treat everything as private Only open up methods or member variables as public if you really want them to be accessed outside of the class.

Constructors

Back at our simple Student Example public class Student { private int age = 20; //code omitted public static void main(String[] args){ Student s1 = new Student(); System.out.println(s1.getAge()); } public int getAge(){ return age; We have a problem – all our students will be age 20

Back at our simple Student Example public class Student { private int age = 20; //code omitted public static void main(String[] args){ Student s1 = new Student(); s1.setAge(19); System.out.println(s1.getAge()); } public int getAge(){ return age; public void setAge(int a){ age = a; We have a problem – all our students will be age 20 One solution is to use a Setter method. But Is this good encapsulation?

Back at our simple Student Example public class Student { private int age = 20; //code omitted public static void main(String[] args){ Student s1 = new Student(); s1.setAge(19); System.out.println(s1.getAge()); } public int getAge(){ return age; public void setAge(int a){ age = a; We have a problem – all our students will be age 20 One solution is to use a Setter method. But Is this good encapsulation? No – object creation is in two steps. Someone could forget to set it before using the object. We need a way to force a program to set the age at the point of object creation

Constructors Look a bit like methods Contain code that is called during the creation of objects Is used to initialise objects and set critical member variables This maintains Encapsulation

Constructors Constructor Rules: Must have the same name as the class public class Student { private int age; public Student() { age = 20; } //code omitted Constructor Rules: Must have the same name as the class Do not need a return type

Constructors Constructor Rules: Must have the same name as the class public class Student { private int age; public Student() { age = 20; } public Student(int a) { age = a; //code omitted Constructor Rules: Must have the same name as the class Does not need a return type Can take parameters Can be overloaded

Constructors Constructor Rules: Must have the same name as the class public class Student { private age; public Student() { age = 20; } public Student(int a) { age = a; public static void main(String[] args){ Student s1 = new Student(19); System.out.println(s1.getAge()); //code omitted Constructor Rules: Must have the same name as the class Does not need a return type Can take parameters Can be overloaded Are invoked at the point of creation using the new keyword

The Default Constructor What happens if you do not declare a constructor? In these cases Java creates an invisible default constructor for you The default constructor takes no parameters and contains no behavior. But allows you to create Object instances We’ve been using them from day one Dog d = new Dog();

Summary Recap Accessor Methods Encapsulation Constructors Variables, Scope and Methods Accessor Methods Getters and Setters Encapsulation public and private Constructors