1 / 58

Objects: Basic Concepts

Objects: Basic Concepts. Objectives. Classes and Objects Writing Methods Passing parameters and getting return value Abstraction and Encapsulation Access levels and Encapsulation. Object Oriented Paradigm. Object oriented paradigm incorporates 3 main concepts Encapsulation Inheritance

kristene
Download Presentation

Objects: Basic Concepts

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. Objects: Basic Concepts

  2. Objectives • Classes and Objects • Writing Methods • Passing parameters and getting return value • Abstraction and Encapsulation • Access levels and Encapsulation

  3. Object Oriented Paradigm • Object oriented paradigm incorporates 3 main concepts • Encapsulation • Inheritance • Polymorphism • These concepts are implemented in a Java program through a structure called class • classes are the basic building blocks in the construction of an object-oriented program • In this section, we explore the concept of encapsulation and its application to designing classes; inheritance and polymorphism are discussed in later sections

  4. class • A program is made of objects • An object is an instance of a class • Examples • dog is a class; pooky, your pet, is an instance of dog, i.e. object • circle is a class, a circle of 2” dia drawn on a screen is an object • a point in a 2-D space is a class, a point located at some coordinate on the screen is an object. • A class is a template or blueprint from which objects are made • A class models a thing, person, place or an idea, i.e. an entity

  5. class • An entity has characteristics and behavior • The entity’s characteristics or attributes are modeled as instance variables in a class • The entity’s behavior or operations are modeled as methods of the class entity: a point class: Point Attributes: x & y coordinates Instance Vars: int x, y Operation: distance from origin Method: void distanceFromOrigin()

  6. class • A class is always the starting point in writing a Java program • class is also the implementation of an entity’s software model public class ClassName { // definition of the class } • public - indicator of the access level; a keyword • class - declaration of a class; a keyword • ClassName - the name of the class, user defined identifier • { } - block, defines the implementation of the class • This is the only place for the complete definition of the class

  7. class public class Point{ } All instance variables or data members are declared here private int x; private int y; public double distanceFromOrigin() { return Math.sqrt(x* x + y * y); } All methods are defined here; Other Methods

  8. Designing a class: Abstraction • A process of extracting appropriate information about an entity or a category, without getting mired in details • We ignore unimportant details about the entity • The class represents our view of the entity • The quality of abstraction is judged by the appropriateness of our representation • For example, an wire frame picture of a car, though a correct abstraction, would be poor representation of reality if we are interested in abstracting car’s ‘running’ behavior • Different software designers may create different abstraction of the same entity

  9. object • A program is made of objects • An object is an instance of a class • objects need to be instantiated or created before they can be used • Any number of objects can be instantiated from a class public class AnyClass { public static void main(String args[]) { Point p1 = new Point(); Point p2 = new Point(); } } • Memory is allocated for an object only when the object is instantiated Constructor, discussed in the next section

  10. Memory Allocation: Objects Point p1 = new Point(); • p1 is a reference variable for an object type Point Point p1; p1 = new Point(); • Each object has its own copy of the instance variables p1 Memory is allocated at the compilation time for p1 Object is constructed at run-time somewhere in memory by asking the system for allocation of memory from free store. x=0 y=0 p1

  11. DataMembers of an Object • An object has two types of members: data and method • Data members are declared in the class space • In a program, a data member is referred using a syntax of object.dataMemberName • If p1 and p2 are two objects of type Point p1.x refers to the data member x (an int) of p1; and p2.x refers to the data member x (an int) of p2 • There is no possibility of confusion between x of p1 and x of p2 since p1 and p2 make them unambiguous • The period or dot is called member of operator

  12. public Data Members • Consider the following partial class definition for Point public class Point { public int x; public int y; // rest of the class definition } • Also consider a second class PointUser with a main method public static void main(String args[]) { Point p1 = new Point(); // rest of the code }

  13. public data Members • Notice that both data members of Point (x & y) are declared as public (also called modifier) • Since these members are public, it is legal to access these members from anywhere in the program p1.x = 20; is a legal operation in the main method of PointUser, also from any other method of any class • Public members can be modified by any object anywhere in the program • We cannot guarantee the consistency of these data members since they can be modified by any object

  14. private data Members • Consider the Point class again where x and y are private public class Point { private int x; private int y; // rest of the class definition } • Operation such asp1.x = 20;in the main or any method outside Point class results in a compilation error • Members marked private are not accessible outside the class • It would be ‘relatively easy’ to protect the integrity of private data members

  15. Methods: Introduction • A method can be thought of as a named piece of code that implements a well defined behavior of the object or a well defined operation with the object • Complex objects usually have many methods • Method syntax <modifiers> return type methodName ( arguments) { // implementation of the method } Method name and argument list together represent the method’s signature

  16. Methods: Introduction • modifiers - public, private, protected, static • modifiers are optional - results in package visibility • return type - is required, void is used if no return type exists • arguments - is a comma separated list of variables; the list can be empty • A class can have many member methods public void setPoint(int a, int b) { x = a; y = b; } defines the return type Access level or modifier arguments or Parameter list

  17. Invoking Member Method • If p1 is an object of type Point p1. showCoordinates() results in invoking or executing the method showCoordinates for p1 • Similarly, if p2 is another object of type Point p2. showCoordinates() results in invoking the method showCoordinates for p2 • There is no possibility of confusion between these two method invocations since each method may only use its local variables and the data members of that object

  18. public class Point { private int x; private int y; public void setPoint(int a, int b) { x = a; y = b; } public void showCoordinates() { System.out.println("x = "+x+ " y = "+y); } } public class PointUser { public static void main(String args[]) { Point p1 = new Point(); p1.setPoint(20,15); p1.showCoordinates(); } } Follow the lines to see sequence of statements executed as a result of method call A simple example

  19. Method Invocation again • A method can be called or invoked as many times as desired. • Every time the method is called, it is a brand new activity and all statements in the method are executed without any memory of past execution • Suppose we execute the following in the main method of the PointUser class p1.showCoordinates(); // shows the current x and y value p1.showCoordinates(); // shows the current x and y value again p1.showCoordinates(); // shows the current x and y value again

  20. Variable Scope public class SomeClass { private int x; private int y; public void methodOne(){ int p = 20; int q = 15; } public void methodTwo() { int x = 20; y = 15; } } x and y are instance variables (data members) and visible to all methods p and q are local variables of methodOne and visible strictly in the method. x is a local variable and hides the instance variable x y is the instance variable

  21. Variable Scope • Instance variables are created when objects are created • Instance variables live as long as the object lives • Local variables are created only when a method is invoked • Local variables die when the method completes execution • Local variables are created all over again when the method is called again • Every time a method is called, local variables are created fresh without any memory of past life

  22. Passing parameter • Methods are not very useful unless they can be generalized • Parameters are used to generalize a method • Consider the setPoint method of the Point class • In many cases, we cannot predetermine coordinates of a point; we delay setting the coordinate until run-time • Parameters are used to ‘pass’ coordinates to the setPoint method; the method uses values of parameters to complete its task • Ability to pass parameters to a method during the run-time makes the method general

  23. Passing parameter public void setPoint(int a, int b) { x = a; y = b; } • int a and int b are the two parameters • Parameters are ‘place holders’ for values supplied during the run-time through formal arguments • Parameters are local variables of the method • Parameters get their starting values from the caller of the method • Parameters go out of scope when the method ends execution

  24. Invoking a method with parameter Point p1 = new Point(); int xOrd = 20; int yOrd = 15; p1.setPoint(xOrd,yOrd); public void setPoint(int a, int b) { x = a; y = b; } b gets a copy of yOrd at the time of call a gets a copy of xOrd at the time of call

  25. Value Parameters • Parameters are always passed by value public class NewPoint { private int x = 20; private int y = 18; public void setPoint(int a, int b) { 3.1 x =a; 3.2 b = 82; } } public class TestPoint { public static void main(String args[]) { 1. int k = 100; 2. NewPoint p = new NewPoint(); 3. p.setPoint(300,k); 4. System.out.println(“k is still “+k); } } b = k hence b = 100 b (not k) is changed to 82 k = 100; change to b in setPoint has no effect on k in the calling method

  26. Objects as Parameters • Objects are also passed by value; however, values of instance variables of the object can be changed • The reference itself does not change public class MyObject { int x; public void setX(MyObject m) { 4.1. m.x = 300; } public static void main(String args[]) { 1. MyObject obj = new MyObject(); 2. obj.x = 20; 3. System.out.println(“Obj before change “+obj.x); 4. obj.setX(obj); 5. System.out.println(“Obj after change “+obj.x); } } x = 20 x = 300

  27. Parameter Type Checking • The count and data types of parameters in the calling side must match, in order, those of the formal parameters Method: public void swap (int x, int y) { int temp = x; x = y; y = temp; } String s1 = “Java”; int d2 = 20; swap(1,2); //OK, x = 1, y = 2 swap(s1,9); //Illegal, s1 is a String swap(10,d2); //OK, x = 10, y = d2

  28. Returning a value from a Method • All methods discussed up to this point are void methods; they do not return any thing to its caller • A method can return a value to its caller int sum(int x, int y) { // implementation } • The method sum returns an integer to its caller • The return value can be assigned to an integer variable or used in an expression where an integer is normally used int s = obj.sum (2,3); int r = 2*obj.sum(2,3); System.out.println(“Result is “+2*sum(2,3)); • The example assumes that sum is a method of object obj

  29. return Statement • return is logically the last statement executed in a method • When a return is executed, the control reverts to the caller • return statement has 2 forms return; return expression; • Using the first form, control is merely returned to the caller • Using the second form, both control and the result of the expression are returned return; // No return value, only control return 3; // Return value is 3 return (a+b/3); // Expression result is returned

  30. return Statement • void methods do not return any value, coding of the return statement is optional • non-void methods are required to code the return statement public void printInterest(double amt, double rate) { double interest; interest = amt * rate /1200.0; System.out.println(“Interest is = “+interest); } public int sum (int x, int y) { return (x+y); } No return needed return is needed, method returns int

  31. Encapsulation • As we have seen, making data members public can be a bad idea since any object can modify the public member • Making the data member private prevents access by other objects; however, from time to time other objects do in fact need to change values of these data items • Why not control data member access through public methods? public void setX( int d) { // validate d for required properties x = d; }

  32. Encapsulation • A class encapsulates or hides a set of ‘characteristics’ and ‘behavior’ of an entity • Encapsulation enables the programmer to force interaction with the object only through ‘public’ interfaces (methods) • Private information of an object is prevented from being directly manipulated by other objects • The extent of hiding is determined by design of the class • Encapsulation then is • declaring data members as private • providing public methods to access the data members; • validating parameters of these public methods before allowing changes to the data members

  33. More on classes and objects

  34. Objectives • Constructors • Overloading of Methods • Class variables and methods • this Key word

  35. Introduction • This section is a continuation of basic object concepts • A number of new syntax rules are presented as are concepts of designing a class • We start with the discussion of method overloading

  36. Method Overloading • A method can be overloaded • Each overloaded method has its own implementation • Example from java.lang.Math class: public static int max(int a, int b) { // implementation } public static long max(long a, long b) { // implementation } public static float max(float a, float b) { // implementation} public static double max(double a, double b) { //implementation } • Rules • A method’s signature must be unique • Method name is the same • Argument list must be distinct - necessary condition • Return type may be different - not sufficient by itself

  37. Method Overloading: Example public class Overload { //Overload.java public int add(int a, int b) { return (a+b); } public double add(double a, double b) { return (a+b); } public String add(String s1, String s2) { return (s1+s2); } public static void main(String args[]) { int a = 2, b = 3; double d1 = 2.3, d2 = 3.4; Overload o = new Overload(); System.out.println("add Integers "+o.add(a,b)); System.out.println("add doubles "+o.add(d1,d2)); System.out.println("concat Strings "+o.add("Hello ","World")); System.out.println("add doubles "+o.add(a,d2)); } }

  38. Method Overloading • How does the compiler choose the appropriate method? • By matching the argument types • If arguments do not have exact match, standard promotions are tried • If the compiler is unable to match argument types, error is reported • Advantage of overloading - a programmer chooses the ‘same’ method name even if the arguments are different

  39. Method Overloading pitfall • Consider the following two overloaded methods: public long add(int a, long b) { return a+b; } public long add(long a, int b) { return a+b; } • These two methods can be ambiguous in following case obj.add(2,3); • As you see, there is no exact match • When standard promotions are attempted, the compiler cannot uniquely determine the correct overloaded method to use: thus compiler error • Parameter types should be carefully chosen when designing overloaded methods

  40. Constructors • Constructors are special methods • Constructors are used to initialize an object • Constructor syntax <modifier> classname ( arguments) { // implementation of the constructor } • Name of the constructor is same as the name of the class • Constructor does not have a return type • If a return type is used, it turns into a method • Constructor may or may not have arguments

  41. public class TestPoint { public static void main(String args[]) { Point p = new Point(); // activities with p p = new Point(20,20); // activities with the new p } } Notice matching constructor signature - OVERLOADING Constructors are methods and can be overloaded Constructors: Example public class Point { private int x, y; public Point() { x = 0; y = 0; } public Point(int a, int b) { x = a; y = b; } // rest of the class } Default

  42. Designing a class: Constructors • Default constructor is the ‘no argument’ constructor • The compiler provides the default constructor if it is not coded in the class • However, if a constructor with arguments exists, compiler does not provide a ‘no argument’ constructor • It is generally a good idea to code a default constructor when a constructor with arguments is coded

  43. Constructing an object • When an object is constructed, instance variables are automatically initialized to their default values • The default values depend upon the data type of the instance variable and are as shown

  44. Constructing an object • Local variables are not initialized automatically • It is the programmer’s responsibility to initialize local variables to an appropriate initial value • It is also a good programming practice to initialize all local variables

  45. Explicit Initialization of Instance Variables • Instance variables can be explicitly initialized public class Point { private int x = 20; private int y = 18; public void setPoint(int a, int b) { x = a; y = b; } public void showCoordinates() { System.out.println("x = "+x+" y = "+y); } } x is initialized to 20 and y is initialized to 18 when an object of type Point is created

  46. public class TestPoint { public static void main(String args[]) { Point p = new Point(); // activities with p } } Memory is allocated for the instance variables: x and y in this case Instance variables are initialized to their default values: x and y set to 0 Explicit initialization, if any, is done: x is set to 20, y to 25 Constructor is executed Memory allocation: Construction Process public class Point { private int x = 20; private int y = 25; public Point() { x = 20; y = 25; } public Point(int a, int b) { x = a; y = b; } // rest of the class }

  47. Hiding Instance Variables • Instance variables have lower priority than local variables of the same name public class Point { private int x; private int y; public void setPoint(int a, int b) { int x; x = a; y = b; } public void showCoordinates() { System.out.println("x = "+x+" y = "+y); } } This x is a local variable and therefore hides the instance variable x The local variable x is being initialized. This initialization has no effect on the instance variable x This x is still the instance variable since no local variable with the same name exists

  48. this • this is a key word • this always refers to the current object • It can be used to unhide an instance variable in a method public class Point { private int x, y; public Point() { this.x = 20; //this key word is not necessary this.y = 25; } public Point(int x, int y) { this.x = x; //this key word is necessary this.y = y; //to unhide the instance variable } // rest of the class }

  49. Calling overloaded constructor • public class TestPoint { • public static void main(String args[]) { • Point p = new Point(); • // activities with p • Point p2 = new Point(18,99); • } • } • ‘this’ key word is used call an overloaded constructor • If ‘this’ keyword is used in a constructor, it must be the very first line public class Point { private int x, y; public Point() { this(20,25); } public Point(int a, int b) { x = a; y = b; } // rest of the class }

  50. static data Members • A class can include static data members • Static data members are class variables • All objects of the class share the same copy of the variable • If static data members are public, they can be accessed with ClassName.staticMemberName • If static data members are private, they can be accessed within the class by name

More Related