for use of ist410 students only objectbasics-1 objects: basic concepts
Post on 19-Dec-2015
226 Views
Preview:
TRANSCRIPT
ObjectBasics-1For use of IST410 Students only
Objects: Basic Concepts
ObjectBasics-2For use of IST410 Students only
Objectives
Classes and Objects Writing Methods Passing parameters and getting return value Abstraction and Encapsulation Access levels and Encapsulation
ObjectBasics-3For use of IST410 Students only
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
ObjectBasics-4For use of IST410 Students only
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
ObjectBasics-5For use of IST410 Students only
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 classentity: a point class: PointAttributes: x & y coordinates Instance Vars: int x, yOperation: distance from origin Method:
void distanceFromOrigin()
ObjectBasics-6For use of IST410 Students only
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
ObjectBasics-7For use of IST410 Students only
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 datamembers are declared here
All methods aredefined here;
ObjectBasics-8For use of IST410 Students only
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
ObjectBasics-9For use of IST410 Students only
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
ObjectBasics-10For use of IST410 Students only
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
p1 x=0y=0
Memory is allocated at thecompilation time for p1
Object is constructed atrun-time somewhere in memoryby asking the system forallocation of memory from free store.
ObjectBasics-11For use of IST410 Students only
Data Members 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; andp2.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
ObjectBasics-12For use of IST410 Students only
public Data Members
Consider the following partial class definition for Pointpublic class Point {
public int x; public int y; // rest of the class definition
} Also consider a second class PointUser with a main
methodpublic static void main(String args[]) {
Point p1 = new Point();// rest of the code
}
ObjectBasics-13For use of IST410 Students only
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 programp1.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
ObjectBasics-14For use of IST410 Students only
private data Members
Consider the Point class again where x and y are privatepublic class Point {
private int x; private int y; // rest of the class definition
} Operation such as p1.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
ObjectBasics-15For use of IST410 Students only
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
ObjectBasics-16For use of IST410 Students only
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
arguments or Parameter list
Access level or modifier
ObjectBasics-17For use of IST410 Students only
Invoking Member Method
If p1 is an object of type Pointp1. showCoordinates()
results in invoking or executing the method showCoordinates for p1
Similarly, if p2 is another object of type Pointp2. 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
ObjectBasics-18For use of IST410 Students only
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
ObjectBasics-19For use of IST410 Students only
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 classp1.showCoordinates(); // shows the current x and y valuep1.showCoordinates(); // shows the current x and y value againp1.showCoordinates(); // shows the current x and y value again
ObjectBasics-20For use of IST410 Students only
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
ObjectBasics-21For use of IST410 Students only
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
ObjectBasics-22For use of IST410 Students only
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
ObjectBasics-23For use of IST410 Students only
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
ObjectBasics-24For use of IST410 Students only
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 ofyOrd at the time of call
a gets a copy of xOrd at the time of call
ObjectBasics-25For use of IST410 Students only
Value Parameters
Parameters are always passed by valuepublic 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); }}
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
ObjectBasics-26For use of IST410 Students only
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 changepublic 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
ObjectBasics-27For use of IST410 Students only
Parameter Type Checking
The count and data types of parameters in the calling side must match, in order, those of the formal parametersMethod: 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
ObjectBasics-28For use of IST410 Students only
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
ObjectBasics-29For use of IST410 Students only
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
ObjectBasics-30For use of IST410 Students only
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
ObjectBasics-31For use of IST410 Students only
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 propertiesx = d;
}
ObjectBasics-32For use of IST410 Students only
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
ObjectBasics-33For use of IST410 Students only
More on classes and objects
ObjectBasics-34For use of IST410 Students only
Objectives
Constructors Overloading of Methods Class variables and methods this Key word
ObjectBasics-35For use of IST410 Students only
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
ObjectBasics-36For use of IST410 Students only
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
ObjectBasics-37For use of IST410 Students only
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));
}}
ObjectBasics-38For use of IST410 Students only
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
ObjectBasics-39For use of IST410 Students only
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 caseobj.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
ObjectBasics-40For use of IST410 Students only
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
ObjectBasics-41For use of IST410 Students only
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 }} Notice matching constructor
signature - OVERLOADING Constructors are methods and can be
overloaded
Default
ObjectBasics-42For use of IST410 Students only
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
ObjectBasics-43For use of IST410 Students only
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
Type Defaultboolean falsechar nullbyte 0short 0int 0long 0Lfloat 0.0Fdouble 0.0Dobjects null
ObjectBasics-44For use of IST410 Students only
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
ObjectBasics-45For use of IST410 Students only
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
ObjectBasics-46For use of IST410 Students only
Memory allocation: Construction Process
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
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}
ObjectBasics-47For use of IST410 Students only
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
ObjectBasics-48For use of IST410 Students only
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 necessarythis.y = y; //to unhide the instance variable
} // rest of the class}
ObjectBasics-49For use of IST410 Students only
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);
}} ‘this’ key word is used call an
overloaded constructor If ‘this’ keyword is used in a
constructor, it must be the very first line
ObjectBasics-50For use of IST410 Students only
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
ObjectBasics-51For use of IST410 Students only
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); }}
ObjectBasics-52For use of IST410 Students only
static Methods
A method can be marked static - called class methods
A static method is called using ClassName.methodName 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
ObjectBasics-53For use of IST410 Students only
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));
}}
Notice that calcSquareRoot method is called without instantiating an object of type SqrtTest
Static methods can only use static data members and local variables of the method
ObjectBasics-54For use of IST410 Students only
static initializers
A class can include statements written in a static block Such static blocks are called static initializers Static blocks are executed only once when the class is
loaded for the first time If a class includes more than one static blocks, they are
executed in the order specified Static blocks provide a handy mechanism to load device
drivers, class libraries etc at the start of an application
ObjectBasics-55For use of IST410 Students only
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(); }}
OutputFixedVariableNew
ObjectBasics-56For use of IST410 Students only
Java source file layout
Source definition of a java class has three components An optional package definition Any number of (optional) import statements The class definition
package project.accounting; import java.awt.*;
import java.io.*; import java.awt.event.*; public class MyClass { // Class definition }
Optional declaration
ObjectBasics-57For use of IST410 Students only
Exercise
Write a class named MyDate. This date models a standard calendar date. This class should include 4 constructors and a number of methods
Constructor that takes three arguments for day, month, year and after validation initializes the object to a date using the three parameters
A default constructor that calls the first constructor with default date values of 1,1,2001
An overloaded constructor that takes only 2 arguments for day and month, calls the first constructor and initializes to the given date of 2001
The last overloaded constructor takes a MyDate object as the argument and initializes the date to that date value
ObjectBasics-58For use of IST410 Students only
Exercise
A static method called printDate that takes a MyDate object as argument and prints the date value
to set the date by taking 3 parameters: one each for day, month,year
a private validation method that ensures the date created is legal a print method that prints the current date 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
accessor methods getDay, getMonth, getYear that returns the day, month, and year respectively
top related