1 / 162

Introduction to Classes and Objects

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

dschmidt
Download Presentation

Introduction to Classes and Objects

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. 3 • Introduction to Classes and Objects

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

  3. 3.1 Introduction • 3.2 Classes, Objects, Methods and Instance Variables • 3.3 Declaring a Class with a Method and Instantiating an Object of a Class • 3.4 Declaring a Method with a Parameter • 3.5 Instance Variables, set Methods and get Methods • 3.6 Primitive Types vs. Reference Types • 3.7 Initializing Objects with Constructors • 3.8 Floating-Point Numbers and Type double • 3.9 (Optional) GUI and Graphics Case Study: Using Dialog Boxes • 3.10 (Optional) Software Engineering Case Study: Identifying the Classes in a Requirements Document • 3.11 Wrap-Up

  4. 3.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

  5. 3.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

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

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

  8. a generic class class class_name { access_modifier type instance_variable_name; access_modifier type instance_variable_name; access_modifier type instance_variable_name; access_modifier return_type (parameter_list) { // body of a method return return_type; }

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

  10. Primitive Types vs. Reference Types • Types in Java • Primitive • boolean, byte, char, short, int, long, float, double • Reference (sometimes called nonprimitive types) • Objects • Default value of null • Used to invoke an object’s methods

  11. 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, Account account1 indicates that account1 is a reference to an Account object).

  12. A very simple class - circle // Circle.java // one instance variable no method public class Circle { public double radius; } // end of class Circle

  13. class a template or blueprint for circles • Circle name of the new type • it is possible to declare instances of Circle • Circle c1 = new Circle(); • instance of a Cicle named c1 • int i =5; • an integer varibale is declered and initilized to

  14. using the . opperator it is possible to reach the instance variables • c1.radius =2; • assign 2 for the variable radius of c1 objcet • double a = c1.radius; • a is decleared and initilized with the value of c1.radius • System.out .printf(“%f”,c1.radius); • print the radius of c1 • area = Math.PI*c;.radius*c1.radius; • the area variable is computed as • System.out .println(2*Math.PI*c1.radius); • print the circunference of c1

  15. // CircleTest.java • public class CircleTest • { • public static void main(String args[]) • { • Circle c1 = new Circle(); • double area; • c1.radius =10; • area = Math.PI*c1.radius*c1.radius; • System.out. printf(“area of c1:: %f\n”,area); • } // end of main method • } // end of CircelTest class

  16. // CircleTest2.java • public class CircleTest • { • public static void main(String args[]) • { • Circle c1; // decleare c1 • System.out. printf(“radius of c1%f\n”,c1.radius); // error • c1 = new Circle(); // criate an initilize a Circel object • // assign c1 to that objcet • System.out. printf(“radius of c1%f\n”,c1.radius); // prints 0 • Circle c2 = new Circle(); // all in one step for c2 • double area; • c1.radius =10; // set c1’s radius to 10 • area = Math.PI*c1.radius*c1.radius; • System.out. printf(“area of c1: %f\n”,area);

  17. c2.radius =20; // set c2’s radius to 10 • area = Math.PI*c2.radius*c2.radius; • System.out. printf(“area of c2: %f\n”,area); • } // end of main method • } // end of CircelTest2 class

  18. c1.radius and c2.radius • are different variables • c1.radius: radius of c1 • c2.radius: radius of c2 • different memory locations • different values...

  19. Declaring objects • two step procedure: • 1-declaring a variable of that class Circle c1: • this is a reference variable to a Circle object that is not defined or initilaized yet

  20. Circle c1 = new Circle(); • combining the two stepes • can be split into two steps • // step 1 • Circle c1; • // c1 a referenc to a Circle type objcet • get the value of null • c1.radius : not defined yet – error

  21. step 2: • c1 = new Circle(); • allocates memory for a Circle type objcet • for holding instance variables • c1 can reach its instance variables • c1 can call or invoke its methods

  22. Circle c1; • c1 is a reference to a Circel • whose value is null c1 null • c1 = new Circle(); • second step: • c1 is a reference • can reach • radius radius d1

  23. new opperator • class variable name = class name(); • class name(); • a constructor is run • usually initilize instance variables • example: • c1 = new Circle(); • a Circle object’ instance variable • radius is initilize to 0 • doubles are initilize to 0

  24. Nesne Referans Değikenlerine Atama Yapmak • Circle c1= new Circle(); • Circle c3 = c1; • c3 is declared and assigned to c1 • so c3 also points to the objcet pointed by c1 • c1 and c3 are reference to the same Circle objcet in the memory

  25. c1 and c3 references to the sam • Circle object radius c1 c3

  26. Differences between Variables of Primitive Data Types and Object Types

  27. Copying Variables of Primitive Data Types and Object Types

  28. int i = 1 ,j = 2; • // declare and initilize two primitive types • i =j; • //both i and j are store 2 • Circle c1 = new Circle(); • c1.radius =5; • Circle c2 = new Circle(); • c2.radius =9; • c1 =c2;

  29. Garbage Collection As shown in the previous figure, after the assignment statement c1 = c2, c1 points to the same object referenced by c2. The object previously referenced by c1 is no longer referenced. This object is known as garbage. Garbage is automatically collected by JVM.

  30. 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 variable.

  31. Circle c1 = new Circle(); • c1.radius =20; • Circle c3 = c1; • System.out.println(“radius of c3:”+c3.radius); • prints 20 • it seems that no value is assigned to c3.radius • as c3 refers to the same object as c1 • c1.radius and c3.radius are the same value in memory

  32. Methods • return_tyep method_name (parameter list) • { • statements • return expresion of type return_type; • } • return type can be • primitive types • objects • void:returns noting • parameter list: • comma seperated list of paramers type and name

  33. Exampe • lets add a method to the Circle class • public void printRadius(); • { • System.out.println(“radius:”+radius ); • }

  34. Adding a method to the Circle class • public class Circle • { • public double radius; • public void printRadius() • { • System.out.println(“radius:”+radius ); • } // end of printRadius method • } // end of Circle class

  35. Calling the method in the test class • //CircleTest3.java • public class CircleTest3 • { • public static void main(String args[]) • { • Circle c1= new Circle(); • Circle c2= new Circle(); • c1.radius = 10; • c2.radius = 20; • c1. printRadius(); // prints radius of c1 • c2. printRadius(); // prints radius of c2 • } // end of main • } // end of CicleTest3 class

  36. printRadius() • does not return anything - void • takes no parameters • c1.printRadius(); • invokes printRadius for c1 • the radius variable of the object refered by c1 is printed • c2.printRadius(); • the same action for c2

  37. the instance variable radius takes the value whose objcet references • no need for the . operator • to refer an instance variable or method from its own class • object name is not needed • to call it from another class • objcet name is needed • we will avoid it soon information hiding

  38. two methds returning a value • lets add a methods to calculate the area and circunference of a circle • public double area() • { • double area = Math.PI*radius*radius; • return area; • } • public double circonference() • { • return 2*Math.PI*radius, • }

  39. // CircleTest4.java • public class CircleTest44 • { • public static void main(String args[]) • { • Circle c1= new Circle(); • Circle c2= new Circle(); • c1.radius = 10; • c2.radius = 20; • double circe1Area = c1.area(); • System.out.printf(“area of c1: %f\n”,circle1Area); • System.out.printf(“circunference of c2: %f\n”,c2.circunference()); • } • }

  40. More on Arguments and Parameters • Parameters specified in method’s parameter list • Part of method header • Uses a comma-separated list

  41. Common Programming Error 3.2 • A compilation error occurs if the number of arguments in a method call does not match the number of parameters in the method declaration.

  42. Common Programming Error 3.3 • A compilation error occurs if the types of the arguments in a method call are not consistent with the types of the corresponding parameters in the method declaration.

  43. methods taking parameters • lets add a method setting the radius of a circle: • public void setRadius(double r ) • { • if (r > 0) • radius = r; • else • radius = 0; • }

  44. // CircleTest4.java • public class CircleTest44 • { • public static void main(String args[]) • { • Circle c1= new Circle(); • c1.setRadius(10); • // equivalent to c1.radius = 10; • // but c1.radius =-10; ends a meaningless radius • System.out.printf(“area of c1: %f\n”,c1.area()); • } • }

  45. void setRadius(double r) • takes a double parameter • parameters are local variables in the method • when the method is called or invoked an argument is passed to the parameter • in this example r=10 • it is possible to call the method like that • c1.setRadius(5+5); • r = 5+5

  46. c1.radius =-10; • assigns a meaningless value to radius of c1 • setRadius method protect this • written once in class Cricle • otherwise any class attemting to assign a value to radius should make this check • if it is to be done with one method it is natural to be part of the Circle class

  47. set and get methods • private instance variables • Cannot be accessed directly by clients of the object • Use set methods to alter the value • Use get methods to retrieve the value

  48. 3.5 Instance Variables, set Methods and get Methods • Variables declared in the body of method • Called local variables • Can only be used within that method • Variables declared in a class declaration • Called fields or instance variables • Each object of the class has a separate instance of the variable

  49. Access Modifiers public and private • private keyword • Used for most instance variables • private variables and methods are accessible only to methods of the class in which they are declared • Declaring instance variables private is known as data hiding • Return type • Indicates item returned by method • Declared in method header

  50. public class Circle • { • private radius; • public void setRadius(double r) • { • ..... • } • public double getRadius(); • { • return radius; • } • }

More Related