Unit 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

Object Oriented Programming with Java

Unit Wise Lecture Notes

Compiled by :
Dharmesh Tank
Unit 2 Basics of Objects and Classes in JAVA
Classes and Objects:

In the real world, you'll often find many individual objects all of the same kind. There may be
thousands of other bicycles in existence, all of the same make and model. Each bicycle was built
from the same set of blueprints and therefore contains the same components. In object-oriented
terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is
the blueprint from which individual objects are created.

Declaring Member Variables


There are several kinds of variables:
• Member variables in a class—these are called fields.
• Variables in a method or block of code—these are called local variables.
• Variables in method declarations—these are called parameters.
A class is declared by use of the class keyword class
class classname
{
type instance-variable1;
type instance-variable2;
………
type instance-variableN;

type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list)
{
// body of method
}
………
type methodnameN(parameter-list)
{
// body of method
}
}
The data, or variables, defined within a class are called instance variables. The code is contained
within methods. Collectively, the methods and variables defined within a class are called members
of the class. In most classes, the instance variables are acted upon and accessed by the methods
defined for that class. Variables defined within a class are called instance variables because each
instance of the class (that is, each object of the class) contains its own copy of these variables.
Thus, the data for one object is separate and unique from the data for another.
Example:
class demo
{
int x=1, y=2; float z=3;
void display()
{
System.out.println(“values of x, y and z are:”(+x)”-”(+y)”-”(+z));
}
}

Declaring Objects
when you create a class, you are creating a new data type. You can use this type to declare objects
of that type. However, obtaining objects of a class is a two-step process. First, you must declare a
variable of the class type. This variable does not define an object. Instead, it is simply a variable
that can refer to an object. Second, you must acquire an actual, physical copy of the object and
assign it to that variable. You can do this using the new operator.
The new operator dynamically allocates (that is, allocates at run time) memory for an
object and returns a reference to it. This reference is, more or less, the address in memory of the
object allocated by new.
This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically
allocated. In the above programs to declare an object of type demo:

demo d1 = new demo( );


This statement combines the two steps just described. It can be rewritten like this to show
each step more clearly:

demo d1; // declare reference to object


d1 = new demo( ); // allocate a demo object

The first line declares d1 as a reference to an object of type demo. After this line executes, d1
contains the value null, which indicates that it does not yet point to an actual object. Any attempt
to use d1 at this point will result in a compile-time error. The next line allocates an actual object
and assigns a reference to it to d1. After the second line executes; you can use d1 as if it were a
demo object. But in reality, d1 simply holds the memory address of the actual demo object.

Object Reference Variables:


o Object reference variables act differently than you might expect when an assignment
takes place.
o For example, what do you think the following fragment does?

▪ Box b1 = new Box();


▪ Box b2 = b1;
o After this fragment executes, b1 and b2 will both refer to the same object.
o The assignment of b1 to b2 did not allocate any memory or copy any part of the original
object. It simply makes b2 refer to the same object as does b1.
o Thus, any changes made to the object through b2 will affect the object to which b1 is
referring, since they are the same object.
o This situation is depicted here:

Constructors:

A class contains constructors that are invoked to create objects from the class blueprint.
Constructor declarations look like method declarations—except that they use the name of the
class and have no return type. A constructor initializes an object immediately upon creation.
Constructors can be Default or Parameterized Constructors or Copy Constructors.

Default Constructor:

A default constructor is called when an instance is created for a class.


Class demo
{
int x, y; float z;
demo()
{
x=1; y=2; z=3.9;
}
void display()
{
System.out.println(“values of x, y and z are:”(+x)”-”(+y)”-”(+z));
}
}
Class demomain
{
public static void main(String args[])
{
demo d1=new demo(); // this is a call for the above default constructor
d1.display();
}
}
Parameterized Constructor:
Class demo
{
int x, y; float z;
demo(int x1,int y1,float z1)
{
x=x1;
y=y1;
z=z1;
}
demo(int x1,int y1,float z1)
{
x=x1;
y=y1;
z=z1;
}

void display()
{
System.out.println(values of x, y and z are:”(+x)”-”(+y)”-”(+z));
}
}
Class demomain
{
public static void main(String args[])
{
demo d1=new demo(1,2,3.9); // this is a call for the above parameterized
d1.display();
}
}
Copy Constructor:
class Rectangle
{
//declaration
int length;
int breadth;

//constructor to initialize length and bredth of rectang of rectangle


Rectangle(int l, int b)
{
length = l;
breadth= b;
}
Rectangle(Rectangle obj) //copy constructor
{
System.out.println("Copy Constructor Invoked");
length = obj.length;
breadth= obj.breadth;
}
//method to calcuate area of rectangle
int area()
{
return (length * breadth);
}
class CopyConstructor
{
public static void main(String[] args)
{
Rectangle firstRect = new Rectangle(5,6);
Rectangle secondRect= new Rectangle(firstRect);
System.out.println("Area of First Rectangle : "+ firstRect.area());
System .out.println("Area of Second Rectangle : "+ secondRect.area());
}
}

Output:

Method Overloading

o Class have multiple methods(functions) by same name but different parameters, it is known
as method overloading.
o Method overloading is one of the ways that Java supports polymorphism.
o But as you will see, method overloading is one of Java’s most exciting and useful features.
o When an overloaded method is called, Java uses the type and/or number of arguments as its
guide to determine which version of the overloaded method to actually call.
o Thus, overloaded methods must differ in the type and/or number of their parameters.
o While overloaded methods may have different return types, the return type alone is
insufficient to distinguish two versions of a method.
o Here is a simple example that illustrates method overloading:
EXAMPLE: Sum of two numbers using method overloading.
class sumoftwo
{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}
}
class sum
{
public static void main(String args[])
{
sumoftwo ob=new sumoftwo();
ob.sum(10,20,30);
ob.sum(20,50);
}
}

OUTPUT:
60
70

EXAMPLE:
// Demonstrate method overloading.
class one
{
void test()
{
System.out.println("No parameters");
}
void test(int a)
{
System.out.println("a: " + a);
}
void test(int a, int b)
{
System.out.println("a and b: " + a + " " + b);
}
}
class two
{
public static void main(String args[])
{
one ob = new one();
ob.test();
ob.test(10);
ob.test(10, 20);
}
}

OUTPUT:
No parameters a: 10
a and b: 10 20
Overloading Constructors
o Constructor is special type of method which called at the time of object creation.
o In addition to overloading normal methods, you can also overload constructor.
o There is two types of constructor:
1. Default constructor (Constructor have no-parameter)
2. Parameterized constructor (Constructor have parameter)
3. Copy Constructor
EXAMPLE:
//Demonstrate constructor(default constructor) overloading.
class display
{
display()
{
System.out.println(“Hello world”);
}
}
class read_display
{
public static void main(String args[])
{
display ob=new display();
}
}
/* Here, Box defines three constructors to initialize the dimensions of a box various
ways.*/
class Box
{
double width, height, depth;
Box(double w, double h, double d)
{
width = w; height = h; depth = d;
}
Box(double l)
{
width = l; height = l; depth = l;
}
Box()
{
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
double volume()
{
return width * height * depth;
}
}
class Demobox
{
public static void main(String args[])
{
Box b1 = new Box(10, 20, 15);
Box b2 = new Box();
Box mycube = new Box(7);
double vol;
vol = b1.volume();
System.out.println("Volume of mybox1 is " + vol);
vol = b2.volume();
System.out.println("Volume of mybox2 is " + vol);
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
OUTPUT:
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0
Recursion:
o Java supports recursion. Recursion is the process of defining something in terms of itself.
o As it relates to Java programming, recursion is the attribute that allows a method to call itself.
A method that calls itself is said to be recursive.
o The classic example of recursion is the computation of the factorial of a number.
o The factorial of a number N is the product of all the whole numbers between 1 and N.
o For example, 3 factorial is 1 × 2 × 3, or 6. Here is how a factorial can be computed by use of
a recursive method:
// A simple example of recursion.
class Factorial
{
int fact(int n)
{
int result;
if(n==1) return 1;
result = fact(n-1) * n;
return result;
}
}
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));
}
}
Output:
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
This Keyword:
o Sometimes a method will need to refer to the object that invoked it. To allow this, Java
defines the this keyword.
o this can be used inside any method to refer to the current object.
o That is, this is always a reference to the object on which the method was invoked.
o You can use this anywhere a reference to an object of the current class type is permitted.

Example:
class JBT {
int variable = 5;
public static void main(String args[])
{
JBT obj = new JBT();
obj.method(20);
obj.method();
}
void method(int variable)
{
variable = 10;
System.out.println("Value of Instance variable :" +
this.variable);
System.out.println("Value of Local variable :" +
variable);
}
void method() {
int variable = 40;
System.out.println("Value of Instance variable :"+
this.variable);
System.out.println("Value of Local variable :" +
variable);
}
}
Output:
To differentiate between the local and instance variables we have used this keyword int the
constructor.

Static Keyword
o The static keyword is used in java mainly for memory management.
o We may apply static keyword with variables, methods and blocks.
o The static can be:
• variable (also known as class variable)
• method (also known as class method)
• block
o A static method belongs to the class rather than object of a class.
o A static method can be invoked without the need for creating an object of a class.
o Static method can access static data member and can change the value of it.
o To create such a member, precede its declaration with the keyword static.
o When a member is declared static, it can be accessed before any objects of its class are
created, and without reference to any object.
o The most common example of a static member is main( ).
o main( )is declared as static because it must be called before any objects exist.
o Methods declared as static have several restrictions:
• They can only call other static methods.
• They must only access static data.
EXAMPLE:-Demonstrate static variables, methods, and blocks.
class UseStatic
{
static int x = 3;
static void meth(int x)
{
System.out.println("x = " + x);
}
static
{
System.out.println(“Static block initialized::”+ x);
}
public static void main(String args[])
{
meth(42);
}
}
OUTPUT:
Static block initialized::3
x = 42

o Outside of the class in which they are defined, static methods and variables can be used
independently of any object. To do so, you need only specify the name of their class
followed by the dot operator.
o For example, if you wish to call a static method from outside its class, you can do so using
the following general form.
classname.method( )

o Here, classname is the name of the class in which the static method is declared.
o As you can see, this format is similar to that used to call non- static methods through object-
reference variables.
o A static variable can be accessed in the same way—by use of the dot operator on the name
of the class.
Example:
class Demo
{
static int a = 42;
static int b = 99;
static void callme()
{
System.out.println("a = " + a);
}
}
class test
{
public static void main(String args[])
{
Demo.callme();
System.out.println("b = " + Demo.b);
}
}
Output:
a=42
b=99

Garbage Collection:
o Since objects are dynamically allocated by using the new operator, objects are destroyed
and their memory released for later reallocation.
o In some languages, such as C++, dynamically allocated objects must be manually released
by use of a delete operator.
o Java takes a different approach; it handles deallocation for you automatically. The
technique that accomplishes this is called garbage collection.
o It works like this: when no references to an object exist, that object is assumed to be no
longer needed, and the memory occupied by the object can be reclaimed.
o There is no explicit need to destroy objects as in C++.
o Garbage collection is also called automatic memory management.
Syntax:
public class Main
{
public static void main(String[] args)
{ System.gc(); }
}
The finalize( ) Method:
o Sometimes an object will need to perform some action when it is destroyed. For example, if
an object is holding some non-Java resource such as a file handle or window character font,
then you might want to make sure these resources are freed before an object is destroyed.
o To handle such situations, Java provides a mechanism called finalization. By using
finalization, you can define specific actions that will occur when an object is just about to
be reclaimed by the garbage collector.
o It is important to understand that finalize() is only called just prior to garbage collection.
o It is not called when an object goes out-of-scope, for example. This means program should
provide other means of releasing system resources, etc., used by the object. It must not rely
on finalize() for normal program operation.
o To add a finalizer to a class, you simply define the finalize( ) method.
o The Java run time calls that method whenever it is about to recycle an object of that class.
o Inside the finalize() method you will specify those actions that must be performed before an
object is destroyed.
o The garbage collector runs periodically, checking for objects that are no longer referenced
by any running state or indirectly through other referenced objects.
o Right before an asset is freed, the Java run time calls the finalize( ) method on the object.

To import : java.lang.Object.finalize()

The finalize( ) method has this general form:


protected void finalize( )
{
// finalization code here
}
Here, the keyword protected is a specifier that prevents access to finalize( ) by code
defined outside its class.

final KEYWORD:
o A variable can be declared as final.
o The Java final keyword is used to indicate that something "cannot change".
o Use of Final keyword:
▪ It is used to indicate that a class cannot be extended.
▪ It is used to indicate that a method cannot be overridden.
▪ It is used to indicate that a local variable cannot be changed once its value is set.
▪ It is used to indicate that a static variable cannot be changed once set, in effect
implementing "constants".
For example:
▪ final int I= 1;
Subsequent parts of your program can now use i, etc., as if they were constants, without
fear that a value has been changed.
EXAMPLE:
public class Demo
{
final int I=10;
void abc()
{
System.out.println("Final variable value : "+I);
}
public static void main(String[] args)
{
Demo f=new Demo();
f.abc();
}
}
OUTPUT:-

Final variable value :10


Difference between final, finally and finalize
No. final finally finalize

1) Final is used to apply Finally is used to place Finalize is used to


restrictions on class, important code, it will be perform clean up
method and variable. Final executed whether processing just before
class can't be inherited, exception is handled or object is garbage
final method can't be not. collected.
overridden and final
variable value can't be
changed.

2) Final is a keyword. Finally is a block. Finalize is a method.


Java final example

class FinalExample{
public static void main(String[] args){
final int x=100;
x=200; // Compile Time Error
}
}
Java finally example
class FinallyExample{
public static void main(String[] args){
try
{
int x=300;
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is executed");}
}
}
Java finalize example
class FinalizeExample{
public void finalize()
{System.out.println("finalize called");}
public static void main(String[] args){
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1=null;
f2=null;
System.gc();
}
}
Parameter Passing:
o In general, there are two ways that a computer language can pass an argument to a
subroutine.
o The first way is call-by-value. In this method copies the value of an argument into the formal
parameter of the subroutine. Therefore, changes made to the parameter of the subroutine
have no effect on the argument.
o The second way an argument can be passed is call-by-reference. In this method, a reference
to an argument (not the value of the argument) is passed to the parameter. Inside the
subroutine, this reference is used to access the actual argument specified in the call. This
means that changes made to the parameter will affect the argument used to call the
subroutine.
o Java uses both approaches, depending upon what is passed.
o In Java, when you pass a simple type to a method, it is passed by value. Thus, what occurs
to the parameter that receives the argument has no effect outside the method. For example,
consider the following program:
// Simple types are passed 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);
}
}
Output :
a and b before call: 15 20
a and b after call: 15 20

we can see, the operations that occur inside meth( ) have no effect on the values of a and
b used in the call; their values here did not change to 30 and 10.
When we pass an object to a method, the situation changes dramatically, because objects
are passed by reference. Keep in mind that when you create a variable of a class type, you
are only creating a reference to an object. Thus, when you pass this reference to a method,
the parameter that receives it will refer to the same object as that referred to by the
argument. This effectively means that objects are passed to methods by use of call-by-
reference. Changes to the object inside the method do affect the object used as an
argument.
Example:
// Objects are passed 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 CallByRef
{
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);
}}
Output:
ob.a and ob.b before call: 15 20
ob.a and ob.b after call: 30 10

in this case, the actions inside meth( ) have affected the object used as an argument.

Java Access/ Visibility Modifiers

You must have seen public, private and protected keywords while practising
java programs, these are called access modifiers. An access modifier restricts the
access of a class, constructor, data member and method in another class. In java we
have four access modifiers:
1. default
2. private
3. protected
4. public

1. Default access modifier

When we do not mention any access modifier, it is called default access modifier. The
scope of this modifier is limited to the package only. This means that if we have a class
with the default access modifier in a package, only those classes that are in this package
can access this class. No other class outside this package can access this class.
Similarly, if we have a default method or data member in a class, it would not be visible
in the class of another package. Lets see an example to understand this:

Default Access Modifier Example in Java

In this example we have two classes, Test class is trying to access the default method
of Addition class, since class Test belongs to a different package, this program would
throw compilation error, because the scope of default modifier is limited to the same
package in which it is declared.
Addition.java

package abcpackage;

public class Addition {


/* Since we didn't mention any access modifier here, it would
be considered as default. */
int addTwoNumbers(int a, int b){
return a+b; }}

Test.java

package xyzpackage;
/* We are importing the abcpackage but still we will get error
because the class we are trying to use has default access
modifier. */
import abcpackage.*;
public class Test {
public static void main(String args[]){
Addition obj = new Addition();
/* It will throw error because we are trying to access
* the default method in another package
*/
obj.addTwoNumbers(10, 21);
}
}

Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:


The method addTwoNumbers(int, int) from the type Addition is not visible
at xyzpackage.Test.main(Test.java:12)

2. Private access modifier

The scope of private modifier is limited to the class only.

1. Private Data members and methods are only accessible within the class
2. Class and Interface cannot be declared as private
3. If a class has private constructor then you cannot create the object of that class from
outside of the class.
Let’s see an example to understand this:
Private access modifier example in java

This example throws compilation error because we are trying to access the private data member
and method of class ABC in the class Example. The private data member and method are only
accessible within the class.
class ABC{
private double num = 100.789;
private int square(int a){
return a*a;
}
}
public class Example{
public static void main(String args[]){
ABC obj = new ABC();
System.out.println(obj.num);
System.out.println(obj.square(10));
}
}
Output:
Compile - time error

3. Protected Access Modifier


Protected data member and method are only accessible by the classes of the same package and the
subclasses present in any package. You can also say that the protected access modifier is similar
to default access modifier with one exception that it has visibility in sub classes. Classes cannot
be declared protected. This access modifier is generally used in a parent child relationship.

Protected access modifier example in Java


In this example the class Test which is present in another package is able to call
the addTwoNumbers() method, which is declared protected. This is because the Test class
extends class Addition and the protected modifier allows the access of protected members in
subclasses (in any packages).
Addition.java
package abcpackage;
public class Addition {
protected int addTwoNumbers(int a, int b){
return a+b;
}
}
Test.java
package xyzpackage;
import abcpackage.*;
class Test extends Addition{

public static void main(String args[]){

Test obj = new Test();

System.out.println(obj.addTwoNumbers(11, 22));
}
}
Output: 33
4. Public access modifier

The members, methods and classes that are declared public can be accessed from anywhere. This
modifier doesn’t put any restriction on the access.

public access modifier example in java

Lets take the same example that we have seen above but this time the method addTwoNumbers()
has public modifier and class Test is able to access this method without even extending the
Addition class. This is because public modifier has visibility everywhere.
Addition.java

package abcpackage;
public class Addition {
public int addTwoNumbers(int a, int b){
return a+b;
}
}

Test.java

package xyzpackage;
import abcpackage.*;
class Test{
public static void main(String args[]){

Addition obj = new Addition();


System.out.println(obj.addTwoNumbers(100, 1));
}
}
Output:
101
Lets see the scope of these access modifiers in tabular
form:
The scope of access modifiers in tabular form
+ + + + +
| Class | Package | Subclass | Subclass |Outside|
| | |(same package)|(diff package)|Class |
————————————+———————+—————————+——————————----+—————————----—+————————
public | Yes | Yes | Yes | Yes | Yes |
————————————+———————+—————————+—————————----—+—————————----—+————————
protected | Yes | Yes | Yes | Yes | No |
————————————+———————+—————————+————————----——+————————----——+————————
default | Yes | Yes | Yes | No | No |
————————————+———————+—————————+————————----——+————————----——+————————
private | Yes | No | No | No | No |
+ + + + +
Returning an object
o A method can return any type of data, including class types that you create.
o For example, in the following program, the abc( ) method returns an object in which the
value of a is ten greater than it is in the invoking object.
EXAMPLE:
class Test
{
int a;
Test(int i)
{
a = i;
}
Test abc()
{
Test temp = new Test(a+10);
return temp; //returning object
}
}
class two
{
public static void main(String args[])
{
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.abc();
System.out.println("ob1.a: " + ob1.a); 2
System.out.println("ob2.a: " + ob2.a); 12
ob2 = ob2.abc();
System.out.println("ob2.a after second increase: "+ ob2.a);
}
}
OUTPUT:
ob1.a: 2
ob2.a: 12
ob2.a after second increase: 22

Nested Classes
o Class within another class such classes is known as nested classes.
o A nested class has access to the members, including private members, of the class in
which it is nested.
o However, the enclosing class does not have access to the members of the nested class.
o There are two types of nested classes: static and non-static.
o A static nested class is one which has the static modifier applied. Because it is static, it
must access the members of its enclosing class through an object. That is, it cannot refer
to members of its enclosing class directly. Because of this restriction, static nested classes
are seldom used.
o The most important type of nested class is the inner class.
o An inner class is a non-static nested class.
o It has access to all of the variables and methods of its outer class and may refer to them
directly in the same way that other non-static members of the outer class
Inner Classes
o As with instance methods and variables, an inner class is associated with an instance of
its enclosing class and has direct access to that object's methods and fields.
o Also, because an inner class is associated with an instance, it cannot define any static
members itself.
o Objects that are instances of an inner class exist within an instance of the outer class.
o Consider the following classes:
class OuterClass
{ ...
class InnerClass
{
..
}
}
o An instance of InnerClass can exist only within an instance of OuterClass and has direct
access to the methods and fields of its enclosing instance.
o The next figure illustrates this idea.
o An Instance of Inner Class Exists Within an Instance of OuterClass.

Example:
class Outer
{
int outer_x = 100;
void test()
{
Inner in = new Inner();
in.display();
}
// this is an inner class class Inner
class Inner{
{
void display()
{
System.out.println("display: outer_x = " + outer_x);
}
}
}
class InnerClassDemo
{
public static void main(String args[])
{
Outer outer = new Outer();
outer.test();
}
}
OUTPUT:

display: outer_x = 100

Anonymous inner class in java

A class that have no name is known as anonymous inner class in java. It should be used if you
have to override method of class or interface. Java Anonymous inner class can be created by two
ways:

1. Class (may be abstract or concrete).


2. Interface

Example
abstract class Person
{
abstract void eat();
}
class TestAnonymousInner
{
public static void main(String args[])
{
Person p=new Person()
{
void eat(){System.out.println("nice fruits");}
};
p.eat();
}
}

Output:
nice fruits

You might also like