1 / 32

Chapter 7 Objects and Classes

Chapter 7 Objects and Classes. 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 . Classes and Objects. A Java program consists of one or more classes

anais
Download Presentation

Chapter 7 Objects and Classes

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 7 Objects and Classes Fall 2012 CS2302: Programming Principles

  2. 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 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

  5. 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. Fall 2012 CS2302: Programming Principles

  6. 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 Fall 2012 CS2302: Programming Principles

  7. Class: Car Object: a car • Attributes: • String model • Color color • intnumPassengers • 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: Fall 2012 CS2302: Programming Principles

  8. Defining Classes for Objects • Class • User-defined data type • Object • Instance of class, A role of variable • Define a correspond class to define a object • Define a class Describe the structure of object Data Field(variable, constant) [modifier] class ClassName{ // field declarations //Constructors // method declarations } public, final, abstract Define actions of object Method Field Fall 2012 CS2302: Programming Principles

  9. 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 Fall 2012 CS2302: Programming Principles

  10. Class Example Fall 2012 CS2302: Programming Principles

  11. Object Example Fall 2012 CS2302: Programming Principles

  12. 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) Class vs. Object Fall 2012 CS2302: Programming Principles

  13. 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 Class vs. Object Fall 2012 CS2302: Programming Principles

  14. Program File File File Class Variables Statements Constructors Variables File Statements Methods Variables Diagram of program structure • A program consists of one or more classes • Typically, each class is in a separate .javafile Fall 2012 CS2302: Programming Principles

  15. Object type is a Reference Type • Go over the textbook slides from page 29 to 38 Fall 2012 CS2302: Programming Principles

  16. 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. Fall 2012 CS2302: Programming Principles

  17. Benefits of Encapsulation 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. Fall 2012 CS2302: Programming Principles

  18. 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 example of Encapsulation Fall 2012 CS2302: Programming Principles

  19. 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 Fall 2012 CS2302: Programming Principles

  20. 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. Fall 2012 CS2302: Programming Principles

  21. 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, publicor without a visibility modifier: privateint hours; int hours; public int hours; Fall 2012 CS2302: Programming Principles

  22. 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()andsetTime() 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). Fall 2012 CS2302: Programming Principles

  23. 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. Fall 2012 CS2302: Programming Principles

  24. Illegal Access - example // Example of illegal access classBankAccountTest { public static void main(String[] args) { BankAccount victim = newBankAccount(2398742); victim.balance = victim.balance - 500; // this will not compile! } } public class BankAccount { private long accountNumber; private double balance; // … Fall 2012 CS2302: Programming Principles

  25. Encapsulation - example public void transfer(double amount, BankAccounttargetAccount) { withdraw(amount); targetAccount.deposit(amount); } // alternative version (valid, but not so nice) public void transfer(double amount, BankAccounttargetAccount) { balance -= amount; targetAccount.balance += amount; } Fall 2012 CS2302: Programming Principles

  26. Getters/Accessors and Setters/Mutators Methods class Clock {               Private String time;                 voidsetTime (String t) {time = t;} StringgetTime() {return time;} } classClockTestDrive {      public static void main (String [] args){Cock c = new Clock(); c.setTime("12345")        Stringtod = c.getTime(); System.out.println(time: " + tod);}} Fall 2012 CS2302: Programming Principles

  27. 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 public method Fall 2012 CS2302: Programming Principles

  28. 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. Fall 2012 CS2302: Programming Principles

  29. 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 : <class-name>.<variable-name> Fall 2012 CS2302: Programming Principles

  30. 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 callonly 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 : <class-name>.<method-name> • A static method cannot refer to “this” or “super” keywords in anyway Fall 2012 CS2302: Programming Principles

  31. Static Variables - Example public class BankAccount { private long accountNumber; private double balance; private staticintnumberOfAccounts = 0; publicBankAccount() { this.accountNumber = ++numberOfAccounts; this.balance = 0; } public staticintgetNumberOfAccounts { returnnumberOfAccounts; } } Fall 2012 CS2302: Programming Principles

  32. 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) Fall 2012 CS2302: Programming Principles

More Related