Objects and Classes 1 Objectives To construct objects

Objects and Classes 1

• • • Objectives To construct objects from classes. To describe classes and objects using UML. To distinguish between reference and primitive variables. To use pre-defined classes from the Java library. To use getter and setter methods to fetch and set values of private variables. To write and call methods with reference parameters. To differentiate between instance and static variables and methods. To determine the scope of variables. To use this as the name of the current controlling object for a method. To use arrays of objects. To declare inner classes. 2

OO Programming Concepts Object-oriented programming (OOP) =state+behaviour to model an object. state= current values of instance or static variables. Behaviour = instance or static methods defined in the class from which the object was created. 3

Objects State=values of variable(s). Behaviour= method(s) of class. 4

Classes Objects are instantiated from classes. Constructors are methods used to instantiate objects. 5

Classes 6

Constructors, cont. no-arg constructor method: Circle () {…. } • no-arg constructor with empty body is provided by the system if not explicitly coded, UNLESS other constructors are explicitly coded. · Constructor name=class name. · No return type, not even void. • · Invoke constructor by Class. Name x =new Classname(…) 7

Creating Objects Using Constructors Class. Name c = new Class. Name(); • Role of constructors: – Initialize state – Can do lots more Example: Circle c =new Circle(); Circle c= new Circle(5. 0); 8

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

Constructing Objects, cont. 10

Declaring Object Reference Variables Declaring a reference variable: Circle my. Circle; /* default value =null if declared outside of methods*/ /* garbage default value if declared inside a method*/ 11

Declaring/Creating Objects in a Single Step Class. Name object. Ref. Var = new Class. Name(); Assign object reference Create an object Example: Circle my. Circle = new Circle(); 12

Accessing Objects • Using the state of an object: e. g. , my. Circle. radius • Calling an object’s method: e. g. , my. Circle. find. Area() /* this. find. Area() or find. Area() if called from Circle class*/ /* throws a Null. Pointer. Exception if my. Circle == null */ 13

Using Objects • Objectives: – Access data – Create objects – Use methods Test. Simple. Circle Run 14

Caution pow(…) is a static method in the java. lang. Math class java. lang. Math. pow(); Math. method. Name(arguments) (e. g. , Math. pow(3, 2. 5)) IF one had a Math object x, then x. pow(3, 2. 5) is ok. Simple. Circle. find. Area() is illegal. /* find. Area is not static—it depends on an object*/my. Circle. find. Area() is legal. 15

Default Values for variables Local variables (inside methods): no default values. Instance or static variable (outside methods); reference variables: default null. numeric primitive variables: default 0 boolean primitive variables: default false char primitive variables: default ‘u 0000’ 16

Example 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' 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); } } 17
![Example public class Test { public static void main(String[] args) { int x; // Example public class Test { public static void main(String[] args) { int x; //](http://slidetodoc.com/presentation_image_h2/1e94eeeeec53612766cf149fd0db341d/image-18.jpg)
Example 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 18

primitive values reference values 19

Assignment statements 20

Garbage Collection: gc() is called automatically c 1 = c 2, c 1; /* the object previously referenced by c 1 has no reference now*/ /an automatic call to gc() is made*/ /* think free(p) in C */ 21

Garbage Collection, cont c 1= null ; /* net effect is to call gc() if no other variable references that object*/ 22

The Java Library of classes (huge!) System. current. Time. Millis() current time: System. current. Time. Millis() /*static method of java. lang. System */ • Division and remainder operators extract current second, minute, and hour. 23

The Date Class java. util. Date. to. String() java. util. Date has a nice to. String() method that returns a String. java. util. Date date = new java. util. Date(); System. out. println(date. to. String()); Or import java. util. Date; Date date = new Date(); System. out. println(date); displays a string like Sun Mar 09 13: 50: 19 EST 2003. 24

Using Classes from the Java Library • javax. swing. JFrame • import javax. swing. JFrame; – Set title – Set size – Set location – Display frame Test. Frame Run 25

Trace Code Declare my. Circle = new Circle(5. 0); my. Circle no value SCircle your. Circle = new Circle(); your. Circle. radius = 100; 26

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

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

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 29

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 30

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 31

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 32

Using the JFrame Class • Objective: Demonstrate using classes from the Java library. Use the JFrame class in the javax. swing package to create two frames; use the methods in the JFrame class to set the title, size and location of the frames and to display the frames. Test. Frame Run 33

Trace Code JFrame frame 1 = new JFrame(); frame 1. set. Title("Window 1"); frame 1. set. Size(200, 150); frame 1. set. Visible(true); JFrame frame 2 = new JFrame(); frame 2. set. Title("Window 2"); frame 2. set. Size(200, 150); frame 2. set. Visible(true); frame 1 reference Declare, create, and assign in one statement : JFrame title: width: height: visible: 34

Trace Code JFrame frame 1 = new JFrame(); frame 1. set. Title("Window 1"); frame 1. set. Size(200, 150); frame 1. set. Visible(true); JFrame frame 2 = new JFrame(); frame 2. set. Title("Window 2"); frame 2. set. Size(200, 150); frame 2. set. Visible(true); frame 1 reference Set title property : JFrame title: "Window 1" width: height: visible: 35

Trace Code JFrame frame 1 = new JFrame(); frame 1. set. Title("Window 1"); frame 1. set. Size(200, 150); frame 1. set. Visible(true); JFrame frame 2 = new JFrame(); frame 2. set. Title("Window 2"); frame 2. set. Size(200, 150); frame 2. set. Visible(true); frame 1 reference : JFrame title: "Window 1" width: 200 height: 150 visible: Set size property 36

Trace Code JFrame frame 1 = new JFrame(); frame 1. set. Title("Window 1"); frame 1. set. Size(200, 150); frame 1. set. Visible(true); JFrame frame 2 = new JFrame(); frame 2. set. Title("Window 2"); frame 2. set. Size(200, 150); frame 2. set. Visible(true); frame 1 reference : JFrame title: "Window 1" width: 200 height: 150 visible: true Set visible property 37

Trace Code JFrame frame 1 = new JFrame(); frame 1. set. Title("Window 1"); frame 1. set. Size(200, 150); frame 1. set. Visible(true); JFrame frame 2 = new JFrame(); frame 2. set. Title("Window 2"); frame 2. set. Size(200, 150); frame 2. set. Visible(true); frame 1 reference : JFrame title: "Window 1" width: 200 height: 150 visible: true frame 2 reference Declare, create, and assign in one statement : JFrame title: width: height: visible: 38

Trace Code JFrame frame 1 = new JFrame(); frame 1. set. Title("Window 1"); frame 1. set. Size(200, 150); frame 1. set. Visible(true); JFrame frame 2 = new JFrame(); frame 2. set. Title("Window 2"); frame 2. set. Size(200, 150); frame 2. set. Visible(true); frame 1 reference : JFrame title: "Window 1" width: 200 height: 150 visible: true frame 2 reference : JFrame title: "Window 2" width: height: visible: Set title property 39

Trace Code JFrame frame 1 = new JFrame(); frame 1. set. Title("Window 1"); frame 1. set. Size(200, 150); frame 1. set. Visible(true); JFrame frame 2 = new JFrame(); frame 2. set. Title("Window 2"); frame 2. set. Size(200, 150); frame 2. set. Visible(true); frame 1 reference : JFrame title: "Window 1" width: 200 height: 150 visible: true frame 2 reference : JFrame title: "Window 2" width: 200 height: 150 visible: Set size property 40

Trace Code JFrame frame 1 = new JFrame(); frame 1. set. Title("Window 1"); frame 1. set. Size(200, 150); frame 1. set. Visible(true); JFrame frame 2 = new JFrame(); frame 2. set. Title("Window 2"); frame 2. set. Size(200, 150); frame 2. set. Visible(true); frame 1 reference : JFrame title: "Window 1" width: 200 height: 150 visible: true frame 2 reference : JFrame title: "Window 2" width: 200 height: 150 visible: true Set visible property 41

Visibility Modifiers and Accessor/Mutator Methods By default, the class, variable, or method can be accessed by any class in the same package. • public The class, data, or method is visible to any class in any package. • private The data or methods can be accessed only by the declaring class. The get and set methods are used to read and modify private properties. 42

The private modifier restricts access to within a class, the default modifier restricts access to within a package, and the public modifier enables unrestricted access. 43

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

Example of Data Field Encapsulation In this example, private data are used for the radius and the accessor methods get. Radius and set. Radius are provided for the clients to retrieve and modify the radius. Circle Test. Circle Run 45

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 the preceding example, 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 necessary to be immutable. For example, the following class Student has all private data fields and no mutators, but it is mutable. 46

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! } } 47

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

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

Passing Objects to Methods, cont. 50

Instance Variables, and Methods Instance variables belong to a specific instance. Instance methods are invoked by an instance of the class. 51

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

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

Static Variables, Constants, and Methods, cont. 54

Example of Using Instance and Class Variables and Method Objective: Demonstrate the roles of instance and class variables and their uses. This example adds a class variable num. Of. Objects to track the number of Circle objects created. Circle. With. Static. Variable. And. Method Test. Circle. With. Static. Variable. And. Method Run 55

Scope of Variables • The scope of instance and static variables is the entire class. They can be declared anywhere inside a class. • 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. 56

The Keyword this • Use this to refer to the object that invokes the instance method. • Use this to refer to an instance data field. • Use this to invoke an overloaded constructor of the same class. 57

Serving as Proxy to the Calling Object 58

Calling Overloaded Constructor 59
![Array of Objects Circle[] circle. Array = new Circle[10]; An array of objects is Array of Objects Circle[] circle. Array = new Circle[10]; An array of objects is](http://slidetodoc.com/presentation_image_h2/1e94eeeeec53612766cf149fd0db341d/image-60.jpg)
Array of Objects Circle[] circle. Array = new Circle[10]; An array of objects is actually an array of reference variables. So invoking circle. Array[1]. find. Area() involves two levels of referencing as shown in the next figure. circle. Array references to the entire array. circle. Array[1] references to a Circle object. 60
![Array of Objects, cont. Circle[] circle. Array = new Circle[10]; 61 Array of Objects, cont. Circle[] circle. Array = new Circle[10]; 61](http://slidetodoc.com/presentation_image_h2/1e94eeeeec53612766cf149fd0db341d/image-61.jpg)
Array of Objects, cont. Circle[] circle. Array = new Circle[10]; 61

Array of Objects, cont. Summarizing the areas of the circles Total. Area Run 62

Class Abstraction and Encapsulation Class abstraction means to separate class implementation from the use of the class. The creator of the class provides a description of the class and let the user know how the class can be used. The user of the class does not need to know how the class is implemented. The detail of implementation is encapsulated and hidden from the user. 63

The Loan Class Loan Test. Loan. Class Run 64

The Stack. Of. Integers Class Test. Stack. Of. Integers Run 65

Inner Classes • Inner class: A class is a member of another class. • Advantages: In some applications, you can use an inner class to make programs simple. Show. Inner. Class • An inner class can reference the data and methods defined in the outer class in which it nests, so you do not need to pass the reference of the outer class to the constructor of the inner class. 66

Inner Classes (cont. ) • Inner classes can make programs simple and concise. • An inner class supports the work of its containing outer class and is compiled into a class named Out. Class. Name$Inner. Class. Name. clas s. For example, the inner class Inner. Class in Show. Inner. Class is compiled into Show. Inner. Class$Inner. Class. class. 67

Inner Classes (cont. ) • An inner class can be declared public, protected, or private subject to the same visibility rules applied to a member of the class. • An inner class can be declared static. A static inner class can be accessed using the outer class name. A static inner class cannot access nonstatic members of the outer class 68
- Slides: 68