2.15k likes | 2.17k Views
1. Introduction to Classes and Objects. OBJECTIVES. In this chapter you will learn: What classes, objects, methods and instance variables are. How to declare a class and use it to create an object. How to declare methods in a class to implement the class’s behaviors.
E N D
1 • Introduction to Classes and Objects
OBJECTIVES In this chapter you will learn: • What classes, objects, methods and instance variables are. • How to declare a class and use it to create an object. • How to declare methods in a class to implement the class’s behaviors. • How to declare instance variables in a class to implement the class’s attributes. • How to call an object’s method to make that method perform its task. • The differences between instance variables of a class and local variables of a method. • How to use a constructor to ensure that an object’s data is initialized when the object is created. • The differences between primitive and reference types.
1.1 Introduction • 1.2 Classes, Objects, Methods and Instance Variables • 1.3 Declaring a Class without/with a Method and Instantiating an Object of a Class • 1.4 Declaring a Method without/with a Parameter • 1.5 Instance Variables, set Methods and get Methods • 1.6 Primitive Types vs. Reference Types • 1.7 Initializing Objects with Constructors
Classes 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.
Classes and Objects An object has both a state and behavior. The state defines the object, and the behavior defines what the object does.
1.2 Classes, Objects, Methods and Instance Variables (Cont.) • Classes contain one or more attributes • Specified by instance variables • Carried with the object as it is used
1.2 Classes, Objects, Methods and Instance Variables • Class provides one or more methods • Method represents task in a program • Describes the mechanisms that actually perform its tasks • Hides from its user the complex tasks that it performs • Method call tells method to perform its task
a generic class class class_name { access_modifier type instance_variable_name = initial_value; access_modifier type instance_variable_name; access_modifier type instance_variable_name; // methods access_modifier return_type method_name(parameter_list) { // body of a method statement(s); return return_expression; } // end of method .. } // end of class
Examples of Classes and Objects • In registration system • classes: • Student, Instructor, Adivisor, Course • Student: blueprint for a typical student • chacteristics – atributes – instance variables • name, last name, address, deparment, advisor.,,, • courses taken • behavior – by methods • add course, delete course, send approvel, concent request • what about gpa? bevaior or chacteristic
Examples of Classes and Objects (cont.) • Intructor: • charecteristics: • name, department, title, • behavior: • approve/reject programs, approve/reject concents • give courses, see course lists • Course • charcateristics: • name, credit, desription, prerequizite(s), hours • behavior: • How can a course behave?
Objects • Specific sturdents are instances of the Student class • they are Studnet objects • each Student object has a different name, address, department,... • The Student class indicats what characteristics a particular student should have • Each shoud have a name, ad department • and what can a student do – hew it behave in the program
Objects (cont.) • Similarly there are instances of Instructors, Courses • Every course opended is an instance of the Course class • it has a name, credit, hours and so on. • Instructor class indicates the charcateristics and behavior of a typical insturtor in the registration system. • Each particular instructor has a specific value for these characteristics and behave as indicated by methods of the Instructor class.
Another Example • Geometric program – a game program • Classes: regrangle, circle, square, cube,... • Rectangle • charceteristics: heigth, width, position, color • behavior: move, expend or shrink • what about area characteristics or behavior? • area can be calculated from heitht nnd width • knowing heigth and width of a rectangle – their values can change through out the program execution • any call to the area method returns a value to area
Reference and primitive types • build in types– primitive types • byte,short,int,long,float,double,char,boolean • single variables – value of a singel varible • initial default values are 0 • for boolean falce • for local variables initial default is not defined • Referece types: • holds the address of an object in the memory
Primitive Types vs. Reference Types • Types in Java • Primitive • boolean, byte, char, short, int, long, float, double • Reference (sometimes called nonprimitive types) • Refers to objects • Default value of null • Used to invoke an object’s methods
Software Engineering Observation 3.4 • A variable’s declared type (e.g., int, double or GradeBook) indicates whether the variable is of a primitive or a reference type. If a variable’s type is not one of the eight primitive types, then it is a reference type. For example, Rectangel r1 • indicates that r1 is a reference to an Rectamge object).
A very simple class - Rectangle // Rectangle.java // only two simple instance variables: heigth and width // no methods public class Rectangle { public double height; public double width; } // end of class Rectangle
Explanations • The file Rectangle.java contains the source code for the Rectangle class • The class name and file name are the same • There can only be one class declared as public in a file whose name is to be the same as the file name • In principle there can be more than one class in a file but others are not declared as public • When you use a development environment such as Eclipse, it creates one class for each file • The extension of source code files is always java
Common Programming Error 1.1 • Declaring more than one public class in the same file is a compilation error.
Explanations (cont.) • When the program is compiled Java produces a byte code stored in a file named Rectangle.class • The extension of byte codes are: class • file name is: public_class_name.class • in this example: Rectangle.class • When executing – running - a program Java Virtual Machine (JVM) takes the byte codes and converts them into appropriate machine language of the platform. Then, CPU executes the instructions in the platform’s machine language
Explanations (cont.) • The Rectangle defined in the file Rectangle.java has only two properties as hight and width. • Both are real numbers declared a type double • Every Rectangle object created – instantiated – from the Rectangle class can have a different hight and width variable • These are called instance variables as every instance of Rectangle has these variables possibly with different values. • these variables are declared with access modifier public – • other classes can directly reach them and change them.
Explanations (cont.) • Rectangle class is a template or blueprint for rectangles • Rectangle name of the new class • it is possible to declare instances of Rectangles, that is to create objects from the Rectangle class like that: • Rectangle r1 = new Rectangle(); • Rectangle r2 = new Rectangle(); • instance of a Rectangles refered by reference variables r1 and r2 • Compare with declaring and inililizing a simple type • int i =5; • an integer varibale i is declered and initilized to 5
A Test Class // a test calss for creating Rectangle s and nanipulating TestRectangle .java public class TestRectangle { public static void main(String args[]) { Rectangle r1 = new Rectangle(); Rectangle r2 = new Rectangle(); r1.height = 3.0; r1.width = 4.0; r2.height = 5.0; double area1 = r1.height*r1.width; double area2 = r2.height*r2.width; System.out. printf(“area of r1: %10.2f\n”,area1); System.out. printf(“area of r2: %10.2f\n”,area2); } // end of method main } // end of class TestRectangle
Explanations • There are two classes in this program: • Rectangle and TestRectangle whose source codes are stored in files Rectangle.java and TestRectangle.java respectively. • When the program is compiled the two source files are complied to files containing byte codes: • Rectangle.class and TestRectangle.class respectively. • When the program runs (is executed) Java Virtual Machine (JVM) takes the byte code instructions in .class files convert them into the machine language of the platform and execute instruction one by one
Explanations (cont.) • There should only be one main method in only one of these files or classes usually called the test class or driver class. • The instructions in the main method are executed one by one in a sequence naturally considering decision or iterations. • In most of our applications objects from other classes are created, refered or manipulated in the main method of the test class.
what happends • In the previous program the following things happen in the main method in a sequence: • first two Rectangle type objects are created and refered by two reference variables r1 and r2 respetively. Rectangle r1 = new Rectangle(); Rectangle r2 = new Rectangle(); • Initially the height and width of both rectangles have values 0.0 • Look at the code of the Rectangle class – the two instance variables are declared without specifiying any initial value. public double height; public double width; • The default values for numerical type simple instance variables are • 0 for byte, short, int and long • 0.0 for float and double • Default values for boolean type varaibles – false • for char type variables – null charcter \n0000’
in memory • r1 and r2 refers to difremt • Rectangle objects hegth 0.0 width 0.0 r1 heigth 0.0 width 0.0 r2
what happends (cont.) • r1.heigth and r2.heigth are different variables • r1.heigth: heigth of regtangle refered by reference r1 • r2.height: heigth of regtangle refered by reference r2 • stored in different memory locations • can have different values...
What happends (cont.) • using the . opperator it is possible to change and reach the instance variables of objects • r1.height =3.0; • assign 3.0 for the variable heigfth of r1 objcet • double area = r1.heigth*r1.width; • area is decleared and initilized with the value of r1.height*r1width • System.out .printf(“%f”,r1.height); • print the higth of r1 • the area or r1 can be printed withut using a variable is computed as System.out .printf(“area of r1 %10.2f”\n” ,r1.higth*r1.width); • prints the area of rectangle refered by r1 without storing in a seperate variable such as area1
What happends (cont.) • Note that test class can reach and change values of heigth and width variables of two Rectangle objects • because • in the Rectange class both heigth and width are declared as public • objects created in other classes – here in the test class • can change or reach these variables
Rectange as a reference • Note the word Rectangle appers two times in the statement Rectangle r1 = new Rectangle(); new Rectangle(); - creates a Rectangle object in memory Rectangle r1 = declares a reference variable of type Rectangle and assign the newly created Rectangle object to the (created on the right hand side of the =) to the referance variable • Reference variables refer to objcts • their values are not simple things such as integers or doubles but they hold the memoy address of objcts they are refering to.
The height and width variables of the first rectange is changed to 3.0 and 4.0 respectively wia r1. • Only the height variable of the second rectangle is changed via r2 to 5.0 . r1.height = 3.0; r1.width = 4.0; r2.height = 5.0; • the width of the second rectangle remains at 0.0
after changing values of variables • r1 and r2 refers to difremt • Rectangle objects hegth 3 width 4 r1 heigth 5 width 0 r2
areas of the two rectangles are calculated and stored in area1 and area2 variables of type double. double area1 = r1.height*r1.width; double area2 = r2.height*r2.width; • Both area1 and area2 are local variables in method main • The values of area1 and area2 are printed System.out. printf(“area of r1: %10.2f\n”,area1); System.out. printf(“area of r2: %10.2f\n”,area2);
Deeper Look at Object Creation Rectange r1 = new Rectangel(); • actually three things happen here • i - because of “=“ this is an assignment statement • on the right hand side of assignment • new Rectangle(); • a Rectange object is created in memory whose instance variables heigth and width are taking defaulst values of 0.0 • ii – on the left hand side - Rectangle r1 • a Rectangle type reference variable whose name is r1 is declared • iii – r1 is assigned to the newly created object • r1 refers to the newly created objcet just created on the right hand side of assignment
Deeper Look at Object Creation (cont.) Rectangel r1 = new Rectangel(); • can be executed in two steps • can be split into two Java statements • step 1 Rectangle r1; • r1 is a reference variable to a Rectangle type objcet • here only a reference is declared • but no object is created yet, r1 has the value null
Deeper Look at Object Creation (cont.) • if you write and try to execute • r1.heigth • error as r1 does not refer to any object yet – • what is the value of r1 then? null • if a reference variable exists but currently not refering to any objcect, its value is null.
step 2: • r1 = new Rectangle(); • new Rectangle(); • creates a Rectangle object • allocates memory for a Rectangle type objcet • for holding instance variables • r1 is already declared in step 1 (as a reference type) is assigned to the newly created object • after step 2 is executed r1.height = 5.0; • type of statements can be executed
Rectangle r1; • r1 is a reference variable • whose curent value is null r1 null • r1 = new Rectangle(); • second step: • r1 is a reference • refering to the • Rectangle object height 0.0 widtih 0.0 r1
new opperator • reference_variable_name = new class name(); • class name(); • a constructor is executed • usually initilize instance variables • example: • r1 = new Rectangle(); • a Rectangle object’ instance variable • hight, width are initilize to 0 • doubles are initilize to 0 • Look at the
returning to the test clas Rectangle r1 = new Rectangle(); Rectangle r2 = new Rectangle(); r1.height = 3.0; r1.width = 4.0; r2.height = 5.0; double area1 = r1.height*r1.width; double area2 = r2.height*r2.width; System.out. printf(“area of r1: %10.2f\n”,area1); System.out. printf(“area of r2: %10.2f\n”,area2);
Assigning instance variables wia references Rectangle r1 = new Rectangle(); Rectangle r2 = new Rectangle(); r1.height = 3.0; r1.width = 4.0; r2.height = 5.0; • r1 and r2 are refering different Rectangle objcects in memory
in memory • r1 and r2 refers to difremt • Rectangle objects hegth 3 width 4 r1 heigth 5 width 0 r2
Values of Reference Variables • then perfrom the assignment r1 = r2; • the value of r2 is assigned to r1 • the new value of r1 becomes the value of r2 • but what is the value of r2? • – the Rectangle objects it refer to – the address of the object – not specifically its height or width.
so now r1’s value is also the same object r2 is refering • both r1 and r2 are refering to the same Rectangle object in memory • So what happens to the first Rectangel object previously refered by r1 • now, no reference variable is refering to the first Ractange object created.
in memory aftrer the assignment • r1 and r2 refering to the same • Rectangle object hegth 3 width 4 r1 heigth 5 width 0 r2
after the assignment r1=r2; • r1.heigth and r2.heigth has the value 5.0 • as both reference variables refer to the same object, • hight value r1.heigth = 6; System.out.println(r2.heigth); • prints 6.000 to the screen • because we change the value via r1 from 5 to 6 • and afrterwords refer it in println via r2
Garbage Collection As shown in the previous figure, after the assignment statement r1 = r2, r1 points to (refers to ) the same object referenced by r2. The object previously referenced by r1 is no longer referenced by any reference variable. This object is known as garbage. Garbage is automatically collected by JVM.
Garbage Collection, cont TIP: If you know that an object is no longer needed, you can explicitly assign null to a reference variable for the object. The JVM will automatically collect the space if the object is not referenced by any refernece variable. Rectange r1 = new Rectange(); ... ... r1 = null;
Copying Variables of Primitive Data Types for simple types such as int variables // declare and initilize two primitive types int i = 1 ,j = 2; i =j; //after this assignment both i and j are storing 2