Professional Documents
Culture Documents
3
Defining Methods
A method is a collection of statements that are
grouped together to perform an operation.
4
Defining Methods
A method is a collection of statements that are
grouped together to perform an operation.
5
Pass by Value
6
Exercise: Converting Hexadecimals to
Decimals
7
Solution
8
9
Overloading Methods
Overloading methods enables you to define the methods with
the same name as long as their signatures are different.
10
11
Objects and Classes
12
OO Programming Concepts
Object-oriented programming (OOP) involves
programming using objects. An object represents an
entity in the real world that can be distinctly
identified. For example, a student, a desk, a circle, a
button, and even a loan can all be viewed as objects.
An object has a unique identity, state, and behaviors.
The state of an object consists of a set of data fields
(also known as properties) with their current values.
The behavior of an object is defined by a set of
methods.
13
Objects
14
Classes
Classes are constructs that define objects of the
same type. A Java class uses variables to define
data fields and methods to define behaviors.
Additionally, a class provides a special type of
methods, known as constructors, which are
invoked to construct objects from the class.
15
Classes
16
Unified Modeling Language (UML)
Class Diagram
17
Example: Defining Classes and
Creating Objects
18
19
20
21
Example: Defining Classes and Creating Objects
22
23
24
25
Constructors
Constructors are a special kind of methods that are invoked to
construct objects.
Circle() {
}
Circle(double newRadius) {
radius = newRadius;
}
26
Constructors, cont.
A constructor with no parameters is referred to as a no-
arg constructor.
Constructors must have the same name as the class
itself.
Constructors do not have a return type—not even
void.
Constructors are invoked using the new operator
when an object is created. Constructors play the role
of initializing objects.
27
Creating Objects Using Constructors
new ClassName();
Example:
new Circle();
new Circle(5.0);
28
Default Constructor
A class may be defined without constructors. In
this case, a no-arg constructor with an empty
body is implicitly defined in the class.
This constructor, called a default constructor, is
provided automatically only if no constructors
are explicitly defined in the class.
29
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n; }
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a; }
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
} 30
Destructor
The destructor is the opposite of the constructor.
The constructor is used to initialize objects while the destructor is
used to delete or destroy the object that releases the resource
occupied by the object.
Remember that there is no concept of destructor in Java. In place
of the destructor, Java provides the garbage collector that works
the same as the destructor.
The garbage collector is a program (thread) that runs on the JVM
It is difficult for the programmer to forcefully execute the garbage
collector to destroy the object. Alternatively, the Java Object class
provides the finalize() method that works the same as the
destructor.
31
Garbage Collection
TIP: If you know that an object is no longer needed, you can
explicitly assign null to a reference variable for the object. The
JVM will automatically collect the space if the object is not
referenced by any variable.
32
public class DestructorExample
{
public static void main(String[] args)
{
DestructorExample de = new DestructorExample ();
de.finalize();
de = null;
System.gc();
System.out.println("Inside the main() method");
}
protected void finalize()
{
System.out.println("Object is destroyed GC");
}
}
33
Declaring Object Reference Variables
To reference an object, assign the object to a
reference variable.
ClassName objectRefVar;
Example:
Circle myCircle;
34
Declaring/Creating Objects
in a Single Step
ClassName objectRefVar = new ClassName();
35
Accessing Object’s Members
Referencing the object’s data:
objectRefVar.data
e.g., myCircle.radius
36
Caution
Recall that you use
Math.methodName(arguments) (e.g., Math.pow(3, 2.5))
37
Reference Data Fields
The data fields can be of reference types. For example, the
following Student class contains a data field name of the String
type.
public class Student {
String name;
// name has default value null
int age;
// age has default value 0
boolean isScienceMajor;
// isScienceMajor has default value false
char gender;
// c has default value '\u0000'
}
38
The null Value
If a data field of a reference type does not
reference any object, the data field holds a
special literal value, null.
39
Default Value for a Data Field
The default value of a data field is null for a
reference type, 0 for a numeric type, false for a
boolean type, and '\u0000' for a char type.
However, Java assigns no default value to a local
variable inside a method.
public class Test {
public static void main(String[] args) {
Student student = new Student();
System.out.println("name? " + student.name);
System.out.println("age? " + student.age);
System.out.println("isScienceMajor? " + student.isScienceMajor);
System.out.println("gender? " + student.gender);
}
}
40
Example
Java assigns no default value to a local variable inside a
method.
41
Differences between Variables of
Primitive Data Types and Object Types
42
Copying Variables of Primitive
Data Types and Object Types
43
The Date Class
Java provides a system-independent encapsulation of date
and time in the java.util.Date class. You can use the Date
class to create an instance for the current date and time and
use its toString method to return the date and time as a string.
44
The Date Class Example
For example, the following code
java.util.Date date = new java.util.Date();
System.out.println(date.toString());
45
Input
import java.util.Date;
public class DateDemo {
Output
on May 04 09:51:52 CDT 2009
46
// Program to demonstrate methods of Date class
import java.util.*;
public class Main
{
public static void main(String[] args)
{
// Creating date
Date d1 = new Date(2000, 11, 21);
Date d2 = new Date(); // Current date
Date d3 = new Date(2010, 1, 3);
boolean a = d3.after(d1);
System.out.println("Date d3 comes after " + "date d2: " + a);
boolean b = d3.before(d2);
System.out.println("Date d3 comes before "+ "date d2: " + b);
int c = d1.compareTo(d2);
System.out.println(c);
System.out.println("Miliseconds from Jan 1 "+ "1970 to date d1 is " +
d1.getTime());
System.out.println("Before setting "+d2);
d2.setTime(204587433443L);
System.out.println("After setting "+d2);
}
}
47
The Random Class
You have used Math.random() to obtain a random double
value between 0.0 and 1.0 (excluding 1.0). A more useful
random number generator is provided in the java.util.Random
class.
48
The Random Class Example
If two Random objects have the same seed, they will generate
identical sequences of numbers. For example, the following
code creates two Random objects with the same seed 3.
Random random1 = new Random(3);
System.out.print("From random1: ");
for (int i = 0; i < 10; i++)
System.out.print(random1.nextInt(1000) + " ");
Random random2 = new Random(3);
System.out.print("\nFrom random2: ");
for (int i = 0; i < 10; i++)
System.out.print(random2.nextInt(1000) + " ");
From random1: 734 660 210 581 128 202 549 564 459 961
From random2: 734 660 210 581 128 202 549 564 459 961
49
import java.util.Random;
public class JavaRandomExample1 {
public static void main(String[] args) {
//create random object
Random random= new Random();
//returns unlimited stream of pseudorandom long values
System.out.println("Longs value : "+random.longs());
// Returns the next pseudorandom boolean value
boolean val = random.nextBoolean();
System.out.println("Random boolean value : "+val);
byte[] bytes = new byte[10];
//generates random bytes and put them in an array
random.nextBytes(bytes);
System.out.print("Random bytes = ( ");
for(int i = 0; i< bytes.length; i++)
{
System.out.printf("%d ", bytes[i]);
}
System.out.print(")");
}
}
50
The Point2D Class
Java API has a conveninent Point2D class in the
javafx.geometry package for representing a point in a two-
dimensional plane.
51
52
Instance Variables, and Methods
Instance variables belong to a specific instance.
53
Static Member
To create a static member (block, variable, method,
nested class), you need to precede its declaration with
the keyword static.
When a member of the class is declared as static, it
can be accessed before the objects of its class are
created, and without any object reference.
static keyword is a non-access modifier and can be
used for the following:
Static Block
Static Variable
Static Method
Static Classes
54
Static Block
// Java program to demonstrate the use of static blocks
import java.util.*;
public class BlockExample{ Output
// static variable Static block initialized
static int j = 10; Inside main method
static int n; Value of j:10
// static block Value of n : 80
static {
System.out.println("Static block initialized.");
n = j * 8;
}
public static void main(String[] args)
{
System.out.println("Inside main method");
System.out.println("Value of j : "+j);
System.out.println("Value of n : "+n);
}
}
55
Static Variables
// Java program demonstrate execution of static blocks and variables
import java.util.*;
public class VariableExample Output
{ from n
// static variable
Inside the static block
static int j = n();
// static block Value of j: 20
static { Inside main method
System.out.println("Inside the static block");
}
// static method
static int n() {
System.out.println("from n ");
return 20;
}
// static method(main !!)
public static void main(String[] args)
{
System.out.println("Value of j : "+j);
System.out.println("Inside main method");
}
}
56
Static Methods
void getStudentInfo()
{
System.out.println("name : " +
// static keyword with methods and variables
this.name);
// Student class System.out.println("rollNo : " +
class Student { this.rollNo);
String name; // accessing static variable
int rollNo; System.out.println("cllgName : " +
// static variable cllgName);
}
static String cllgName;
}
// static counter to set unique roll no // Driver class
static int counter = 0; public class StaticDemo {
public Student(String name) public static void main(String[] args)
{ {
this.name = name; // calling static method
// without instantiating Student class
this.rollNo = setRollNo();
Student.setCllg("XYZ");
}
// getting unique rollNo Student s1 = new Student("Alice");
// through static variable(counter) Student s2 = new Student("Bob");
static int setRollNo()
{ s1.getStudentInfo();
s2.getStudentInfo();
counter++;
}
return counter; }
}
// static method
static void setCllg(String name) { cllgName = name; }
// instance method
57
Static Class
// A java program to demonstrate use of static keyword with Classes
import java.io.*;
public class SMEC {
private static String str = “Welcome SMEC-VIT";
// Static class
static class MyNestedClass {
// non-static method
public void disp(){
System.out.println(str);
}
}
public static void main(String args[])
{
SMEC.MyNestedClass obj = new SMEC.MyNestedClass();
obj.disp();
}
}
58
Visibility Modifiers
59
Visibility Modifiers and
Accessor/Mutator Methods
By default, the class, variable, or method can be
accessed by any class in the same package.
public
The class, data, or method is visible to any class in any
package.
private
The data or methods can be accessed only by the declaring
class.
The get and set methods are used to read and modify private
properties.
60
The private modifier restricts access to within a class, the default
modifier restricts access to within a package, and the public
modifier enables unrestricted access.
61
The default modifier on a class restricts access to within a package,
and the public modifier enables unrestricted access.
62
NOTE
An object cannot access its private members, as shown in (b).
It is OK, however, if the object is declared in its own class, as
shown in (a).
63
Why Data Fields Should Be
private?
To protect data.
64
Example of
Data Field Encapsulation
65
Passing Objects to Methods
Passing by value for primitive type value
(the value is passed to the parameter)
Passing by value for reference type value
(the value is the reference to the object)
66
Passing Objects to Methods, cont.
67
Array of Objects
Circle[] circleArray = new Circle[10];
69
Array of Objects, cont.
public class TotalArea {
/** Main method */
public static void main(String[] args) {
// Declare circleArray
CircleWithPrivateDataFields[] circleArray;
// Create circleArray
circleArray = createCircleArray();
// Print circleArray and total areas of the circles
printCircleArray(circleArray);
}
/** Create an array of Circle objects */
public static CircleWithPrivateDataFields[] createCircleArray() {
CircleWithPrivateDataFields[] circleArray =
new CircleWithPrivateDataFields[5];
A class with all private data fields and without mutators is not
necessarily immutable. For example, the following class
Student has all private data fields and no mutators, but it is
mutable.
72
Example public class BirthDate {
private int year;
public class Student {
private int month;
private int id;
private BirthDate birthDate; private int day;
73
What Class is Immutable?
For a class to be immutable, it must mark all data fields private
and provide no mutator methods and no accessor methods that
would return a reference to a mutable data field object.
74
Scope of Variables
The scope of instance and static variables is the
entire class. They can be declared anywhere inside
a class.
The scope of a local variable starts from its
declaration and continues to the end of the block
that contains the variable. A local variable must be
initialized explicitly before it can be used.
75
The this Keyword
The this keyword is the name of a reference that
refers to an object itself. One common use of the
this keyword is reference a class’s hidden data
fields.
Another common use of the this keyword to
enable a constructor to invoke another
constructor of the same class.
76
Reference the Hidden Data Fields
77
Calling Overloaded Constructor
78