1
UNIT-2
Classes and Objects: Introduction, Class Declaration and Modifiers, Class Members,
Declaration of Class Objects, Assigning One Object to Another, Access Control for Class
Members, Accessing Private Members of Class, Constructor Methods for Class, Overloaded
Constructor Methods, Nested Classes, Final Class and Methods, Passing Arguments by Value and
by Reference, Keyword this.
Methods: Introduction, Defining Methods, Overloaded Methods, Overloaded Constructor
Methods, Class Objects as Parameters in Methods, Access Control, Recursive Methods, Nesting
of Methods, Overriding Methods, Attributes Final and Static.
Classes and Objects
Introduction
class:
class is a language construct (not an object oriented feature) i.e. similar to a structure in ‘c’
language as long as user defined data type is concerned.
A class is defined as collection of similar objects.
Classes are user-defined data types and behave like the built-in types of a programming language.
Class declaration contains name of the class and body of the class. The body of the class may
consist of several statements and is enclosed between the braces {}.
A sample of class declaration is as follows.
Object:
Object is nothing but the copy of class. It will literally store RAM.
A class is a plan/blueprint for the proposed objects.
Object implements Encapsulation where as class is the basis of Encapsulation.
Class is the language feature, where as Encapsulation is the object oriented feature. By writing
classes in programs we are implementing the concept Encapsulation.
Class Declaration and Modifiers
A class declaration starts with the Access modifier. It is followed by keyword class, which is
followed by the name or identifier. The body of class is enclosed between a pair of braces { }.
Example:
2
The class name starts with an upper-case letter, whereas variable names may start with lower-
case letters.
In the case of names consisting of two or more words as in MyFarm, the other words for
with a capital letter for both classes and variables. In multiword identifiers, there is no blank
space between the words
The class names should be simple and descriptive.
Class names should start with an upper-case letter and should be nouns. For example, it could
include names such as vehicles, books, and symbols.
It should have both upper and lower-case letters with the first letter capitalized
Acronyms and abbreviations should be avoided
Class Modifiers
Class modifiers are used to control the access to class and its inheritance characteristics.
Java consists of packages and the packages consist of sub-packages and classes Packages can also
be used to control the accessibility of a class
These modifiers can be grouped as (a) access modifiers and (b) non-access modifiers. Table 5.l
gives a description of the various class modifiers.
Class Members
The class members are declared in the body of a class. These may comprise data (variables in a
class). code (methods) and nested classes.
The members of a class comprise the members declared in the class as well as the members
inherited from a super class. The scope of all the members extends to the entire class body. The
fields comprise two types of variables
1. Non Static variables: These include instance and local variables
(a) Object Variables (Instance variables): These variables are individual to an object
and an object keeps a copy of these variables in its memory.
(b) Local variables: These are local in scope and not accessible outside their scope.
2. Class variables (Static Variables): These variables are also qualified as static variables. The
values of these variables are common to all the objects of the class. The class keeps only one
copy of these variables and all the objects share the same copy. As class variables belong to
the whole class, these are also called class variables.
Declaration of Class Objects
Creating an object is also referred to as instantiating an object.
3
Objects in java are created dynamically using the new operator.
The new operator creates an object of the specified class and returns a reference to that object.
Syntax: (creating an object)
className objectReference=new className();
Assigning One Object to Another
Java provides the facility to assign one object to another object
Syntax:
new_Object = old_object;
All the properties of old_object will be copied to new object.
Example:
class ClassOne
{
double length;
double width;
double area()
{
return length*width;
}
}
public class ClassTwo
{
public static void main (String args[])
{
ClassOne a = new ClassOne(); //defining an object of ClassOne
ClassOne b = new ClassOne(); //defining an object of ClassOne
[Link] = 20.0;
[Link] = 40.0;
[Link]("Area of ClassOne = " + [Link]());
b = a; // Object Assignment
[Link]("Area of ClassTwo = " + [Link]());
}
}
Output:
E:\core java\unit-2>javac [Link]
E:\core java\unit-2>java ClassTwo
Area of ClassOne = 800.0
Area of ClassTwo = 800.0
E:\core java\unit-2>
Access Control for Class Members
Access specifiers in java
These are used to define the scope of a variable or a method or a class.
There are three access specifiers in java
private
protected
4
public
There are four accessibility modes in java.
private
default
protected
public
private
This mode has the visibility class level visibility.
default
This mode visibility is class level+ package level.
protected
This mode visibility class level + package level + child class level.
public
Total java Environment
Q) Write programs to demonstrate accessibility modes of variable.
package pack1;
public class A
{
private int a=1;
public int b=2;
protected int c=3;
int d=4;
}
//using A class in another class B of same package
package pack1;
import pack1.A
public class B
{
public static void main(String args[])
{
A a=new A();
//[Link](a.a);
[Link](a.b);
[Link](a.c);
[Link](a.d);
}
}
//using A in a class C which is in another package
package pack2;
import pack1.A
public class C
{
public static void main(String args[])
{
A a=new A();
//[Link](a.a);
[Link](a.b);
//[Link](a.c);
//[Link](a.d);
}
}
//using A in child class C1 which is in another package
package pack2;
import pack1.A
public class C1 extends A
5
{
public static void main(String args[])
{
C1 c=new C1();
//[Link](c.a);
[Link](c.b);
[Link](c.c);
//[Link](c.d);
}
Note:
To run the program which contains package we have to type the command on command prompt
as shown below.
Ex: java pack1.B
The commented statements will not work in those classes because of their visibility mode of the
variables.
Accessing Private Members of Class
Private members of a class, whether they are instance variables or methods, can only be accessed
by other members of the same class
Any code outside of class cannot directly access them because they are private.
Example:
class Farm
{
//private variables
private double length;
private double width;
//definition of public methods
public double area() {
return length*width;
}
public void setSides(double l, double w){
length=l; width = w;
}
public double getLength(){
return length;
}
public double getWidth(){
return width;
}
}
class PrivateEx
{
public static void main (String args[])
{
Farm farm1 =new Farm();
[Link](50.0,20.0);
double farmArea = [Link]();
[Link]("Area of farm1 = "+ farmArea);
[Link]("Length of farm1 = "+ [Link]());
[Link]("Length of farm1 = "+ [Link]());
}
}
Output:
E:\core java\unit-2>javac [Link]
6
E:\core java\unit-2>java PrivateEx
Area of farm1 = 1000.0
Length of farm1 = 50.0
Length of farm1 = 20.0
E:\core java\unit-2>
In the above program, the two object variables length and width are declared private. The first
thing is to assign values to these variables for an object. This is done by defining a public method
setSides(), which is invoked by the class object for entering values that are passed to length and
width variables The method setSides().
The class also defines another method area() to which the values are passed for calculationof area
when the method area() is invoked by the object. For obtaining values of length and width by
outside code, two public methods are defined as
public double getLength(){return length;} //Function for getting length
public double getWidth(){return width;}// Function for getting width
Constructor Methods for Class
A constructor is a specialized method of a class.
A constructor is different from normal methods of a class in the following criteria.
o In name
o Type of calling
o Frequency of calling
o In type
o In purpose
A constructor name and class name are same.
A constructor is called implicitly/automatically.
A constructor is called as soon as the object is created and before the new operator binds the
object to the reference variable (after the object creation and before new operator binds the object
the reference variable).
Constructor does not have any return type not even void.
A constructor is meant for object initialization at the time of object creation whatever resources
you want to supply to the object you can supply.
If a constructor is not available for a class its object cannot be created.
We have three kinds of constructors in java.
o Default constructor
o Zero argument constructor
o Parameterized constructor
Default constructor:
If we don’t supply any constructor for the class, the compiler will provide a zero argument
constructor while creating the object. This is called “Default constructor”.
Ex:
class A{
void x(){
}
}
Note: In the above class A, we did not provide constructor. The compiler will provide a
constructor while creating the object for the class A.
Zero argument constructor:
If supply a constructor for the class with zero arguments as shown below then it is called
“Zero argument constructor”.
Ex:
class A{
7
A(){
[Link](“….Zero Argument constructor….”);
}
void x(){
}
}
Note: In the above class A, we provide constructor with no arguments.
Parameterized constructor:
If supply a constructor for the class with one or more parameters then it is called
“Parameterized constructor”.
Q) Write a program on parameterized constructor
class Account
{
int accno;
String name;
float balance;
Account(int ano,String n,float bal)
{
accno=ano;
name=n;
balance=bal;
}
void displayAccountDetails()
{
[Link]("A/C no :"+accno);
[Link]("A/C holder name :"+name);
[Link]("A/C balance :"+balance);
}
void withdraw(float amt)
{
if(balance>=amt)
{
balance=balance-amt;
[Link]("After withdrawing the balance is :"+balance);
}
else
[Link]("In sufficient funds available.......");
}
void deposit(float amt)
{
balance=balance+amt;
}
}
class ConstructorExample
{
public static void main(String args[])
{
Account a1=new Account(1001,"rama",500);
[Link]();
[Link](4000);
[Link]("After depositing balance is:"+[Link]);
[Link](500);
}
}
8
Output:
E:\core java\unit-2>javac [Link]
E:\core java\unit-2>java ConstructorEx
A/C no :1001
A/C holder name :rama
A/C balance :500.0
After depositing balance is:4500.0
After withdrawing the balance is :4000.0
E:\core java\unit-2>
Overloaded Constructor Methods (constructor overloading)
Signature of a method: Method name + parameters list is called the signature of the method.
Overloading
Defining a constructor with same name and with different parameters (different signatures) is
called constructor overloading.
Q) Write a program on constructor overloading.
class Book
{
int isbn;
String title;
float price;
Book()
{
isbn=123456;
title="java complete reference";
price=310;
}
Book(int a)
{
isbn=123456;
title="java complete reference";
price=310;
}
Book(int n,String t,float p)
{
isbn=n;
title=t;
price=p;
}//perameterized constructor
void displayItemDetails()
{
[Link](isbn);
[Link](title);
[Link](price);
}
}
class ConstructorOverloadEx
{
public static void main(String []args)
{
Book b1=new Book();
[Link]("First Book Details .........");
[Link]();
9
Book b2=new Book(123456,"Head First java",400);
[Link]("Second Book Details .........");
[Link]();
}
}
Output:
E:\core java\unit-2>javac [Link]
E:\core java\unit-2>java ConstructorOverloadEx
First Book Details .........
123456
java complete reference
310.0
Second Book Details .........
123456
Head First java
400.0
E:\core java\unit-2>
Constructor Chaining
Calling the zero argument constructor from the first line of the parameterized constructor using
the method ‘this()’ is called constructor chaining.
Chaining must be done at the first time of the parameterized constructor.
Q) Write an example program on constructor chaining
class Item
{
int itemno;
float price;
Item()
{
[Link]("Item issued");
}//default constructor
Item(int ino,float p)
{
this();//chaining
itemno=ino;
price =p;
}
void displayItemDetails()
{
[Link]("Item No:"+itemno);
[Link]("Item price:"+price);
}
}
class ConstructorChainingEx
{
public static void main(String []args)
{
Item i=new Item(100001,50);
[Link]();
}
}
Output:
E:\core java\unit-2>javac [Link]
E:\core java\unit-2>java ConstructorChainingEx
Item issued
Item No:100001
10
Item price:50.0
E:\core java\unit-2>
Nested Classes(Inner Classes)
Java inner class or nested class is a class i.e. declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place so that it can be more
readable and maintainable.
Additionally, it can access all the members of outer class including private data members and
methods.
There are four types of inner classes
1. Static Inner classes: These are the static members of a class.
[Link]
class Outer {
static class Inner {
void innerMethod() {
[Link]("Inner class reference is: " + this);
}
}
}
public class StaticInnerEx {
public static void main(String[] args) {
[Link] n = new [Link]();
[Link]();
}
}
Output:
Inner class reference is: Outer$Inner@c17164
2. Non Static Inner classes (Member Inner classes): These are the non-static members of a class.
[Link]
//Non static inner class Example
class Outer {
private int x = 100;
public void makeInner(){
Inner in = new Inner();
[Link]();
}
class Inner{
public void seeOuter(){
[Link]("Outer x is " + x);
[Link]("Inner class reference is " + this);
[Link]("Outer class reference is " + [Link]);
}
}
public static void main(String [] args){
Outer o = new Outer();
Inner i = [Link] Inner();
[Link]();
}
}
Output:
Outer x is 100
Inner class reference is Outer$Inner@c17164
Outer class reference is Outer@1fb8ee3
11
3. Method Local Inner class: There are defined within the method body
//Method local Inner class
public class Outer1 {
private String x = "outer";
public void doStuff() {
class MyInner {
public void seeOuter() {
[Link]("x is" + x);
}
}
MyInner i = new MyInner();
[Link]();
}
public static void main(String[] args) {
Outer1 o = new Outer1();
[Link]();
}
}
Output:
x is outer
4. Anonymous Inner class: These are not having any name(no name classes)
Example code:
[Link](new ActionListener(){
public void actionPerformed(ActionEvent e){
[Link]("Button has been clicked");
}
});
Final Class and Methods
final methods
If a method is declared final it can be inherited by the child class but it cannot be overridden.
class A
{
final void x ()
{
[Link](“……super x()…..”);
}
}
class B extends A
{
void y()
{
x();//final method can be inherited
}
void x()
{
//final method cannot be overridden
}
}
final classes
12
If a class is declared final, it cannot be sub classed i.e. inheritance is prevented but we can create
object for that class.
final class A
{
void x(){
A a=new A()// allowed because final class can be instiantiated.
}
}
class B extends A
{
} // not allowed because A is final.
In a hierarchy of classes the most specialized class is generally declared final if it is felt that
reusability is saturated and further specialization will not give any meaningful classes.
Passing Arguments by Value and by Reference
There are basically two types of techniques for passing the parameters in Java. The first one is
pass-by-value and the second one is pass-by-reference.
When a primitive type is passed to a method, then it is done by the use of pass-by-value.
All the non-primitive types that include objects of any class are always implicitly passed by use
of pass-by-reference.
Basically, pass-by-value means that the actual value of the variable is passed and pass-by-
reference means the memory location is passed where the value of the variable is stored.
Java Pass by Value Example
In this example, we will see how to pass a parameter by using pass-by-value which is also known
as call-by-value.
Here we have initialized a variable ‘data’ with some value and used the pass-by-value technique
to show how the value of the variable remains unchanged. In the next segment, we will try to
show a similar example, but we will use non-primitives.
Ex:
class CallByValue{
int data=50;
void change(int data){
[Link]=data+100;//changes will be in the local variable only
}
public static void main(String args[]){
CallByValue c=new CallByValue();
[Link]("before change "+[Link]);
[Link](500); //calling method by passing value
[Link]("after change "+[Link]);
}
}
Output:
E:\core java\unit-2>javac [Link]
E:\core java\unit-2>java CallByValue
before change 50
after change 600
E:\core java\unit-2>
Java Passing Object: Pass by Reference Example
In this example, we will see how to pass any object of a class using pass-by-reference.
As you can see, when we have passed the object reference as a value instead of a value, the
original value of the variable ‘data’ is changed to 20. This is because of the changes in the called
method.
13
Ex:
class CallByReference{
int data=50;
void change(CallByReference c){
[Link]=[Link]+100;//changes will be in the instance variable
}
public static void main(String args[]){
CallByReference op=new CallByReference ();
[Link]("before change "+[Link]);
[Link](op);//calling method by passing object reference
[Link]("after change "+[Link]);
}
}
Output:
E:\core java\unit-2>javac [Link]
E:\core java\unit-2>java CallByReference
before change 50
after change 150
E:\core java\unit-2>
Keyword this
The keyword this provides reference to the current object.
Ex:
class Add
{
int a,b;
void setValues(int a, int b)
{
this.a = a;
this.b = b;
}
void add()
{
[Link]("Sum = "+ (a+b) );
}
}
class ThisKeywordEx
{
public static void main (String args[])
{
Add obj= new Add();
[Link](10,20);
[Link]();
}
}
Output:
E:\core java\unit-2>javac [Link]
E:\core java\unit-2>java ThisKeywordEx
Sum = 30
E:\core java\unit-2>
Methods
Introduction
A method in Java represents an action on data or behavior of an object.
In other programming languages, the methods are called functions or procedures.
A method is an encapsulation of declarations and executable statements meant to execute desired
operations.
14
Defining Methods
A method definition comprises two components:
1. Header that includes modifier, type, identifier, or name of method and a list ofparameters.
• The parameter list is placed in a pair of parentheses.
2. Body that is placed in braces ({ }) and consists of declarations and executable
statement and other expressions.
Method definition:
Modifier return_type method_name (datatype Parameter_Name,…)
{
/*Statements --
Body of the method*/
}
Modifier description is as follows.
Ex:
class Add
{
int a,b;
void setValues(int x, int y) // method with two arguments
{
a = x;
b = y;
}
void add() // method without arguments
{
[Link]("Sum = "+ (a+b) );
}
}
class MethodDemo
{
public static void main (String args[])
{
Add obj= new Add();
[Link](10,20); // method calling
[Link]();
}
}
15
Output:
>javac [Link]
>java MethodDemo
Sum = 30
Overloaded Methods
Binding
Associating / linking / resolving the method call to the method definition is known as binding.
We have two kinds of binding
o Static Binding
o Dynamic Binding
Static Binding is when the linking of method call to the method definition happens at the
compilation time, such binding is called as static / early / compile time binding.
Dynamic Binding is when if the linking of method call to the method definition happens at
program execution time, such type of binding is known as dynamic / late / runtime binding.
Note:-
When method names same and binding involved is static, we say that static polymorphism is
implemented.
If binding involved is dynamic we say that dynamic polymorphism is implemented.
To implement the object oriented feature polymorphism we are taking the help of method
overloading and method overriding (language features).
Q) Write a program to implement static polymorphism (method overloading).
class Policy
{
int policyno;
String name;
float premium;
void giveDataToPolicy(int pno,String name,float premium)
{
policyno=pno;
[Link]=name;
[Link]=premium;
}
void giveDataToPolicy(float pr)
{
premium=pr;
}
void displayPolicyDetails()
{
[Link]("....policy no....:"+policyno);
[Link]("....pname....:"+name);
}
}
class MethodOverloadingEx
{
public static void main(String args[])
{
Policy p1=new Policy();
[Link](1001,"Rama",1000);
[Link]();
[Link](1000);
[Link]("....after modifying policy details....");
[Link]();
}
}
Output:
16
E:\core java\unit-2>javac [Link]
E:\core java\unit-2>java MethodOverloadingEx
....policy no....:1001
....pname....:Rama
...after modifying policy details....
....policy no....:1001
....pname....:Rama
E:\core java\unit-2>
One Entity (object) behaving differently in different situations is known as polymorphism.
In Object oriented system we have two kinds of objects.
o Monomorphic Object
o Polymorphic Object
An object is said to be monomorphic if it is behaving uniquely in all the situations.
One interface multiple forms is the concept of polymorphism.
Polymorphism offers extensibility of code.
It offers flexibility in application development.
Overloaded Constructor Methods
Overloading
Defining a constructor with same name and with different parameters (different signatures) is
called constructor overloading.
Q) Write a program on constructor overloading.
class Book
{
int isbn;
String title;
float price;
Book()
{
isbn=123456;
title="java complete reference";
price=310;
}
Book(int a)
{
isbn=123456;
title="java complete reference";
price=310;
}
Book(int n,String t,float p)
{
isbn=n;
title=t;
price=p;
}//perameterized constructor
void displayItemDetails()
{
[Link](isbn);
[Link](title);
[Link](price);
}
}
class ConstructorOverloadEx
{
public static void main(String []args)
{
17
Book b1=new Book();
[Link]("First Book Details .........");
[Link]();
Book b2=new Book(123456,"Head First java",400);
[Link]("Second Book Details .........");
[Link]();
}
}
Output:
E:\core java\unit-2>javac [Link]
E:\core java\unit-2>java ConstructorOverloadEx
First Book Details .........
123456
java complete reference
310.0
Second Book Details .........
123456
Head First java
400.0
E:\core java\unit-2>
Class Objects as Parameters in Methods
Objects can be passed as parameters to the Methods just like pr imit ive data types.
It is called as Call by Reference.
Ex:
class AddDemo
{
int a,b;
void add(AddDemo obj2) // method with Object as anargument
{
Syst [Link] ln("Sum = "+ (obj2.a + obj2.b));
}
}
class Object AsParamet ers
{
public static void main (String args[])
{
AddDemo obj1= new AddDemo(); obj1.a=180;
obj1.b=50; [Link](obj1) ;
}
}
Output:
E:\core java\unit-2>javac Object AsParamet ersEx. java
E:\core java\unit-2>java ObjectAsParametersEx
Sum = 230
E:\core java\unit-2>
Access Control
See this topic above.
Recursive Methods
A Method which is calling itself is called as Recursive Method.
Ex: Recursive method to find factorial of a given number.
class Fact
{
int factorial (int n)
{
if(n<2)
return n;
18
else
return n*(factorial(n-1));
}
}
class RecursiveEx
{
public static void main(String[] args)
{
Fact obj =new Fact();
int n=5;
int res = [Link](n);
[Link]("Factorial of " + n + " = " +res);
}
}
Output:
E:\core java\unit-2>javac [Link]
E:\core java\unit-2>java RecursiveEx
Factorial of 5 = 120
E:\core java\unit-2>
Nesting of Methods
A method calling in another method with in the class is called as Nesting ofMethods.
Ex:
class Rectangle
{
void perimeter(int l, int w)
{
[Link]("Length ="+l+", Width= "+w);
[Link]("Perimeter = " + (l+w));
}
void area(int l, int w)
{
perimeter(l,w); // Nesting of Method
[Link]("Area = " + (l*w));
}
}
class NestingOfMethodsEx
{
public static void main(String[] args)
{
Rectangle obj = new Rectangle();
[Link](5,4);
}
}
Output:
E:\core java\unit-2>javac [Link]
E:\core java\unit-2>java NestingOfMethodsEx
Length =5, Width= 4
Perimeter = 9
Area = 20
E:\core java\unit-2>
Overriding Methods
See this topic in Inheritance in unit-3.
Attributes Final and Static
See Attribute Final from UNIT-1
See Static Variable and Method from UNIT-1