Presentation is loading. Please wait.

Presentation is loading. Please wait.

For use of IST410 Students only ObjectBasics-1 Objects: Basic Concepts.

Similar presentations


Presentation on theme: "For use of IST410 Students only ObjectBasics-1 Objects: Basic Concepts."— Presentation transcript:

1 For use of IST410 Students only ObjectBasics-1 Objects: Basic Concepts

2 For use of IST410 Students only ObjectBasics-2 Objectives l Classes and Objects l Writing Methods l Passing parameters and getting return value l Abstraction and Encapsulation l Access levels and Encapsulation

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

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

5 For use of IST410 Students only ObjectBasics-5 class l An entity has characteristics and behavior l The entity’s characteristics or attributes are modeled as instance variables in a class l The entity’s behavior or operations are modeled as methods of the class entity: a pointclass:Point Attributes: x & y coordinatesInstance Vars: int x, y Operation: distance from originMethod: void distanceFromOrigin()

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

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

8 For use of IST410 Students only ObjectBasics-8 Designing a class: Abstraction l A process of extracting appropriate information about an entity or a category, without getting mired in details l We ignore unimportant details about the entity l The class represents our view of the entity l The quality of abstraction is judged by the appropriateness of our representation l 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 l Different software designers may create different abstraction of the same entity

9 For use of IST410 Students only ObjectBasics-9 object l A program is made of objects l An object is an instance of a class l objects need to be instantiated or created before they can be used l 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(); } l Memory is allocated for an object only when the object is instantiated Constructor, discussed in the next section

10 For use of IST410 Students only ObjectBasics-10 Memory Allocation: Objects Point p1 = new Point(); l p1 is a reference variable for an object type Point Point p1; p1 = new Point(); l Each object has its own copy of the instance variables p1 x=0 y=0 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.

11 For use of IST410 Students only ObjectBasics-11 Data Members of an Object l An object has two types of members: data and method l Data members are declared in the class space l In a program, a data member is referred using a syntax of object.dataMemberName l 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 l There is no possibility of confusion between x of p1 and x of p2 since p1 and p2 make them unambiguous l The period or dot is called member of operator

12 For use of IST410 Students only ObjectBasics-12 public Data Members l Consider the following partial class definition for Point public class Point { public int x; public int y; // rest of the class definition } l 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 For use of IST410 Students only ObjectBasics-13 public data Members l Notice that both data members of Point (x & y) are declared as public (also called modifier) l 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 l Public members can be modified by any object anywhere in the program l We cannot guarantee the consistency of these data members since they can be modified by any object

14 For use of IST410 Students only ObjectBasics-14 private data Members l 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 } l Operation such as p1.x = 20; in the main or any method outside Point class results in a compilation error l Members marked private are not accessible outside the class l It would be ‘relatively easy’ to protect the integrity of private data members

15 For use of IST410 Students only ObjectBasics-15 Methods: Introduction l 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 l Complex objects usually have many methods l Method syntax return type methodName ( arguments) { // implementation of the method } Method name and argument list together represent the method’s signature

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

17 For use of IST410 Students only ObjectBasics-17 Invoking Member Method l If p1 is an object of type Point p1. showCoordinates() results in invoking or executing the method showCoordinates for p1 l Similarly, if p2 is another object of type Point p2. showCoordinates() results in invoking the method showCoordinates for p2 l 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 For use of IST410 Students only ObjectBasics-18 A simple example 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

19 For use of IST410 Students only ObjectBasics-19 Method Invocation again l A method can be called or invoked as many times as desired. l 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 l 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

20 For use of IST410 Students only ObjectBasics-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 For use of IST410 Students only ObjectBasics-21 Variable Scope l Instance variables are created when objects are created l Instance variables live as long as the object lives l Local variables are created only when a method is invoked l Local variables die when the method completes execution l Local variables are created all over again when the method is called again l Every time a method is called, local variables are created fresh without any memory of past life

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

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

24 For use of IST410 Students only ObjectBasics-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 For use of IST410 Students only ObjectBasics-25 Value Parameters l 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.1x =a; 3.2b = 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); } k = 100; change to b in setPoint has no effect on k in the calling method b = k hence b = 100 b (not k) is changed to 82

26 For use of IST410 Students only ObjectBasics-26 Objects as Parameters l Objects are also passed by value; however, values of instance variables of the object can be changed l 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 For use of IST410 Students only ObjectBasics-27 Parameter Type Checking l 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 For use of IST410 Students only ObjectBasics-28 Returning a value from a Method l All methods discussed up to this point are void methods; they do not return any thing to its caller l A method can return a value to its caller int sum(int x, int y) { // implementation } l The method sum returns an integer to its caller l 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)); l The example assumes that sum is a method of object obj

29 For use of IST410 Students only ObjectBasics-29 return Statement l return is logically the last statement executed in a method l When a return is executed, the control reverts to the caller l return statement has 2 forms return; return expression; l Using the first form, control is merely returned to the caller l 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 For use of IST410 Students only ObjectBasics-30 return Statement l void methods do not return any value, coding of the return statement is optional l 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 For use of IST410 Students only ObjectBasics-31 Encapsulation l As we have seen, making data members public can be a bad idea since any object can modify the public member l 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 l Why not control data member access through public methods? public void setX( int d) { // validate d for required properties x = d; }

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

33 For use of IST410 Students only ObjectBasics-33 More on classes and objects

34 For use of IST410 Students only ObjectBasics-34 Objectives l Constructors l Overloading of Methods l Class variables and methods l this Key word

35 For use of IST410 Students only ObjectBasics-35 Introduction l This section is a continuation of basic object concepts l A number of new syntax rules are presented as are concepts of designing a class l We start with the discussion of method overloading

36 For use of IST410 Students only ObjectBasics-36 Method Overloading l A method can be overloaded l Each overloaded method has its own implementation l 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 } l Rules m A method’s signature must be unique m Method name is the same m Argument list must be distinct - necessary condition m Return type may be different - not sufficient by itself

37 For use of IST410 Students only ObjectBasics-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 For use of IST410 Students only ObjectBasics-38 Method Overloading l How does the compiler choose the appropriate method? m By matching the argument types m If arguments do not have exact match, standard promotions are tried m If the compiler is unable to match argument types, error is reported l Advantage of overloading - a programmer chooses the ‘same’ method name even if the arguments are different

39 For use of IST410 Students only ObjectBasics-39 Method Overloading pitfall l 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; } l These two methods can be ambiguous in following case obj.add(2,3); l As you see, there is no exact match l When standard promotions are attempted, the compiler cannot uniquely determine the correct overloaded method to use: thus compiler error l Parameter types should be carefully chosen when designing overloaded methods

40 For use of IST410 Students only ObjectBasics-40 Constructors l Constructors are special methods l Constructors are used to initialize an object l Constructor syntax classname ( arguments) { // implementation of the constructor } l Name of the constructor is same as the name of the class l Constructor does not have a return type l If a return type is used, it turns into a method l Constructor may or may not have arguments

41 For use of IST410 Students only ObjectBasics-41 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 } 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 } l Notice matching constructor signature - OVERLOADING l Constructors are methods and can be overloaded Default

42 For use of IST410 Students only ObjectBasics-42 Designing a class: Constructors l Default constructor is the ‘no argument’ constructor l The compiler provides the default constructor if it is not coded in the class l However, if a constructor with arguments exists, compiler does not provide a ‘no argument’ constructor l It is generally a good idea to code a default constructor when a constructor with arguments is coded

43 For use of IST410 Students only ObjectBasics-43 Constructing an object l When an object is constructed, instance variables are automatically initialized to their default values l The default values depend upon the data type of the instance variable and are as shown

44 For use of IST410 Students only ObjectBasics-44 Constructing an object l Local variables are not initialized automatically l It is the programmer’s responsibility to initialize local variables to an appropriate initial value l It is also a good programming practice to initialize all local variables

45 For use of IST410 Students only ObjectBasics-45 Explicit Initialization of Instance Variables l 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 For use of IST410 Students only ObjectBasics-46 Memory allocation: Construction Process public class TestPoint { public static void main(String args[]) { Point p = new Point(); // activities with p } l Memory is allocated for the instance variables: x and y in this case l Instance variables are initialized to their default values: x and y set to 0 l Explicit initialization, if any, is done: x is set to 20, y to 25 l Constructor is executed 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 For use of IST410 Students only ObjectBasics-47 Hiding Instance Variables l 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 For use of IST410 Students only ObjectBasics-48 this l this is a key word l this always refers to the current object l 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 For use of IST410 Students only ObjectBasics-49 Calling overloaded constructor 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 } public class TestPoint { public static void main(String args[]) { Point p = new Point(); // activities with p Point p2 = new Point(18,99); } l ‘this’ key word is used call an overloaded constructor l If ‘this’ keyword is used in a constructor, it must be the very first line

50 For use of IST410 Students only ObjectBasics-50 static data Members l A class can include static data members l Static data members are class variables l All objects of the class share the same copy of the variable l If static data members are public, they can be accessed with ClassName.staticMemberName l If static data members are private, they can be accessed within the class by name

51 For use of IST410 Students only ObjectBasics-51 static data Members: Example public class ObjectCounter {//ObjectCounter.java public static int count = 0; private int id; public ObjectCounter() { count++; id = count; } public int getId() { return id; } public static void main(String args[]) { ObjectCounter o1 = new ObjectCounter(); System.out.println("Object id = "+o1.getId()+ " Static counter is = "+ObjectCounter.count); ObjectCounter o2 = new ObjectCounter(); System.out.println("Object id = "+o2.getId()+ " Static counter is = "+ObjectCounter.count); ObjectCounter o3 = new ObjectCounter(); System.out.println("Object id = "+o3.getId()+ " Static counter is = "+ObjectCounter.count); }

52 For use of IST410 Students only ObjectBasics-52 static Methods l A method can be marked static - called class methods l A static method is called using ClassName.methodName l An object need not be constructed to invoked a static method public class SqrtTest { public static double calcSqrRoot(double x) { double sqrt = x/2; double xprev; do { xprev = sqrt; sqrt = ( xprev + x/xprev)/2; } while (Math.abs(sqrt-xprev) > 1E-6) ; return sqrt; } } // end SqrtTest.class

53 For use of IST410 Students only ObjectBasics-53 static Methods public class FindSquareRoot { public static void main(String args[]) { double x = 25.0; System.out.println(“Square root of “+x+” is “+ SqrtTest.calcSqrRoot(x)); } l Notice that calcSquareRoot method is called without instantiating an object of type SqrtTest l Static methods can only use static data members and local variables of the method

54 For use of IST410 Students only ObjectBasics-54 static initializers l A class can include statements written in a static block l Such static blocks are called static initializers l Static blocks are executed only once when the class is loaded for the first time l If a class includes more than one static blocks, they are executed in the order specified l Static blocks provide a handy mechanism to load device drivers, class libraries etc at the start of an application

55 For use of IST410 Students only ObjectBasics-55 static initializers: Example public class StaticBlocks {//StaticBlocks.java static String s1 = "Fixed"; static String s2 = "Variable"; static { System.out.println(s1); System.out.println(s2); s2 = "New"; } static String s3 = s2; static { System.out.println(s3); } public static void main(String args[]) { StaticBlocks sb = new StaticBlocks(); } Output Fixed Variable New

56 For use of IST410 Students only ObjectBasics-56 Java source file layout l Source definition of a java class has three components l An optional package definition l Any number of (optional) import statements l The class definition package project.accounting; import java.awt.*; import java.io.*; import java.awt.event.*; public class MyClass { // Class definition } Optional declaration

57 For use of IST410 Students only ObjectBasics-57 Exercise l Write a class named MyDate. This date models a standard calendar date. This class should include 4 constructors and a number of methods m Constructor that takes three arguments for day, month, year and after validation initializes the object to a date using the three parameters m A default constructor that calls the first constructor with default date values of 1,1,2001 m An overloaded constructor that takes only 2 arguments for day and month, calls the first constructor and initializes to the given date of 2001 m The last overloaded constructor takes a MyDate object as the argument and initializes the date to that date value

58 For use of IST410 Students only ObjectBasics-58 Exercise m A static method called printDate that takes a MyDate object as argument and prints the date value m to set the date by taking 3 parameters: one each for day, month,year m a private validation method that ensures the date created is legal m a print method that prints the current date m accessor methods setDay, setMonth, setYear that respectively changes the value of day, month and year; in each case the update is allowed only if the resultant date is legal m accessor methods getDay, getMonth, getYear that returns the day, month, and year respectively


Download ppt "For use of IST410 Students only ObjectBasics-1 Objects: Basic Concepts."

Similar presentations


Ads by Google