KEMBAR78
principles of proramming language in cppg | PDF
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".*/
The first thing that you must learn about Java is that the name you give to a source file is very
important (same as classname where main() method is present). For this example, the name of
the source file should be Example.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 :-member may be accessed by code outside the class in which it is declared.
private:- which prevents a member from being used by code defined outside of its class.
static :-static allows main( ) to be called without having to instantiate a particular instance of the
class. This is necessary since main( ) is called by the Java interpreter before any objects are
made.
void :- void simply tells the compiler that main( ) does not return a value.
3
A First Simple Program
main :- main( ) is the method called when a Java application begins. Java is case-sensitive. Thus,
Main is different from main. It is important to understand that the Java compiler will compile
classes that do not contain a main( ) method. But the Java interpreter has no way to run these
classes.
String args[ ] :- declares a parameter named args, which is an array of instances of the class
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 object is 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. Kanetkar is an object of class Professor. The Kanetkar object 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
 Behavior determines how an object acts and reacts.
 The visible behavior of an object is modeled by the set of messages/methods it can
respond to (operations the object can perform)
Professor Kanetkar’s Behavior :
Submit Final Grades()
Accept Course Offerings()
Get a vacation()
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 Kanetkar is from Nagpur. Even if there is a professor with the same name –
Kanetkar in 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 & behavior of each object in the class
• Attributes of a Class
 An attribute is a named property of a class that describes a range of values that instances of the
property may hold.
 A class may have any number of attributes or no attributes at all.
 An attribute has a type, which tells us what kind of attribute it is.
 Typically attributes are integer, boolean, varchar etc.
 These are called primitive types. Primitive types can be specific for a certain programming language.
11
• Operations of a Class - is the implementation of a service that can be requested from
any object of the class to affect behavior
 A class may have any number of operations or none at all.
 The operations in a class describe what class can do.
 The operation is described with a return-type, name, zero or more parameters. This
is know as signature of an operation.
 Often, but not always, invoking an operation on an object changes the object’s data
or state.
12
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 ObjectsRefer 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
Arrays - Introduction
20
• students[]
69
61
70
89
23
10
9
0
1
2
3
4
5
6
index
values
Declaration of 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;
int students[];
• 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. int x = students.length; // x = 7
•Accessed using the index
e.g. int x = students [1]; // x = 40
24
Arrays – Example
// StudentArray.java: store integers in arrays and access
public class StudentArray{
public static void main(String[] args) {
int students[];
students = new int[7];
System.out.println("Array Length = " + students.length);
for ( int i=0; i < students.length; i++)
students[i] = 2*i;
System.out.println("Values Stored in Array:");
for ( int i=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 ( int i=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 matrix consisting
of 4 rows and 3 columns.
Item1 Item2 Item3
Salesgirl #1 10 15 30
Salesgirl #2 14 30 33
Salesgirl #3 200 32 1
Salesgirl #4 10 200 4
28
Sold
Person
2D arrays manipulations
•Declaration:
• int myArray [][];
•Creation:
• myArray = new int[4][3]; // OR
• int myArray [][] = new int[4][3]; //declare and create
•Initialisation:
• Single Value;
• myArray[0][0] = 10;
• Multiple values:
• int tableA[2][3] = {{10, 15, 30}, {14, 30, 33}};
• int tableA[][] = {{10, 15, 30}, {14, 30, 33}};
29
Variable Size Arrays
•Java treats multidimensional arrays as “arrays of arrays”. It is possible
to declare a 2D arrays as follows:
• int a[][] = 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: int a[][], 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];
int r = 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
•StringBuffer Class
•StringTokenizer Class
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:
String stringName;
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:
int len = 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 int length() Returns the length of the string.
public charAt(int index) Returns the character at the
specified location (index)
public int compareTo( String
anotherString)
public int compareToIgnoreCase(
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());
}
}
StringDemo Output
•[cmd prompt]:> 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 Objects in Java
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 class is a collection of fields (data) and methods (procedure or function) that operate
on that fields data.
48
Circle
centre
radius
circumference()
area()
Classes
• A class is 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
}
class ClassName [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 new keyword.
• 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:
protected void finalize() throws Throwable
• Throwable - this Exception is raised by this method
59
Example of finalize()
1. class JavafinalizeExample {
2. public static void main(String[] args)
3. {
4. JavafinalizeExample obj = new JavafinalizeExample(); //self obj
5. System.out.println(obj.hashCode());
6. obj = null; //null ref obj
7. // calling garbage collector
8. System.gc();
9. System.out.println("end of garbage collection");
10. }
11. protected void finalize()
12. {
13. System.out.println("finalize method called");
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 Objects in Java
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 informally called as Accessors or 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 initialisation can 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 CounterIndex field is initialized to zero unless otherwise specified differently.
class Counter
{
int CounterIndex;
…
}
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?
•Constructor is a special method that gets invoked “automatically”
at the time of object creation.
•Constructor is normally used for initializing objects with default
values unless different values are supplied.
•Constructor has the same name as the class name.
•Constructor cannot return values.
•A class can have more than one constructor as long as they have
different signature (i.e., different input arguments syntax).
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 {
int CounterIndex;
// Constructor
public Counter()
{
CounterIndex = 0;
}
//Methods to update or access counter
public void increase()
{
CounterIndex = CounterIndex + 1;
}
public void decrease()
{
CounterIndex = CounterIndex - 1;
}
int getCounterIndex()
{
return CounterIndex;
}
}
Trace counter value at each statement and What is the output ?
class MyClass {
public static void main(String args[])
{
Counter counter1 = new Counter();
counter1.increase();
int a = counter1.getCounterIndex();
counter1.increase();
int b = 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 {
int CounterIndex;
// Constructor 1
public Counter()
{
CounterIndex = 0;
}
public Counter(int InitValue )
{
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 Circle( 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 method or operator associated
with different meaning depending on the type of
data passed to it. It can be realised through:
• Method Overloading
• Operator Overloading (Supported in C++, but not in
Java)
•Defining the same method with 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 int max(int a, int b)
{
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";
int a = 10;
int b = 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 this keyword
• this keyword can be used to refer to the object itself.
It is generally used for accessing class members (from its own methods)
when they have the same name as those passed as arguments.
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 useful when 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 static int numCircles;
//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 static int numCircles = 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 Circle( 10, 12, 20); // numCircles = 1
Circle circleB = new Circle( 5, 3, 10);// numCircles = 2
}
}
circleA = new Circle(10, 12, 20) circleB = new Circle(5, 3, 10)
numCircles
Instance Vs Static Variables
• Instance variables : One copy per object. Every object has its
own instance variable.
• E.g. x, y, r (centre and radius in the circle)
• Static variables : 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 comparision methods
class Comparator {
public static int max(int a, int b)
{
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";
int a = 10;
int b = 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 visibility of variables and methods, encapsulation, safely
sealing data within the capsule of 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
• Public keyword 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.
• Private fields or methods for a class only visible within that class. Private members
are not visible within subclasses, and are not inherited.
• Protected members 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 class within package outside
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
public Circle (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
•The final keyword in 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) {
• main expects 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 MyProgram String1 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
$ javac Echo.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 Fienup gets 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

principles of proramming language in cppg

  • 1.
    Unit 3: Javaas Object Oriented Programming Language- Overview Arrays, Strings, Classes and Methods 1
  • 2.
    A First SimpleProgram /*This is a simple Java program. Name this file "Example.java".*/ The first thing that you must learn about Java is that the name you give to a source file is very important (same as classname where main() method is present). For this example, the name of the source file should be Example.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."); } }
  • 3.
    A First SimpleProgram public :-member may be accessed by code outside the class in which it is declared. private:- which prevents a member from being used by code defined outside of its class. static :-static allows main( ) to be called without having to instantiate a particular instance of the class. This is necessary since main( ) is called by the Java interpreter before any objects are made. void :- void simply tells the compiler that main( ) does not return a value. 3
  • 4.
    A First SimpleProgram main :- main( ) is the method called when a Java application begins. Java is case-sensitive. Thus, Main is different from main. It is important to understand that the Java compiler will compile classes that do not contain a main( ) method. But the Java interpreter has no way to run these classes. String args[ ] :- declares a parameter named args, which is an array of instances of the class String. 4
  • 5.
    A First SimpleProgram 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.
  • 6.
    What is aClass ? A class is a description of a set of objects that share the same attributes, operations. An object is an instance of class. A class is an abstraction in which it  Emphasizes relevant characteristics  Suppresses other characteristics 6
  • 7.
    What is anObject ? • 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
  • 8.
    What is anObject ? • 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. Kanetkar is an object of class Professor. The Kanetkar object has state: Name=Kanetkar Employee Id=2001 Hire date=02/02/1995 Status=Tenured (Occupied) Max Load=3 8
  • 9.
    What is anObject ? • Object has Behavior  Behavior determines how an object acts and reacts.  The visible behavior of an object is modeled by the set of messages/methods it can respond to (operations the object can perform) Professor Kanetkar’s Behavior : Submit Final Grades() Accept Course Offerings() Get a vacation() 9
  • 10.
    What is anObject ? • 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 Kanetkar is from Nagpur. Even if there is a professor with the same name – Kanetkar in Pune teaching C++, they both are distinct objects 10
  • 11.
    A Relationship BetweenClasses & 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 & behavior of each object in the class • Attributes of a Class  An attribute is a named property of a class that describes a range of values that instances of the property may hold.  A class may have any number of attributes or no attributes at all.  An attribute has a type, which tells us what kind of attribute it is.  Typically attributes are integer, boolean, varchar etc.  These are called primitive types. Primitive types can be specific for a certain programming language. 11
  • 12.
    • Operations ofa Class - is the implementation of a service that can be requested from any object of the class to affect behavior  A class may have any number of operations or none at all.  The operations in a class describe what class can do.  The operation is described with a return-type, name, zero or more parameters. This is know as signature of an operation.  Often, but not always, invoking an operation on an object changes the object’s data or state. 12
  • 13.
    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
  • 14.
    Declaring Objects 14 Figure 1.1: Declaring Objects Refer From Herbert Shield Complete Reference Java
  • 15.
    Assigning Object ReferenceVariables 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.
  • 16.
    Assigning Object ReferenceVariables 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 ObjectsRefer From Herbert Shield Complete Reference Java
  • 17.
    The General Formof 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
  • 18.
    A Simple ClassExample 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
  • 19.
    Arrays - Introduction •Anarray 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
  • 20.
    Arrays - Introduction 20 •students[] 69 61 70 89 23 10 9 0 1 2 3 4 5 6 index values
  • 21.
    Declaration of Arrays •Likeany 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; int students[]; • Note: we don’t specify the size of arrays in the declaration. 21
  • 22.
    Creation of Arrays •Afterdeclaring 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
  • 23.
    Initialization of Arrays •Oncearrays 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
  • 24.
    Arrays – Length •Arraysare 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. int x = students.length; // x = 7 •Accessed using the index e.g. int x = students [1]; // x = 40 24
  • 25.
    Arrays – Example //StudentArray.java: store integers in arrays and access public class StudentArray{ public static void main(String[] args) { int students[]; students = new int[7]; System.out.println("Array Length = " + students.length); for ( int i=0; i < students.length; i++) students[i] = 2*i; System.out.println("Values Stored in Array:"); for ( int i=0; i < students.length; i++) System.out.println(students[i]); } } 25
  • 26.
    Arrays – Initializingat 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
  • 27.
    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 ( int i=0; i < students.length; i++) System.out.println(students[i]); } } 27
  • 28.
    Two Dimensional Arrays •Twodimensional arrays allows us to store data that are recorded in table. For example: •Table contains 12 items, we can think of this as a matrix consisting of 4 rows and 3 columns. Item1 Item2 Item3 Salesgirl #1 10 15 30 Salesgirl #2 14 30 33 Salesgirl #3 200 32 1 Salesgirl #4 10 200 4 28 Sold Person
  • 29.
    2D arrays manipulations •Declaration: •int myArray [][]; •Creation: • myArray = new int[4][3]; // OR • int myArray [][] = new int[4][3]; //declare and create •Initialisation: • Single Value; • myArray[0][0] = 10; • Multiple values: • int tableA[2][3] = {{10, 15, 30}, {14, 30, 33}}; • int tableA[][] = {{10, 15, 30}, {14, 30, 33}}; 29
  • 30.
    Variable Size Arrays •Javatreats multidimensional arrays as “arrays of arrays”. It is possible to declare a 2D arrays as follows: • int a[][] = new int [3][]; • a[0]= new int [3]; • a[1]= new int [2]; • a[2]= new int [4]; 30
  • 31.
    Try: Write aprogram to Add to Matrix •Define 2 dimensional matrix variables: • Say: int a[][], 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
  • 32.
    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
  • 33.
    Arrays of Objects •Createthe Circle objects and stores them in the array. //declare an array for 25 Circle objects Circle circleArray[] = new Circle[25]; int r = 0; // create circle objects and store in array for (r=0; r <25; r++) circleArray[r] = new Circle(r); 33
  • 34.
  • 35.
    String Introduction • Stringmanipulation 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
  • 36.
    String Operations inJava •Following are some useful classes that Java provides for String operations. •String Class •StringBuffer Class •StringTokenizer Class 36
  • 37.
    String Class •String classprovides many operations for manipulating strings. •Constructors •Utility •Comparisons •Conversions •String objects are read-only (immutable) 37
  • 38.
    Strings Basics •Declaration andCreation syntax: String stringName; 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: int len = city.length(); 38
  • 39.
    String operations andArrays •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
  • 40.
    String class -Constructors 40 public String() Constructs an empty String. Public String(String value) Constructs a new string copying the specified string.
  • 41.
    String – Someuseful operations 41 public int length() Returns the length of the string. public charAt(int index) Returns the character at the specified location (index) public int compareTo( String anotherString) public int compareToIgnoreCase( String anotherString) Compare the Strings. reigonMatch(int start, String other, int ostart, int count) Compares a region of the Strings with the specified start.
  • 42.
    String – Someuseful 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.
  • 43.
    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()); } }
  • 44.
    StringDemo Output •[cmd prompt]:>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
  • 45.
    Summary •Arrays allows groupingof 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
  • 46.
    Classes and Objectsin Java 46 Basics of Classes in Java
  • 47.
    Introduction • Java isa 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
  • 48.
    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()
  • 49.
    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 } class ClassName [extends SuperClassName] { [fields declaration] [methods declaration] }
  • 50.
    Adding Fields: ClassCircle 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 }
  • 51.
    Adding Methods • Aclass 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; }
  • 52.
    Adding Methods toClass 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
  • 53.
    Data Abstraction • Declarethe Circle class, have created a new data type – Data Abstraction • Can define variables (objects) of that type: Circle aCircle; Circle bCircle; 53
  • 54.
    Class of Circlecont. • 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
  • 55.
    Creating objects ofa class • Objects are created dynamically using the new keyword. • aCircle and bCircle refer to Circle objects 55 bCircle = new Circle() ; aCircle = new Circle() ;
  • 56.
    56 Creating objects ofa class aCircle = new Circle(); bCircle = new Circle() ; bCircle = aCircle;
  • 57.
    57 Creating objects ofa class aCircle = new Circle(); bCircle = new Circle() ; bCircle = aCircle; P aCircle Q bCircle Before Assignment P aCircle Q bCircle Before Assignment
  • 58.
    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
  • 59.
    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: protected void finalize() throws Throwable • Throwable - this Exception is raised by this method 59
  • 60.
    Example of finalize() 1.class JavafinalizeExample { 2. public static void main(String[] args) 3. { 4. JavafinalizeExample obj = new JavafinalizeExample(); //self obj 5. System.out.println(obj.hashCode()); 6. obj = null; //null ref obj 7. // calling garbage collector 8. System.gc(); 9. System.out.println("end of garbage collection"); 10. } 11. protected void finalize() 12. { 13. System.out.println("finalize method called"); 14. } 15. } 60 Sample Output: 2018699554 end of garbage collection finalize method called
  • 61.
    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)
  • 62.
    Executing Methods inObject/Circle • Using Object Methods: 62 Circle aCircle = new Circle(); double area; aCircle.r = 1.0; area = aCircle.area(); sent ‘message’ to aCircle
  • 63.
    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
  • 64.
    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
  • 65.
    Classes and Objectsin Java 65 Constructors, Overloading, Static Members, … etc.
  • 66.
    Refer to theEarlier Circle Program 66 java MyMain Radius=5.0 Area=78.5 Radius=5.0 Circumference =31.400000000000002
  • 67.
    Better way ofInitialising 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 informally called as Accessors or Setters/Getters Methods. 67
  • 68.
  • 69.
    How does thiscode looks ? More readable ? 69 java MyMain Radius=5.0 Area=78.5 Radius=5.0 Circumference =31.400000000000002
  • 70.
    Object Initialization • Whenobjects 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 initialisation can 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 CounterIndex field is initialized to zero unless otherwise specified differently. class Counter { int CounterIndex; … } Counter counter1 = new Counter(); • What is the value of “counter1.CounterIndex” ? • In Java, this can be achieved though a mechanism called constructors. 70
  • 71.
    What is aConstructor? •Constructor is a special method that gets invoked “automatically” at the time of object creation. •Constructor is normally used for initializing objects with default values unless different values are supplied. •Constructor has the same name as the class name. •Constructor cannot return values. •A class can have more than one constructor as long as they have different signature (i.e., different input arguments syntax). 71
  • 72.
    Defining a Constructor •Likeany 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 }
  • 73.
    Defining a Constructor:Example 73 public class Counter { int CounterIndex; // Constructor public Counter() { CounterIndex = 0; } //Methods to update or access counter public void increase() { CounterIndex = CounterIndex + 1; } public void decrease() { CounterIndex = CounterIndex - 1; } int getCounterIndex() { return CounterIndex; } }
  • 74.
    Trace counter valueat each statement and What is the output ? class MyClass { public static void main(String args[]) { Counter counter1 = new Counter(); counter1.increase(); int a = counter1.getCounterIndex(); counter1.increase(); int b = counter1.getCounterIndex(); if ( a > b ) counter1.increase(); else counter1.decrease(); System.out.println(counter1.getCounterIndex()); } } 74
  • 75.
    A Counter withUser Supplied Initial Value ? • This can be done by adding another constructor method to the class. 75 public class Counter { int CounterIndex; // Constructor 1 public Counter() { CounterIndex = 0; } public Counter(int InitValue ) { CounterIndex = InitValue; } } // A New User Class: Utilising both constructors Counter counter1 = new Counter(); Counter counter2 = new Counter (10);
  • 76.
    Adding a Multiple-ParametersConstructor 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; } }
  • 77.
    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.
  • 78.
    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
  • 79.
    Multiple Constructors • Sometimeswant to initialize in a number of different ways, depending on circumstance. • This can be supported by having multiple constructors having different input arguments. 79
  • 80.
    Multiple Constructors 80 public classCircle { 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; } }
  • 81.
    Initializing with constructors 81 publicclass TestCircles { public static void main(String args[]){ Circle circleA = new Circle( 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
  • 82.
    Method Overloading •Constructors allhave 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
  • 83.
    Polymorphism •Allows a singlemethod or operator associated with different meaning depending on the type of data passed to it. It can be realised through: • Method Overloading • Operator Overloading (Supported in C++, but not in Java) •Defining the same method with different argument types (method overloading) - polymorphism. •The method body can have different logic depending on the date type of arguments. 83
  • 84.
    Scenario •A Program needsto 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
  • 85.
    A Program withMethod Overloading // Compare.java: a class comparing different items class Compare { static int max(int a, int b) { 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"; int a = 10; int b = 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
  • 86.
    The this keyword •this keyword can be used to refer to the object itself. It is generally used for accessing class members (from its own methods) when they have the same name as those passed as arguments. 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
  • 87.
    Static Members • Javasupports 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 useful when 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
  • 88.
    Static Variables • Defineusing static: • Access with the class name (ClassName.StatVarName): 88 class Circle { // class static variable, one for the Circle class, how many circles public static int numCircles; //instance variables, one for each instance of a Circle public double x,y,r; // Constructors... } nCircles = Circle.numCircles;
  • 89.
    Static Variables -Example • Using static variables: 89 class Circle { // class variable, one for the Circle class, how many circles private static int numCircles = 0; private double x,y,r; // Constructors... Circle (double x, double y, double r){ this.x = x; this.y = y; this.r = r; numCircles++; } }
  • 90.
    Class Variables -Example • Using static variables: 90 public class CountCircles { public static void main(String args[]){ Circle circleA = new Circle( 10, 12, 20); // numCircles = 1 Circle circleB = new Circle( 5, 3, 10);// numCircles = 2 } } circleA = new Circle(10, 12, 20) circleB = new Circle(5, 3, 10) numCircles
  • 91.
    Instance Vs StaticVariables • Instance variables : One copy per object. Every object has its own instance variable. • E.g. x, y, r (centre and radius in the circle) • Static variables : One copy per class. • E.g. numCircles (total number of circle objects created) 91
  • 92.
    Static Methods •A classcan 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
  • 93.
    Comparator class withStatic methods // Comparator.java: A class with static data items comparision methods class Comparator { public static int max(int a, int b) { 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"; int a = 10; int b = 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)
  • 94.
    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
  • 95.
    Summary •Constructors allow seamlessinitialization 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.
    96 Visibility Control: DataHiding and Encapsulation • Java provides control over the visibility of variables and methods, encapsulation, safely sealing data within the capsule of 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.
    97 Visibility Modifiers: Public,Private, Protected • Public keyword 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. • Private fields or methods for a class only visible within that class. Private members are not visible within subclasses, and are not inherited. • Protected members of a class are visible within the class, subclasses and also within all classes that are in the same package as that class.
  • 98.
    Visibility/Access Modifiers summary Access Modifier withinclass within package outside 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.
    99 Visibility public class Circle{ private 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 public double circumference() { return 2*3.14*r;} public double area() { return 3.14 * r * r; } }
  • 100.
    100 Visibility area Circle circumference Data : Center (x,y) Radiusr message Construction time message message Circle
  • 101.
    Final Keyword InJava •The final keyword in 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.
  • 102.
    Options for UserInput • 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
  • 103.
    Using the commandline • Remember what causes the “big bang” in our programs? public static void main (String [] args) { • main expects 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.
  • 104.
    Using the commandline • However, we can give this array values by providing command line arguments when we start a program running. $ java MyProgram String1 String2 String3 args[0] args[1] args[2]
  • 105.
    Using the commandline • 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 $ javac Echo.java $ java Echo Mark Fienup args[0] is Mark args[1] is Fienup  output
  • 106.
    What are someof 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 Fienup gets ignored) $ java Echo Mark args[0] is Mark Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: (Big problem!)  Sample output  Sample output
  • 107.
    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
  • 108.
    Fixing this problem publicclass 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