Unit 3: Java as Object Oriented
Programming Language-
Overview
Arrays, Strings, Classes and Methods
1
A First Simple Program
/*This is a simple Java program. Name this file "Example.java".*/
ThefirstthingthatyoumustlearnaboutJavaisthatthenameyougivetoasourcefileisvery
important(sameasclassnamewheremain()methodispresent).Forthisexample,thenameof
thesourcefileshouldbeExample.java.
2
class Example
{
// Your program begins with a call to main().
public static void main(String args[])
{
System.out.println("This is a simple Java program.");
}
}
A First Simple Program
public:-membermaybeaccessedbycodeoutsidetheclassinwhichitisdeclared.
private:-whichpreventsamemberfrombeingusedbycodedefinedoutsideofitsclass.
static:-staticallowsmain()tobecalledwithouthavingtoinstantiateaparticularinstanceofthe
class.Thisisnecessarysincemain()iscalledbytheJavainterpreterbeforeanyobjectsare
made.
void:-voidsimplytellsthecompilerthatmain()doesnotreturnavalue.
3
A First Simple Program
main:-main()isthemethodcalledwhenaJavaapplicationbegins.Javaiscase-sensitive.Thus,
Mainisdifferentfrommain.ItisimportanttounderstandthattheJavacompilerwillcompile
classesthatdonotcontainamain()method.ButtheJavainterpreterhasnowaytorunthese
classes.
Stringargs[]:-declaresaparameternamedargs,whichisanarrayofinstancesoftheclass
String.
4
A First Simple Program
To Compile and Run the Java Program Following Command is used
C:\>javac Example.java
C:\>java Example
When the program is run, the following output is displayed:
5
This is a simple Java program.
What is a Class ?
A class is a description of a set of objects that share the same attributes, operations.
An objectis an instance of class.
A class is an abstraction in which it
Emphasizes relevant characteristics
Suppresses other characteristics
6
What is an Object ?
•Informally, an object represents an entity, either physical, conceptual or software.
Physical –Truck or a Person
Conceptual –Chemical Process
Software –Invoice 101, Sales Order SO01
•Formally, an object is an entity with a well defined boundary and identity that
encapsulates its state & behavior
State: is represented by attributes and relationships
Behavior: is represented by operations, methods.
7
What is an Object ?
•Object Has State
The state of an object is one of the possible conditions/attributes in which an object may exist
The state of an object normally changes over time
E.g. Kanetkaris an object of class Professor. The Kanetkarobject has state:
Name=Kanetkar
Employee Id=2001
Hire date=02/02/1995
Status=Tenured (Occupied)
Max Load=3
8
What is an Object ?
•Object has Behavior
Behaviordetermineshowanobjectactsandreacts.
Thevisiblebehaviorofanobjectismodeledbythesetofmessages/methodsitcan
respondto(operationstheobjectcanperform)
ProfessorKanetkar’sBehavior:
SubmitFinalGrades()
AcceptCourseOfferings()
Getavacation()
9
What is an Object ?
•Object has Identity
Each object has a unique identity, even if the state is identical to that of another object.
Distinguish objects.
E.g. Professor Kanetkaris from Nagpur. Even if there is a professor with the same name –
Kanetkarin Pune teaching C++, they both are distinct objects
10
A Relationship Between Classes & Objects
Class serves as a template / blue print for creating objects i.e. A class is an abstract
definition of an object.
It defines the structure & behaviorof each object in the class
•Attributes of a Class
Anattributeisanamedpropertyofaclassthatdescribesarangeofvaluesthatinstancesofthe
propertymayhold.
Aclassmayhaveanynumberofattributesornoattributesatall.
Anattributehasatype,whichtellsuswhatkindofattributeitis.
Typicallyattributesareinteger,boolean,varcharetc.
Thesearecalledprimitivetypes.Primitivetypescanbespecificforacertainprogramminglanguage.
11
Declaring Objects
Box mybox= new Box();// declare and allocate a Box object
This statement combines the two steps just described. It can be rewritten like this to show each
step more clearly
Box mybox; // declare reference to object
mybox= new Box(); // allocate a Box object
13
Declaring Objects
14
Figure 1.1 : Declaring Objects Refer From Herbert Shield Complete
Reference Java
Assigning Object Reference Variables
15
Box b1 = new Box();
Box b2 = b1;
You might think that b2 is being assigned a reference to a copy of the object referred to by b1. That
is, you might think that b1 and b2 refer to separate and distinct objects. However, this would be
wrong.
Instead, after this fragment executes, b1 and b2 will both refer to the same object.
The assignment of b1 to b2 did not allocate any memory or copy any part of the original object.
Assigning Object Reference Variables
It simply makes b2 refer to the same object as does b1.
Thus, any changes made to the object through b2 will affect the object to which b1 is referring,
since they are the same object.
16
Figure 1.2 : Assigning Objects Refer From Herbert Shield Complete
Reference Java
The General Form of a Class
A class is declared by use of the class keyword
The data, or variables, defined within a class are called instance variables
The general form of a class definition is shown here
class classname{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
17
A Simple Class Example
Here is a class called Box that defines three instance variables: width, height, and depth
As stated, a class defines a new type of data. In this case, the new data type is calledBox
class Box {
double width;
double height;
double depth;
}
To actually create a Box object, we will use a statement like the following:
Box mybox= new Box(); // create a Box object called mybox
mybox.width= 100; //Assigning the values to the instance variable of Class using (.) operator.
18
Arrays -Introduction
•An array is a group of contiguous or related data items that share a
common name.
•Used when programs have to handle large amount of data
•Each value is stored at a specific position
•Position is called a index or superscript. Base index = 0
•The ability to use a single name to represent a collection of items and
refer to an item by specifying the item number enables us to develop
concise and efficient programs. For example, a loop with index as the
control variable can be used to read the entire array, perform
calculations, and print out the results.
19
Declarationof Arrays
•Like any other variables, arrays must declared and created before they can
be used. Creation of arrays involve three steps:
•Declare the array
•Create storage area in primary memory.
•Put values into the array (i.e., Memory location)
•Declaration of Arrays:
•Form 1:
Type arrayname[]
•Form 2:
•Type [] arrayname;
•Examples:
int[] students;
intstudents[];
•Note: we don’t specify the size of arrays in the declaration.
21
Creation of Arrays
•After declaring arrays, we need to allocate memory for storage
array items.
•In Java, this is carried out by using “new” operator, as follows:
•Arrayname= new type[size];
•Examples:
•students = new int[7];
22
Initialization of Arrays
•Once arrays are created, they need to be initialized with some values
before access their content. A general form of initialisation is:
•Arrayname[index/subscript] = value;
•Example:
•students[0] = 50;
•students[1] = 40;
•Like C, Java creates arrays starting with subscript 0 and ends with
value one less than the size specified.
•Unlike C, Java protects arrays from overruns and under runs. Trying
to access an array beyond its boundaries will generate an error
message.
23
Arrays –Length
•Arrays are fixed length
•Length is specified at create time
•In java, all arrays store the allocated size in a variable named
“length”.
•We can access the length of arrays as arrayName.length:
e.g. intx = students.length; // x = 7
•Accessed using the index
e.g. intx = students [1]; // x = 40
24
Arrays –Example
// StudentArray.java: store integers in arrays and access
public class StudentArray{
public static void main(String[] args) {
intstudents[];
students = new int[7];
System.out.println("Array Length = " + students.length);
for ( inti=0; i< students.length; i++)
students[i] = 2*i;
System.out.println("Values Stored in Array:");
for ( inti=0; i< students.length; i++)
System.out.println(students[i]);
}
}
25
Arrays –Initializing at Declaration
•Arrays can also be initialised like standard variables at the
time of their declaration.
•Type arrayname[] = {list of values};
•Example:
int[] students = {55, 69, 70, 30, 80};
•Creates and initializes the array of integers of length 5.
•In this case it is not necessary to use the new operator.
26
Arrays –Example
// StudentArray.java: store integers in arrays and access
public class StudentArray{
public static void main(String[] args) {
int[] students = {55, 69, 70, 30, 80};
System.out.println("Array Length = " + students.length);
System.out.println("Values Stored in Array:");
for ( inti=0; i< students.length; i++)
System.out.println(students[i]);
}
}
27
Two Dimensional Arrays
•Two dimensional arrays allows us
to store data that are recorded in
table. For example:
•Table contains 12 items, we can
think of this as a matrixconsisting
of 4 rows and 3 columns.
Item1 Item2 Item3
Salesgirl #110 15 30
Salesgirl #214 30 33
Salesgirl #3200 32 1
Salesgirl #410 200 4
28
Sold
Person
Variable Size Arrays
•Java treats multidimensional arrays as “arrays of arrays”. It is possible
to declare a 2D arrays as follows:
•inta[][] = new int[3][];
•a[0]= new int[3];
•a[1]= new int[2];
•a[2]= new int[4];
30
Try: Write a program to Add to Matrix
•Define 2 dimensional matrix variables:
•Say: inta[][], b[][];
•Define their size to be 2x3
•Initialise like some values
•Create a matrix c to storage sum value
•c[0][0] = a[0][0] + b[0][0]
•Print the contents of result matrix.
31
Arrays of Objects
•Arrays can be used to store objects
Circle[] circleArray;
circleArray= new Circle[25];
•The above statement creates an array that can store references to 25
Circle objects.
•Circle objects are not created.
32
Arrays of Objects
•Create the Circle objects and stores them in the array.
//declare an array for 25 Circle objects
Circle circleArray[] = new Circle[25];
intr = 0;
// create circle objects and store in array
for (r=0; r <25; r++)
circleArray[r] = new Circle(r);
33
String Operations in Java
34
String Introduction
•String manipulation is the most common operation performed in Java programs. The
easiest way to represent a String (a sequence of characters)is by using an array of
characters.
Example:
•char place[] = new char[4];
•place[0] = ‘J’;
•place[1] = ‘a’;
•place[2] = ‘v’;
•place[3] = ‘a’;
•Although character arrays have the advantage of being able to query their length, they
themselves are too primitive and don’t support a range of common string operations. For
example, copying a string, searching for specific pattern etc.
•Recognising the importance and common usage of String manipulation in large software
projects, Java supports String as one of the fundamental data type at the language level.
Strings related operations (e.g., end of string) are handled automatically.
35
String Operations in Java
•Following are some useful classes that Java provides for String
operations.
•String Class
•StringBufferClass
•StringTokenizerClass
36
String Class
•String class provides many operations for manipulating strings.
•Constructors
•Utility
•Comparisons
•Conversions
•String objects are read-only (immutable)
37
Strings Basics
•Declaration and Creation syntax:
StringstringName;
stringName= new String (“string value”);
•Example:
String city;
city = new String (“Bangalore”);
•Length of string can be accessed by invoking length() method
defined in String class:
intlen= city.length();
38
String operations and Arrays
•Java Strings can be concatenated using the + operator.
•String city = “New” + “York”;
•String city1 = “Delhi”;
•String city2 = “New “+city1;
•Strings Arrays
•String city[] = new String[5];
•city[0] = new String(“Melbourne”);
•city[1] = new String(“Sydney”);
•…
•String megacities[] = {“Brisbane”, “Sydney”, “Melbourne”,
“Adelaide”, “Perth”};
39
String class -Constructors
40
public String() Constructs an empty String.
Public String(String value)Constructs a new string copying the specified
string.
String –Some useful operations
41
public intlength() Returns the length of the string.
public charAt(int index) Returns the character at the
specified location (index)
public intcompareTo( String
anotherString)
public intcompareToIgnoreCase(
String anotherString)
Compare the Strings.
reigonMatch(int start, String other,
int ostart, int count)
Compares a region of the Strings
with the specified start.
String –Some useful operations
42
public String replace(char oldChar,
char newChar)
Returns a new string with all
instances of the oldChar replaced
with newChar.
public trim() Trims leading and trailing white
spaces.
public String toLowerCase()
public String toUpperCase()
Changes as specified.
String Class -example
43
// StringDemo.java: some operations on strings
class StringDemo{
public static void main(String[] args)
{
String s = new String("Have a nice Day");
// String Length = 15
System.out.println("String Length = " + s.length() );
// Modified String = Have a Good Day
System.out.println("Modified String = " + s.replace('n', 'N'));
// Converted to Uppercse= HAVE A NICE DAY"
System.out.println("Converted to Uppercase = " + s.toUpperCase());
// Converted to Lowercase = have a nice day"
System.out.println("Converted to Lowercase = " + s.toLowerCase());
}
}
StringDemoOutput
•[cmdprompt]:> java StringDemo
String Length = 15
Modified String = Have a Nice Day
Converted to Uppercase = HAVE A NICE DAY
Converted to Lowercase = have a nice day
44
Summary
•Arrays allows grouping of sequence of related items.
•Java supports powerful features for declaring, creating, and
manipulating arrays in efficient ways.
•Each items of arrays of arrays can have same or variable size.
•Java provides enhanced support for manipulating strings and
manipulating them appears similar to manipulating standard data
type variables.
45
Classes and ObjectsinJava
46
Basics of Classes in Java
Introduction
•Java is a true OO language and therefore the underlying structure of all
Java programs is classes.
•Anything we wish to represent in Java must be encapsulated in a class that
defines the “state” and “behavior” of the basic program components known
as objects.
•Classes create objects and objects use methods to communicate between
them. They provide a convenient method for packaging a group of logically
related data items and functions that work on them.
•A class essentially serves as a template for an object and behaves like a
basic data type “int”. It is therefore important to understand how the fields
and methods are defined in a class and how they are used to build a Java
program that incorporates the basic OO concepts such as encapsulation,
inheritance, and polymorphism.
47
Classes
•A classis a collection of fields(data) and methods(procedure or function) that operate
on that fields data.
48
Circle
centre
radius
circumference()
area()
Classes
•A classis a collection of fields(data) and methods(procedure or function)
that operate on that data.
•The basic syntax for a class definition:
•Bare bone class –no fields, no methods
49
public class Circle {
// my circle class
}
classClassName[extends
SuperClassName]
{
[fields declaration]
[methods declaration]
}
Adding Fields: Class Circle with fields
•Add fields
•The fields (data) are also called the instance variables.
50
public class Circle {
public double x, y; // centre coordinate
public double r; // radius of the circle
}
Adding Methods
•A class with only data fields has no life. Objects created by such
a class cannot respond to any messages.
•Methods are declared inside the body of the class but
immediately after the declaration of data fields.
•The general form of a method declaration is:
51
type MethodName (parameter -list)
{
Method-body;
}
Adding Methods to Class Circle
52
public class Circle {
public double x, y; // centre of the circle
public double r; // radius of circle
//Methods to return circumference and area
public double circumference() {
return 2*3.14*r;
}
public double area() {
return 3.14 * r * r;
}
}
Method Body
Data Abstraction
•Declare the Circle class, have created a new data type –Data
Abstraction
•Can define variables (objects) of that type:
Circle aCircle;
Circle bCircle;
53
Class of Circle cont.
•aCircle, bCircle simply refers to a Circle object, not an object itself.
54
aCircle
Points to nothing (Null Reference)
bCircle
Points to nothing (Null Reference)
null null
Creating objects of a class
•Objects are created dynamically using the newkeyword.
•aCircle and bCircle refer to Circle objects
55
bCircle = new Circle() ;aCircle = new Circle() ;
56
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
57
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
P
aCircle
Q
bCircle
Before Assignment
P
aCircle
Q
bCircle
Before Assignment
Automatic garbage collection
•The object does not have a reference and cannot be used in future.
•The object becomes a candidate for automatic garbage collection.
•Java automatically collects garbage periodically and releases the memory used to be
used in the future.
58
Q
Java Object finalize() Method
•Finalize() is the method of Object class. This method is called just before an object is garbage
collected. finalize() method overrides to dispose system resources, perform clean-up activities
and minimize memory leaks.
•Syntax:
protectedvoidfinalize()throwsThrowable
•Throwable-this Exception is raised by this method
59
Example of finalize()
1.classJavafinalizeExample{
2.publicstaticvoidmain(String[]args)
3.{
4. JavafinalizeExampleobj=newJavafinalizeExample();//self obj
5. System.out.println(obj.hashCode());
6. obj=null;//null ref obj
7. //callinggarbagecollector
8. System.gc();
9. System.out.println("endofgarbagecollection");
10.}
11.protectedvoidfinalize()
12.{
13. System.out.println("finalizemethodcalled");
14.}
15.}
60
Sample Output:
2018699554
end of garbage collection
finalize method called
Accessing Object/Circle Data
•Similar to C syntax for accessing data defined in a structure.
61
Circle aCircle = new Circle();
aCircle.x = 2.0 // initialize center and
radius
aCircle.y = 2.0
aCircle.r = 1.0
ObjectName.VariableName
ObjectName.MethodName(parameter -
list)
Executing Methods in Object/Circle
•Using Object Methods:
62
Circle aCircle = new Circle();
double area;
aCircle.r = 1.0;
area = aCircle.area();
sent ‘message’ to aCircle
Using Circle Class
// Circle.java: Contains both Circle class and its user class
//Add Circle class code here
class MyMain
{
public static void main(String args[])
{
Circle aCircle; // creating reference
aCircle= new Circle(); // creating object
aCircle.x= 10; // assigning value to data field
aCircle.y= 20;
aCircle.r= 5;
double area = aCircle.area(); // invoking method
double circumf= aCircle.circumference ();
System.out.println("Radius="+aCircle.r+" Area="+area);
System.out.println("Radius="+aCircle.r+" Circumference
="+circumf);
}
}
63
java MyMain
Radius=5.0 Area=78.5
Radius=5.0 Circumference =31.400000000000002
Summary
•Classes, objects, and methods are the basic components used in Java programming.
•We have discussed:
•How to define a class
•How to create objects
•How to add data fields and methods to classes
•How to access data fields and methods to classes
64
Classes and ObjectsinJava
65
Constructors, Overloading, Static Members, … etc.
Refer to the Earlier Circle Program
66
java MyMain
Radius=5.0 Area=78.5
Radius=5.0 Circumference =31.400000000000002
Better way of Initialising or Access Data Members
x, y, r
•When there too many items to update/access and also to develop a
readable code, generally it is done by defining specific method for
each purpose.
•To initialise/Update a value:
•aCircle.setX( 10 )
•To access a value:
•aCircle.getX()
•These methods are informallycalled as Accessorsor Setters/Getters
Methods.
67
Accessors –“Getters/Setters”
68
How does this code looks ? More readable ?
69
java MyMain
Radius=5.0 Area=78.5
Radius=5.0 Circumference =31.400000000000002
Object Initialization
•When objects are created, the initial value of data fields is unknown unless its
users explicitly do so. For example,
•ObjectName.DataField1 = 0; // OR
•ObjectName.SetDataField1(0);
•In many cases, it makes sense if this initialisationcan be carried out by
default without the users explicitly initializing them.
•For example, if you create an object of the class called “Counter”, it is natural to assume
that the CounterIndexfield is initialized to zero unless otherwise specified differently.
class Counter
{
intCounterIndex;
…
}
Counter counter1 = new Counter();
•What is the value of “counter1.CounterIndex” ?
•In Java, this can be achieved though a mechanism called constructors.
70
What is a Constructor?
•Constructorisaspecialmethodthatgetsinvoked“automatically”
atthetimeofobjectcreation.
•Constructorisnormallyusedforinitializingobjectswithdefault
valuesunlessdifferentvaluesaresupplied.
•Constructorhasthesamenameastheclassname.
•Constructorcannotreturnvalues.
•Aclasscanhavemorethanoneconstructoraslongastheyhave
differentsignature(i.e.,differentinputargumentssyntax).
71
Defining a Constructor
•Like any other method
•Invoking:
•There is NO explicit invocation statement needed: When the object creation statement is executed, the
constructor method will be executed automatically.
72
class ClassName{
// Data Fields…
// Constructor
public ClassName()
{
// Method Body Statements initialising
Data Fields
}
//Methods to manipulate data fields
}
Defining a Constructor: Example
73
public class Counter {
intCounterIndex;
// Constructor
public Counter()
{
CounterIndex= 0;
}
//Methods to update or access counter
public void increase()
{
CounterIndex= CounterIndex+ 1;
}
public void decrease()
{
CounterIndex= CounterIndex-1;
}
intgetCounterIndex()
{
return CounterIndex;
}
}
Trace counter value at each statement and What is the output ?
classMyClass{
public static void main(String args[])
{
Counter counter1 = newCounter();
counter1.increase();
inta = counter1.getCounterIndex();
counter1.increase();
intb = counter1.getCounterIndex();
if( a > b )
counter1.increase();
else
counter1.decrease();
System.out.println(counter1.getCounterIndex());
}
}
74
A Counter with User Supplied Initial Value ?
•This can be done by adding another constructor method to the class.
75
public class Counter {
intCounterIndex;
// Constructor 1
public Counter()
{
CounterIndex= 0;
}
public Counter(intInitValue)
{
CounterIndex= InitValue;
}
}
// A New User Class: Utilising both constructors
Counter counter1 = new Counter();
Counter counter2 = new Counter (10);
Adding a Multiple-Parameters Constructor
to our Circle Class
76
public class Circle {
public double x,y,r;
// Constructor
public Circle(double centreX, double centreY,double radius)
{
x = centreX;
y = centreY;
r = radius;
}
//Methods to return circumference and area
public double circumference() { return 2*3.14*r; }
public double area() { return 3.14 * r * r; }
}
Constructors initialise Objects
•Recall the following OLD Code Segment:
77
Circle aCircle = new Circle();
aCircle.x = 10.0; // initialize center and radius
aCircle.y = 20.0
aCircle.r = 5.0;
aCircle = new Circle() ;
At creation time the center and
radius are not defined.
These values are explicitly set later.
Constructors initialise Objects
•With defined constructor
78
Circle aCircle = new Circle(10.0, 20.0, 5.0);
aCircle = new Circle(10.0, 20.0, 5.0) ;
aCircle is created with center (10, 20)
and radius 5
Multiple Constructors
•Sometimes want to initialize in a number of different ways, depending
on circumstance.
•This can be supported by having multiple constructors having different
input arguments.
79
Multiple Constructors
80
public class Circle {
public double x,y,r; //instance variables
// Constructors
public Circle(double centreX, double cenreY, double radius) {
x = centreX; y = centreY; r = radius;
}
public Circle(double radius) { x=0; y=0; r = radius; }
public Circle() { x=0; y=0; r=1.0; }
//Methods to return circumference and area
public double circumference() { return 2*3.14*r; }
public double area() { return 3.14 * r * r; }
}
Initializing with constructors
81
public class TestCircles {
public static void main(String args[]){
Circle circleA = new Circl e( 10.0, 12.0, 20.0);
Circle circleB= new Circle(10.0);
Circle circleC = new Circle();
}
}
circleA = new Circle(10, 12, 20)circleB = new Circle(10)
Centre = (0,0)
Radius=10
circleC = new Circle()
Centre = (0,0)
Radius = 1
Centre = (10,12)
Radius = 20
Method Overloading
•Constructors all have the same name.
•Methods are distinguished by their signature:
•name
•number of arguments
•type of arguments
•position of arguments
•That means, a class can also have multiple usual methods with the
same name.
•Not to confuse with method overriding (coming up),method
overloading:
82
Polymorphism
•Allows a single methodor operatorassociated
with different meaning depending on the type of
data passed to it. It can be realisedthrough:
•Method Overloading
•Operator Overloading (Supported in C++, but not in
Java)
•Defining the same methodwith different
argument types (method overloading) -
polymorphism.
•The method body can have different logic
depending on the date type of arguments.
83
Scenario
•A Program needs to find a maximum of two numbers or Strings. Write
a separate function for each operation.
•In C:
•int max_int(int a, int b)
•int max_string(char *s1, char *s2)
•max_int (10, 5) or max_string (“melbourne”, “sydney”)
•In Java:
•int max(int a, int b)
•int max(String s1, String s2)
•max(10, 5) or max(“melbourne”, “sydney”)
•Which is better ? Readability and intuitive wise ?
84
A Program with Method Overloading// Compare.java: a class comparing different items
class Compare {
static intmax(inta, intb)
{
if( a > b)
return a;
else
return b;
}
static String max(String a, String b)
{
if( a.compareTo(b) > 0)
return a;
else
return b;
}
public static void main(String args[])
{
String s1 = "Melbourne";
String s2 = "Sydney";
String s3 = "Adelaide";
inta = 10;
intb = 20;
System.out.println(max(a, b)); // which number is big
System.out.println(max(s1, s2)); // which city is big
System.out.println(max(s1, s3)); // which city is big
}
}
85
The thiskeyword
•thiskeywordcanbeusedtorefertotheobjectitself.
Itisgenerallyusedforaccessingclassmembers(fromitsownmethods)
whentheyhavethesamenameasthosepassedasarguments.
public class Circle {
public double x,y,r;
// Constructor
public Circle (double x, double y, double r) {
this.x= x;
this.y= y;
this.r= r;
}
//Methods to return circumference and area
}
86
Static Members
•Java supports definition of global methods and variables that can be
accessed without creating objects of a class. Such members are called
Static members.
•Define a variable by marking with the static.
•This feature is usefulwhen we want to create a variable common to all
instances of a class.
•One of the most common example is to have a variable that could keep a
count of how many objects of a class have been created.
•Note: Java creates only one copy for a static variable which can be used
even if the class is never instantiated.
87
Static Variables
•Define using static:
•Access with the class name (ClassName.StatVarName):
88
class Circle {
// class static variable, one for the Circle class, how many circles
public staticintnumCircles;
//instance variables, one for each instance of a Circle
public double x,y,r;
// Constructors...
}
nCircles = Circle.numCircles;
Static Variables -Example
•Using static variables:
89
class Circle {
// class variable, one for the Circle class, how many circles
private staticintnumCircles= 0;
private double x,y,r;
// Constructors...
Circle (double x, double y, double r){
this.x= x;
this.y= y;
this.r= r;
numCircles++;
}
}
Class Variables -Example
•Using static variables:
90
public class CountCircles {
public static void main(String args[]){
Circle circleA = new Circl e( 10, 12, 20); // numCircles = 1
Circle circleB = new Circl e( 5, 3, 10);// numCircles = 2
}
}
circleA = new Circle(10, 12, 20)circleB = new Circle(5, 3, 10)
numCircles
Instance Vs Static Variables
•Instancevariables : One copy per object.Every object has its
own instance variable.
•E.g. x, y, r (centre and radius in the circle)
•Staticvariables : One copy per class.
•E.g. numCircles (total number of circle objects created)
91
Static Methods
•A class can have methods that are defined as static (e.g., main
method).
•Static methods can be accessed without using objects. Also, there is
NO need to create objects.
•They are prefixed with keyword “static”
•Static methods are generally used to group related library functions
that don’t depend on data members of its class. For example, Math
library functions.
92
Comparator class with Static methods
// Comparator.java: A class with static data items comparisionmethods
class Comparator {
public static intmax(inta, intb)
{
if( a > b)
return a;
else
return b;
}
public static String max(String a, String b)
{
if( a.compareTo(b) > 0)
return a;
else
return b;
}
}
class MyClass{
public static void main(String args[])
{
String s1 = "Melbourne";
String s2 = "Sydney";
String s3 = "Adelaide";
inta = 10;
intb = 20;
System.out.println(Comparator.max(a, b)); // which number is big
System.out.println(Comparator.max(s1, s2)); // which city is big
System.out.println(Comparator.max(s1, s3)); // which city is big
}
}
93
Directly accessed using ClassName (NO Objects)
Static methods restrictions
•They can only call other static methods.
•They can only access static data.
•They cannot refer to “this” or “super” (more on it later) in anyway.
94
Summary
•Constructors allow seamless initialization of objects.
•Classes can have multiple methods with the same name [Overloading]
•Classes can have static members, which serve as global members of all
objects of a class.
•Keywords:constructors, polymorphism, method overloading, this,
static variables, static methods.
95
96
Visibility Control: Data Hiding and Encapsulation
•Java provides control over the visibilityof variables and methods, encapsulation, safely
sealing data within the capsuleof the class
•Prevents programmers from relying on details of class implementation, so you can update
without worry
•Helps in protecting against accidental or wrong usage.
•Keeps code elegant and clean (easier to maintain)
97
Visibility Modifiers: Public, Private, Protected
•Publickeyword applied to a class, makes it available/visible everywhere. Applied
to a method or variable, completely visible.
•Default keyword applied to a class, makes it available/visible everywhere. Applied
to a method or variable, completely visible.
•Default (No visibility modifier is specified): it behaves like public in its package and private in
other packages.
•only within the package. It cannot be accessed from outside the package.
•Privatefields or methods for a class only visible within that class. Private members
are notvisible within subclasses, and are notinherited.
•Protectedmembers of a class are visible within the class, subclasses and also
within all classes that are in the same package as that class.
Visibility/Access Modifiers summary
Access
Modifier
within classwithin packageoutside
package by
subclass only
outside
package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
98
99
Visibility
public class Circle {
private double x,y,r;
// Constructor
publicCircle (double x, double y, double r) {
this.x = x;
this.y = y;
this.r = r;
}
//Methods to return circumference and area
public double circumference() { return 2*3.14*r;}
public double area() { return 3.14 * r * r; }
}
100
Visibility
area
Circle
circumference
Data :
Center (x,y)
Radius r
message
Construction time message
message
Circle
Final Keyword In Java
•Thefinal keywordin java is used to restrict the user.
The java final keyword can be used in many context.
Final can be:
•Variable: If you make any variable as final, you cannot
change the value of final variable(It will be constant).
•Method: If you make any method as final, you cannot
override it.
•Class: If you make any class as final, you cannot extend it.
Options for User Input
•Options for getting information from the user
•Write event-driven code
•Con: requires a significant amount of new code to set-up
•Pro: the most versatile.
•Use System.in
•Con: less versatile then event-driven
•Pro: requires less new code
•Use the command line (String[ ] args)
•Con: very limited in its use
•Pro: the simplest to set up
Using the command line
•Remember what causes the “big bang” in our programs?
public static void main ( String [] args){
•mainexpects an array of strings as a parameter.
•The fact of the matter is that this array has been a null array in each of
our programs so far.
Using the command line
•However, we can give this array values by providing command line
arguments when we start a program running.
$ java MyProgramString1 String2 String3
args[0] args[1] args[2]
Using the command line
•We can use this to get information from the user when the program is started:
public class Echo {
public static void main(String [] args) {
System.out.println(“args[0] is “ + args[0]);
System.out.println(“args[1] is “ + args[1]);
} // end main
} // end Echo class
$ javacEcho.java
$ java Echo Mark Fienup
args[0] is Mark
args[1] is Fienup
output
What are some of the problems with this solution
•This works great if we “behave” and enter two arguments. But what if we don’t enter two arguments?
$ java Echo Mark Alan Fienup
args[0] is Mark
args[1] is Alan
(no problem, but Fienupgets ignored)
$ java Echo Mark
args[0] is Mark
Exception in thread “main”
java.lang.ArrayIndexOutOfBoundsException :
(Big problem!)
Sample output
Sample output
Fixing this problem
•There are several ways to work around this problem
•Use Java’s exception handling mechanism (not ready to talk about this yet)
•Write your own simple check and handle it yourself
public class MyEcho2 {
public static void main( String[] args) {
if (args.length== 2) {
System.out.println("args[0] is ” + args[0]);
System.out.println("args[1] is " + args[1]);
} else {
System.out.println( "Usage: java MyEcho2 "
+ "string1 string2");
} // end if
} // end main
} // end MyEcho2
Fixing this problem
public class MyEcho2 {
public static void main( String[] args) {
if (args.length== 2) {
System.out.println("args[0] is ” + args[0]);
System.out.println("args[1] is " + args[1]);
} else {
System.out.println( "Usage: java MyEcho2 " + "string1 string2");
} // end if
} // end main
} // end MyEcho2
$ java MyEcho2 Mark
Usage: java MyEcho2 string1 string2
$ java MyEcho2 Mark Alan Fienup
Usage: java MyEcho2 string1 string2
Sample output