Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles
Content Classes and Objects How to define classes Reference Type and default value Using classes from the java library Visibility Modifiers Data Field Encapsulation Static variables 2 Fall 2012 CS2302: Programming Principles
3 Classes and Objects A Java program consists of one or more classes A class is an abstract description of objects Here is an example class: – class Dog {...description of a dog goes here... } Here are some objects of that class: Fall 2012 CS2302: Programming Principles
4 More Objects Here is another example of a class: – class Window {... } Here are some examples of Windows: Fall 2012 CS2302: Programming Principles
OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. – A class is a piece of the program’s source code that describes a particular type of objects. – An object is called an instance of a class. A program can create and use more than one object (instance) of the same class. 5 Fall 2012 CS2302: Programming Principles
Class Object A blueprint for objects of a particular type Defines the structure (number, types) of the attributes Defines available behaviors of its objects Attributes Behaviors 6 Fall 2012 CS2302: Programming Principles
Class: Car Object: a car Attributes: String model Color color int numPassengers double amountOfGas Behaviors: Add/remove a passenger Get the tank filled Report when out of gas Attributes: model = "Mustang" color = Color.YELLOW numPassengers = 0 amountOfGas = 16.5 Behaviors: 7 Fall 2012 CS2302: Programming Principles
Class – User-defined data type Object – Instance of class, A role of variable – Define a correspond class to define a object Define a class class [modifier] class ClassName { // field declarations //Constructors // method declarations } Defining Classes for Objects Describe the structure of object Data Field(variable, constant) Define actions of object Method Field public, final, abstract 8 Fall 2012 CS2302: Programming Principles
Constructors Short procedures for creating objects of a class Always have the same name as the class Initialize the object’s fields May take parameters, but no returns A class may have several constructors that differ in the number and/or types of their parameters 9 Fall 2012 CS2302: Programming Principles
Class Example 10 Fall 2012 CS2302: Programming Principles
Object Example 11 Fall 2012 CS2302: Programming Principles
Class vs. Object A piece of the program’s source code Written by a programmer An entity in a running program Created when the program is running (by the main method or a constructor or another method) 12 Fall 2012 CS2302: Programming Principles
Class vs. Object Specifies the structure (the number and types) of its objects’ attributes — the same for all of its objects Specifies the possible behaviors of its objects Holds specific values of attributes; these values can change while the program is running Behaves appropriately when called upon 13 Fall 2012 CS2302: Programming Principles
Diagram of program structure A program consists of one or more classes Typically, each class is in a separate.java file Program File Class Variables Constructors Methods Variables Statements 14 Fall 2012 CS2302: Programming Principles
Object type is a Reference Type Go over the textbook slides from page 29 to Fall 2012 CS2302: Programming Principles
Encapsulation Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance (is the capability of a class to use the properties and methods of another class ), polymorphism ( more than one form ), and abstraction ( simplifying complex reality by modeling classes ). Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface. Encapsulation provides a technique of making the fields in a class private and providing access to the fields via public methods. 16 Fall 2012 CS2302: Programming Principles
The fields of a class can be made read-only or write-only. A class can have total control over what is stored in its fields. The users of a class do not know (like a blackbox) how the class stores its data. A class can change the data type of a field, and users of the class do not need to change any of their code. The fields of a class can be made read-only or write-only. A class can have total control over what is stored in its fields. The users of a class do not know (like a blackbox) how the class stores its data. A class can change the data type of a field, and users of the class do not need to change any of their code. Benefits of Encapsulation 17 Fall 2012 CS2302: Programming Principles
Encapsulation Implementation If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding. A class interacts with other classes only through constructors and public methods Other classes do not need to know the mechanics (implementation details) of a class to use it effectively 18 Fall 2012 CS2302: Programming Principles example of Encapsulation
Visibility Modifiers We accomplish encapsulation through the appropriate use of visibility modifiers Visibility modifiers specify which parts of the program may see and use any particular class/method/field A modifier is a Java reserved word that specifies particular characteristics of a programming construct We've used the modifier final to define a constant Java has three visibility modifiers : public, private, and protected We will discuss the protected modifier later in the course 19 Fall 2012 CS2302: Programming Principles
Visibility Modifiers - Classes A class can be defined either with the public modifier or without a visibility modifier. If a class is declared as public it can be used by any other class If a class is declared without a visibility modifier it has a default visibility. The default modifier restricts access to the same package. Classes that define a new type of objects, that are supposed to be used anywhere, should be declared public. 20 Fall 2012 CS2302: Programming Principles
Visibility Modifiers - Members A member is a field, a method or a constructor of the class. Members of a class can be declared as private, protected, public or without a visibility modifier: private int hours; int hours; public int hours; 21 Fall 2012 CS2302: Programming Principles
Public Visibility Members that are declared as public can be accessed from any class that can access the class of the member Example: the methods getHours(), secondElapsed() and setTime() are part of the interface of class Clock so we define them as public. We do not want to reveal the internal representation of the object’s data. So we usually declare its state variables as private (encapsulation). 22 Fall 2012 CS2302: Programming Principles
Private Visibility A class member that is declared as private, can be accessed only by code that is within the class of this member. We hide the internal implementation of the class by declaring its state variables and auxiliary methods as private. Data hiding is essential for encapsulation. 23 Fall 2012 CS2302: Programming Principles
Illegal Access - example // Example of illegal access class BankAccountTest { public static void main(String[] args) { BankAccount victim = new BankAccount( ); victim.balance = victim.balance - 500; // this will not compile! } public class BankAccount { private long accountNumber; private double balance; // … 24 Fall 2012 CS2302: Programming Principles
Encapsulation - example public void transfer(double amount, BankAccount targetAccount) { withdraw(amount); targetAccount.deposit(amount); } // alternative version (valid, but not so nice) public void transfer(double amount, BankAccount targetAccount) { balance -= amount; targetAccount.balance += amount; } 25 Fall 2012 CS2302: Programming Principles
Getters/Accessors and Setters/Mutators Methods class Clock { Private String time; void setTime (String t) {time = t;} String getTime() {return time;} } class ClockTestDrive { public static void main (String [] args){ Cock c = new Clock(); c.setTime("12345") String tod = c.getTime(); System.out.println(time: " + tod); } } 27 Fall 2012 CS2302: Programming Principles
Encapsulation Constructors and methods can call other public and private methods of the same class. Constructors and methods can call only public methods of another class. Class X private field private method Class Y public method 27 Fall 2012 CS2302: Programming Principles
The Static Modifier The static modifier can be applied to variables or methods. It associates a variable or method with the class rather than an object. Methods that are declared as static do not act upon any particular object. They just encapsulate a given task, a given algorithm. 28 Fall 2012 CS2302: Programming Principles
Static Variables It is a variable which belongs to the class and not to object (instance) --- class variable A single copy to be shared by all instances of the class A static variable can be accessed directly by the class name and doesn’t need any object – Syntax :. 29 Fall 2012 CS2302: Programming Principles
Static Methods It is a method which belongs to the class and not to the object(instance) A static method can access only static data. It can not access non-static data (instance variables) A static method can call only other static methods and can not call a non-static method from it. A static method can be accessed directly by the class name and doesn’t need any object – Syntax :. A static method cannot refer to “this” or “super” keywords in anyway 31 Fall 2012 CS2302: Programming Principles
Static Variables - Example public class BankAccount { private long accountNumber; private double balance; private static int numberOfAccounts = 0; public BankAccount() { this.accountNumber = ++numberOfAccounts; this.balance = 0; } public static int getNumberOfAccounts { return numberOfAccounts; } 30 Fall 2012 CS2302: Programming Principles
Summary A program consists of one or more classes A class is a description of a kind of object – In most cases, it is the objects that do the actual work A class describes data, constructors, and methods – An object’s data is information about that object – An object’s methods describe how the object behaves – A constructor is used to create objects of the class Methods (and constructors) may contain temporary data and statements (commands) 32 Fall 2012 CS2302: Programming Principles