Java Unit 1.3 (Classes)
Java Unit 1.3 (Classes)
1
Introduction
Java is a true OO language and therefore the
underlying structure of all Java programs is classes.
2
Classes
A class is a collection of Objects. Objects may be fields
(data) and methods (procedure or function) that operate
on that data.
(Or)
A class is a blueprint or template from which individual
objects are created.
Circle
centre
radius
circumference()
area()
3
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:
class ClassName [extends SuperClassName]
{
[fields declaration]
[methods declaration]
}
Add fields
public class Circle
{
public double x, y; // centre coordinate
public double r; // radius of the circle
5
Adding Methods
6
Adding Methods to Class Circle
public class Circle {
void barking()
{
}
void hungry()
{
String foodtype; //Local variable
}
void sleeping() {
}
}
9
Data Abstraction
Circle aCircle;
Circle bCircle;
10
Class of Circle cont.
aCircle, bCircle simply refers to a Circle , not
an object itself.
aCircle bCircle
null null
12
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle();
bCircle = aCircle;
13
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
P Q P Q
14
Automatic garbage collection
Q
The object does not have a
reference and cannot be used in future.
15
Accessing Object/Circle Data
Syntax for accessing data defined in a
structure.
ObjectName . VariableName
ObjectName .MethodName(parameter-list)
16
Executing Methods in Object/Circle
double area;
aCircle.r = 1.0;
area = aCircle.area();
17
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);
}
}
OUT PUT :
Radius=5.0 Area=78.5
Radius=5.0 Circumference =31.400000000000002
18
Costructors
19
Constructor in java is a special type of method that is
used to initialize the object.
Java constructor is invoked at the time of object creation . It
constructs the values i.e. provides data for the object that is
why it is known as constructor.
Rules for creating java constructor:
There are basically two rules defined for the constructor.
1.Constructor name must be same as its class name
2.Constructor must have no explicit return type
Types of java constructors
There are two types of constructors:
Default constructor (no-arg constructor)
Parameterized constructor
20
Example of default constructor
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Output:
Bike is created
21
Example of parameterized constructor
class Student4{
int id;
String name;
22
this keyword
23
this is a reference variable that refers to the
current object in java.
It is a keyword in java language represents
current class object.
this is always a reference to the object on
which the method was invoked.
It can be used in side of method or
constructor.
24
Usage of this keyword
It can be used to refer current class instance variable. { this.x
}
this() can be used to invoke current class constructor from
another method or constructor.
{ this(); }
It can be used to invoke current class method (implicitly)
{ this.add() }
It can be passed as an argument in the method call.
{ add(this);}
It can be passed as argument in the constructor call.
It can also be used to return the current class instance.
{ return this; }
25
Why use this keyword in java ?
The main purpose of using this keyword is to
differentiate the formal parameter and data
members of class.
whenever the formal parameter and data members
of the class are similar then jvm get ambiguity (no
clarity between formal parameter and member of
the class)
To differentiate between formal parameter and
data member of the class, the data member of the
class must be preceded by "this".
26
Example without using this keyword
class Employee
{ int id; String name;
Employee(int id,String name)
{ id = id;
name = name;
}
void show()
{ System.out.println(id+" "+name); }
public static void main(String args[])
{ Employee e1 = new Employee(111,"Harry");
Employee e2 = new Employee(112,"Jacy");
e1.show(); e2.show();
}
}
Output
0 null 0 null
27
Example with using this keyword
class Employee
{ int id; String name;
Employee(int id,String name)
{ this. id = id;
this. name = name;
}
void show()
{ System.out.println(id+" "+name); }
public static void main(String args[])
{ Employee e1 = new Employee(111,"Harry");
Employee e2 = new Employee(112,"Jacy");
e1.show(); e2.show();
}
}
Output
111 Harry 112 Jacy
28
this: to invoke current class method
29
this() : to invoke current class constructor
class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}
Out put:
hello a
10
30
Calling parameterized constructor from default
constructor:
class A{
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class TestThis6{
public static void main(String args[]){
A a=new A();
}}
Out put:
5
31
hello a
this: to pass as an argument in the
method
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){ Hear this refer
m(this); current class object
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
} }
Out put:
method is invoked
32
: this keyword can be used to return current class instance
return_type method_name()
{
return this; Control jump from out
of method
}
33
//Example of this keyword that you return as a
statement from the method
class ClassMe
{
ClassMe getClassMe()
{ return this; }
void display()
{ System.out.println("Don't confuse"); }
}
class MainClass
{ public static void main(String args[])
{
new ClassMe().getClassMe().display();
}}
Output:
Don't confuse
34
Understanding static
The static keyword in java is used for
memory management mainly.
The static can be:
variable (also known as class variable)
block
35
1) Java static variable
36
2) Java static method
If you apply static keyword with any method, it is known as
static method.
A static method belongs to the class rather than object of a
class.
A static method can be invoked without the need for creating
an instance of a class(object).
static method can access static data member and can change
They are: The static method can not use non static data
member or call non-static method directly.
this and super cannot be used in static context.
37
3) Java static block
Is used to initialize the static data member.
It is executed before main method at the time of class loading.
class A2{
static{
System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}
}
Output:
static block is invoked Hello main 38
Overloading Methods or
Constructors
39
In Java, it is possible to define two or more methods within
the same class that share the same name, as long as their
parameter declarations are different.
If a class has multiple methods having same name but
different in parameters, it is known as Method
Overloading.
Method overloading is one of the ways that Java supports
polymorphism.
in java
1. By changing number of arguments
2. By changing the data type
41
1) Method Overloading: changing no. of
arguments
class Adder{
static int add(int a,int b)
{return a+b;}
static int add(int a,int b,int c)
{return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Out put:
22
33 42
2) Method Overloading: changing data type of
arguments
class Adder{
static int add(int a, int b)
{return a+b;}
static double add(double a, double b)
{return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Out put:
22
43
24.9
Note:
In java, method overloading is not possible by changing the return type
of the method only because of ambiguity.
We can also overload java main() method. You can write any
number of main methods in a class by method overloading. But JVM calls
main() method which receives string array as arguments only. Let's see
the simple example:
If there are matching type(int & long) arguments in the method, type
promotion is not performed.
We can also overload constructor methods
Exp:
class TestOverloading4{
public static void main(String[] args){System.out.println("main with String[]");}
public static void main(String args){System.out.println("main with String");}
public static void main(){System.out.println("main without args");}
}
Out put:
main with String[]
44
Using Object as Parameter
class Rectangle
{
int length; int width;
Rectangle(int l, int b)
{
length = l; width = b;
}
void area(Rectangle obj)
{ int areaOfRectangle = obj.length * obj.width;
System.out.println("Area of Rectangle : " + areaOfRectangle);
}}
class RectangleDemo
{ public static void main(String args[])
{ Rectangle r1 = new Rectangle(10, 20);
Rectangle r2 = new Rectangle(20, 30);
r1.area(r1); r2.area(r2);
}}
Output of the program : 200 45
Argument Passing
In general, there are two ways that a
computer language can pass an argument.
1. call-by-value(pass values).
2. call-by-reference(pass object).
Java also use above two ways to pass an
argument.
When you pass a primitive type to a method,
it is passed by value
When you pass an object to a method, it is
call-by-reference
46
// Primitive types are passed by value .(call by value)
class Test {
void meth(int i, int j)
{
i *= 2;
j /= 2;
}
}
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: " +
a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " +
a + " " + b);
}
}
The output from this program is shown here:
a and b before call: 15 20
a and b after call: 15 20 47
// Objects are passed through their references (call by reference).
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// pass an object
void meth(Test o) {
o.a *= 2;
o.b /= 2;
} }
class PassObjRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " +
ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call: " +
ob.a + " " + ob.b);
}
}
This program generates the following output:
ob.a and ob.b before call: 15 20
ob.a and ob.b after call: 30 10 48
Recursion
Java supports recursion.
Recursion is the process of defining
something in terms of itself
Java programming, recursion is the attribute
that allows a method to call itself.
A method that calls itself is said to be
recursive.
49
// A simple example of recursion.
class Factorial {
// this is a recursive method
int fact(int n) {
int result; The output from this program is
if(n==1) return 1; shown here:
result = fact(n-1) * n;
//fact(3-1)*3->fact(2-1)*2*3->1*2*3 Factorial of 3 is 6
return result; Factorial of 4 is 24
Factorial of 5 is 120
}
}
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
50
Access Control
Access means visibility, if you do not have
access to a class you cannot use any
methods or variables of that class.
Java provide Access Modifiers to access
class.
There are two types of modifiers that can be
used for class declaration
Access Modifiers - public and default
(package)
Nonaccess Modifiers - final and abstract
51
Access Modifiers
Access Modifier Class or member can be
referenced by…
public methods of the same class, and
methods of other classes
private methods of the same class only
53
Exploring the String Class
Java does not support String type, it is not a
simple type .
String is an array of characters.It is under the
package java.lang.*;
In java String is an “Object”.
Strings in java are immutable
Once created they cannot be altered and hence
any alterations will lead to creation of new string
object
String is thread safe. It can not be used by two
threads simultaneously
Note: Object is the super class for all classes in java
54
String s1 = “Example”
String s2 = new String(“Example”)
String s3 = “Example”
The difference between the three statements is that, s1
and s3 are pointing to the same memory location i.e. the
string pool . s2 is pointing to a memory location on the
heap.
Using a new operator creates a memory location on the
heap.
Concatenating s1 and s3 leads to creation of a new string
in the pool.
55
StringBuffer
A StringBuffer is like a String, but can be modified.
The length and content of the StringBuffer sequence can
be changed through certain method calls.
StringBuffer can not be used by two threads
simultaneously.
StringBuffer defines three constructors:
StringBuffer(), StringBuffer(int size), StringBuffer(String str)
public class mybuffers{
public static void main(String args[]){
StringBuffer buffer = new StringBuffer(“Hi”);
buffer.append(“Bye”);
System.out.println(buffer);
}
}
This program appends the string Bye to Hi and prints it to the screen.
56
StringBuilder
StringBuilder is same as the StringBuffer , that is it
stores the object in heap and it can also be
modified .
The main difference between the StringBuffer and
StringBuilder is that StringBuilder is not thread
safe .
The StringBuilder class is not synchronized
StringBuilder is fast as it is not thread safe .
StringBuilder allow two threads to simultaneously
access the same method.
57
class StringBuilderExample{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java");//now original string is changed.
System.out.println(sb);//prints Hello Java.
}
}
58
// Demonstrating Strings.
class StringDemo {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1 + " and " + strOb2;
System.out.println(strOb1);
System.out.println(strOb2);
System.out.println(strOb3);
}
}
The output produced by this program is shown here:
First String
Second String
First String and Second String
59
// Demonstrating some String methods.
class StringDemo2 {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1;
System.out.println("Length of strOb1: " +strOb1.length());
System.out.println("Char at index 3 in strOb1: " +strOb1.charAt(3));
if(strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");
if(strOb1.equals(strOb3))
System.out.println("strOb1 == strOb3");
else
System.out.println("strOb1 != strOb3");
}
}
This program generates the following output:
Length of strOb1: 12
Char at index 3 in strOb1: s
strOb1 != strOb2
strOb1 == strOb3
60
// Demonstrate String arrays.
class StringDemo3 {
public static void main(String args[]) {
String str[] = { "one", "two", "three" };
for(int i=0; i<str.length; i++)
System.out.println("str[" + i + "]: " +
str[i]);
}
}
Here is the output from this program:
str[0]: one
str[1]: two
str[2]: three
61
public class ConcatenationExample
{ public static void main(String args[])
{ //One way of doing concatenation
String str1 = "Welcome";
str1 = str1.concat(" to ");
str1 = str1.concat(" String handling ");
System.out.println(str1); //Other way of doing
concatenation in one line
String str2 = "This";
str2 = str2.concat(" is").concat(" just a").concat(" String");
System.out.println(str2);
String str3=str1.concat(str2) } }
Output:
Welcome to String handling
This is just a String
Welcome to String handling This is just a String
62
Using Command-Line Arguments
We will pass information into a program when you
run it. This is accomplished by passing command-
line arguments to main( ).
// Display all command-line arguments.
class CommandLine {
public static void main(String args[]) {
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " +
args[i]);
}
}
63
Try executing this program, as shown here:
java CommandLine this is a test 100 -1
output:
args[0]: this
args[1]: is
args[2]: a
args[3]: test
args[4]: 100
args[5]: -1
64