Chapter 8 Objects and Classes A CLASS is

Chapter 8 Objects and Classes

A CLASS is a “blueprint” from which we create OBJECTS. It is a blueprint for an object Class represents state and behaviors of that object OBJECTS have a “state” of existence defined by ATTRIBUTES. The ATTRIBUTES of an OBJECT are defined by the VARIABLES in the Object’s CLASS. OBJECTS have “behaviors” that are defined by operations known as METHODS.

OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that can be distinctly identified. For example, a student, a desk, a circle, a button, and even a loan can all be viewed as objects. An object has a unique identity, state, and behaviors. The state of an object consists of a set of data fields (also known as properties) with their current values. The behavior of an object is defined by a set of methods.

Class and Object Class is a blueprint for an object Class represents state and behaviors of that object For e. g. Class Person State= Name, Age Behavior= Change Name, Update age Real World Object for e. g. : Bank Account, Vehicles, Animals etc.

Classes Instance data Constructors Methods Contain Name of a class Instance data about employee (state) Behaviors(Methods) Get methods : Accessor Methods Set methods: Mutator methods It is good practice to create get and set method in a class

Objects An object has both a state and behavior. The state defines the object, and the behavior defines what the object does.

Classes are constructs that define objects of the same type. A Java class uses variables to define data fields and methods to define behaviors. Additionally, a class provides a special type of methods, known as constructors, which are invoked to construct objects from the class. Public class employee{ }

Constructor. F Constructor- a special method used to set up an object when it is originally created. Does not have a return value Has the same name as the CLASS in which it is used (If you create a class and do not provide a constructor method, Java will create an empty one by default-it is pretty much useless though) Public employee(){} Open car. java from github and add default constructor

SCOPE F The SCOPE of data refers to the parts of the program in which the data can be used. Data declared at the CLASS level can be used by all of the methods in that CLASS. This data is know as CLASS or INSTANCE data. Private string first. Name Data declared within a Method can only be referenced by that method and is known as LOCAL data. Public Employee(string fname){first. Name=fname} Open car. java from github and add 3 properties

Encapsulation One of the principle attributes of Object Oriented Programming is ENCAPSULATION If we view an OBJECT internally we should be able to see the details of the object’s variables and methods. If we were to view it from outside then we should just see the services it provides and how it interacts with other objects. These services are its INTERFACE. OBJECTS should be self-governing and provide their SERVICES to their CLIENTs through their INTERFACE as though they seem like a black box. Eg. print. Employee()

VISIBILITY “modifiers” help reinforce encapsulation ideas by restricting a client’s ability to access an object. FINAL is used to create an unchangeable variable like a Constant. PRIVATE restricts access to an object to the members of the object’s class. PRIVATE METHODS are known as SUPPORT Methods. PUBLIC visibility allows the object to be referenced anywhere. PUBLIC METHODS ar know as SERVICE Methods PROTECTED- visibility by classes only in the same package Private int employee. ID Public get. Employee. Name() Open car. java from github and add all getter and setter for Protected string get. SSN(){retrun SSN} Protected String set. SSN(string value){return SSN=value} }

SETTERS and GETTERS SETTERS or MUTATORS are common methods involved in most classes. It allows a service interface to change data values. set. Height GETTERS or ACCESSORS are a common service method to allow a method to return a variable’s value to a client program. get. Height

F STATIC - A variable or method that is shared by all instances of a class is called a class variable or class method. You recognize such a variable in Java by the static keyword in the declaration. A static variable will instantiate only one copy of the variable for the whole class instead of a separate copy for each instance of a class. A static variable belongs to a class, not to an instance of the class. Static variables/methods can NOT access non-static variables/methods! Static variables are declared to keep track of some attribute of all instances of a class of objects. Such as a count of all of the circles created. Static methods can serve as utility methods where you don’t have to declare an object of the class to use the method and all dependencies for the static method can be passed in from the class.

The return Statement F The return type of a method indicates the type of value that the method sends back to the calling location F A method that does not return a value has a void return type F A return statement specifies the value that will be returned return expression; F Its expression must conform to the return type 14

The to. String Method F All classes that represent objects should define a to. String method F The to. String method returns a character string that represents the object in some way F It is called automatically when an object is concatenated to a string or when it is passed to the println method F Int x=5; F System. out. printl(x. to. String())

Method Control Flow F The called method is often part of another class or object main obj. do. It(); do. It help. Me(); help. Me

Classes

UML Class Diagram

Default Constructor A class may be defined without constructors. In this case, a no-arg constructor with an empty body is implicitly declared in the class. This constructor, called a default constructor, is provided automatically only if no constructors are explicitly defined in the class.

Constructors Circle() { } Constructors are a special kind of methods that are invoked to construct objects. Circle(double new. Radius) { radius = new. Radius; } 20

Constructors, cont. A constructor with no parameters is referred to as a no-arg constructor. · Constructors must have the same name as the class itself. · Constructors do not have a return type—not even void. · Constructors are invoked using the new operator when an object is created. Constructors play the role of initializing objects. 21

Creating Objects Using Constructors new Class. Name(); Example: new Circle(); new Circle(5. 0); 22

Declaring Object Reference Variables To reference an object, assign the object to a reference variable. To declare a reference variable, use the syntax: Class. Name object. Ref. Var; Example: Circle my. Circle;

Declaring/Creating Objects in a Single Step Class. Name object. Ref. Var = new Class. Name(); Example: Assign object reference Create an object Circle my. Circle = new Circle(); Open car. java from github and create car object

Accessing Object’s Members Referencing the object’s data: object. Ref. Var. data e. g. , my. Circle. radius array. Name. length Invoking the object’s method: object. Ref. Var. method. Name(arguments) e. g. , my. Circle. get. Area() string. Name. length()

animation Trace Code Declare my. Circle = new Circle(5. 0); my. Circle SCircle your. Circle = new Circle(); your. Circle. radius = 100; Open car. java from github call your constructor no value

animation Trace Code, cont. Circle my. Circle = new Circle(5. 0); my. Circle your. Circle = new Circle(); your. Circle. radius = 100; Create a circle no value

animation Trace Code, cont. Circle my. Circle = new Circle(5. 0); Circle your. Circle = new Circle(); your. Circle. radius = 100; Assign object reference to my. Circle reference value

animation Trace Code, cont. Circle my. Circle = new Circle(5. 0); my. Circle reference value your. Circle no value Circle your. Circle = new Circle(); your. Circle. radius = 100; Declare your. Circle

animation Trace Code, cont. Circle my. Circle = new Circle(5. 0); my. Circle reference value your. Circle no value Circle your. Circle = new Circle(); your. Circle. radius = 100; Create a new Circle object

animation Trace Code, cont. Circle my. Circle = new Circle(5. 0); my. Circle reference value Circle your. Circle = new Circle(); your. Circle. radius = 100; your. Circle reference value Assign object reference to your. Circle

animation Trace Code, cont. Circle my. Circle = new Circle(5. 0); my. Circle reference value Circle your. Circle = new Circle(); your. Circle. radius = 100; your. Circle reference value Change radius in your. Circle

Caution Recall that you use Open car. java from github and call setmake, getmake and tostring method Math. method. Name(arguments) (e. g. , Math. pow(3, 2. 5)) to invoke a method in the Math class. Can you invoke get. Area() using Circle 1. get. Area()? The answer is no. All the methods used before this chapter are static methods, which are defined using the static keyword. However, get. Area() is non-static. It must be invoked from an object using object. Ref. Var. method. Name(arguments) (e. g. , my. Circle. get. Area()). More explanations will be given in the section on “Static Variables, Constants, and Methods. ”

Reference Data Fields The data fields can be of reference types. For example, the following Student class contains a data field name of the String type. public class Student { String name; // name has default value null int age; // age has default value 0 boolean is. Science. Major; // is. Science. Major has default value false char gender; // c has default value 'u 0000' }

Default Value for a Data Field The default value of a data field is null for a reference type, 0 for a numeric type, false for a boolean type, and 'u 0000' for a char type. However, Java assigns no default value to a local variable inside a method. public class Test { public static void main(String[] args) { Student student = new Student(); System. out. println("name? " + student. name); System. out. println("age? " + student. age); System. out. println("is. Science. Major? " + student. is. Science. Major); System. out. println("gender? " + student. gender); } }

Example Java assigns no default value to a local variable inside a method. public class Test { public static void main(String[] args) { int x; // x has no default value String y; // y has no default value System. out. println("x is " + x); System. out. println("y is " + y); } } Compilation error: variables not initialized

The Date Class Java provides a system-independent encapsulation of date and time in the java. util. Date class. You can use the Date class to create an instance for the current date and time and use its to. String method to return the date and time as a string.

The Date Class Example For example, the following code java. util. Date date = new java. util. Date(); System. out. println(date. to. String()); displays a string like Sun Mar 09 13: 50: 19 EST 2003.

Static Variables, Constants, and Methods Static variables are shared by all the instances of the class. Static methods are not tied to a specific object. Static constants are final variables shared by all the instances of the class.

Static Variables, Constants, and Methods, cont. To declare static variables, constants, and methods, use the static modifier.

Static Variables, Constants, and Methods, cont.

NOTE An object cannot access its private members, as shown in (b). It is OK, however, if the object is declared in its own class, as shown in (a).

Why Data Fields Should Be private? To protect data. To make class easy to maintain.

Example of Data Field Encapsulation Circle. With. Private. Data. Fields Test. Circle. With. Private. Data. Fields Run

Passing Objects to Methods q Passing by value for primitive type value (the value is passed to the parameter) q Passing by value for reference type value (the value is the reference to the object) Test. Pass. Object Run 45

Passing Objects to Methods, cont. 46
![Array of Objects, cont. Circle[] circle. Array = new Circle[10]; Array of Objects, cont. Circle[] circle. Array = new Circle[10];](http://slidetodoc.com/presentation_image_h2/5f6379687b022b050b0643db846afa84/image-47.jpg)
Array of Objects, cont. Circle[] circle. Array = new Circle[10];

Immutable Objects and Classes If the contents of an object cannot be changed once the object is created, the object is called an immutable object and its class is called an immutable class. If you delete the set method in the Circle class in Listing 8. 10, the class would be immutable because radius is private and cannot be changed without a set method. A class with all private data fields and without mutators is not necessarily immutable. For example, the following class Student has all private data fields and no mutators, but it is mutable. 48

Example public class Student { private int id; private Birth. Date birth. Date; public class Birth. Date { private int year; private int month; private int day; public Student(int ssn, int year, int month, int day) { id = ssn; birth. Date = new Birth. Date(year, month, day); } public Birth. Date(int new. Year, int new. Month, int new. Day) { year = new. Year; month = new. Month; day = new. Day; } public int get. Id() { return id; } public Birth. Date get. Birth. Date() { return birth. Date; } } public void set. Year(int new. Year) { year = new. Year; } } public class Test { public static void main(String[] args) { Student student = new Student(111223333, 1970, 5, 3); Birth. Date date = student. get. Birth. Date(); date. set. Year(2010); // Now the student birth year is changed! } } 49

What Class is Immutable? For a class to be immutable, it must mark all data fields private and provide no mutator methods and no accessor methods that would return a reference to a mutable data field object. 50

Scope of Variables q The scope of instance and static variables is the entire class. They can be declared anywhere inside a class. q The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be initialized explicitly before it can be used. 51

The this Keyword q The this keyword is the name of a reference that refers to an object itself. One common use of the this keyword is reference a class’s hidden data fields. q Another common use of the this keyword to enable a constructor to invoke another constructor of the same class. 52

Reference the Hidden Data Fields 53

Calling Overloaded Constructor 54
- Slides: 54