Unit 3 in Java R&R
Unit 3 in Java R&R
, KAKUTURU
class Person
{
//properties-instance variables
string name;
int age;
//actions - methods
void talk()
{
System.out.println("Hello am"+name);
System.out.println("my age is "+age);
}
}
Object creation:-
The class code along with method code is stored in 'method area' of the JVM. When an
object is created, the memory is allocated on 'heap'. After creation of an object, JVM
produces a unique reference number for the object from the memory address of the
object. This reference number is also called hash code number.
To know the hashcode number of an object, we can use hashCode() method of object
class, as shown here:
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
write a program to create a person class and an object raju to person class. Let us
display the hash code number of the object, using hashCode().
import java.lang.*;
class Person
{
//properties - variables
String name;
int age;
//actions - methods
void talk()
{
System.out.println("Hello am"+name);
System.out.println("My age is"+age);
}
}
class Demo
{
public static void main(String args[])
{
//create person class object:raju
person raju=new person();
//call the talk() method
raju.talk();
//find the hash code of object
System.out.println("hash code="+raju.hashCode());
}
}
OUTPUT:-
c:\> javac Demo.java
c:\>java Demo
hash code=1671711
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
The hash code displayed by the preceding program may vary from system to system
and dependent on the internal memory address by the JVM.
import java.lang.*;
class Demo
{
public static void main(String args[])
{
//create person class object: raju
Person raju=new Person();
//initializing the instance variables using the reference
raju.name="raju";
raju.age="22";
//call the talk() method
raju.talk();
}
}
OUTPUT:-
c:\> javac Demo.java
c:\> java Demo
hello am raju
my age is 22
Access specifiers
An access specifier is a keyword that specifies how to access the members of a class or
a class itself. There are four access specifiers:
Private: 'private' members of a class are not accessible anywhere outside of the class.
There are accessible only inside of the class.
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
public: 'public' members of a class are every where outside of the class. So any other
program can read them and use them.
protected: 'protected' members of a class are accessible outside the class, but
generally within the same directory.
default: If no access specifier is written by the programmer, then the java compiler
uses a 'default' access specifier. these are accessible outside of the class but same
directory.
write a program to initialize the instance variables directly within the class
import java.lang.*;
class Person
{
//instance variables are initialized here
private string name="manasa";
private int age="21";
//methods
void talk()
{
System.out.println("Hello am"+name);
System.out.println("My age is"+age);
}
}
class Demo
{
public static void main(String args[])
{
//create person class object: manasa
Person manasa=new Person();
//call the talk() method
manasa.talk();
//create another person class object: sita
sita.talk();
}
}
OUTPUT:-
c:\>javac Demo.java
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
Constructor
A constructor is a similar to a method that is used to initialize the instance variables.
The sole purpose of a constructor is to initialize the instance variables. Java
constructor is invoked at the time of object creation. The following are characteristics:-
The constructor name and class name should be same, and the constructor's
name should end with a pair of simple braces.
A constructor may have or may not have parameters. parameters are variables
to receive data from outside into the constructor. if a constructor doesn't have
parameters i.e., default parameter, if a parameter have 1or more than one i.e.,
parameterized constructor.
//instance variables
private string name;
private int age;
//default constructor
person()
{
name="manasa";
age="21";
}
//method
void talk()
{
System.out.println("Hello am"+name);
System.out.println("My age is"+age);
}
}
class Demo
{
public static void main(String args[])
{
//create manasa object, here default constructor is called.
Person manasa=new Person();
//call the talk() method
manasa.talk();
//create another object m
Person m=new Person();
m.talk();
}
}
OUTPUT:-
c:\> javac Person.java
c:\> java Person
hello am manasa
my age is 21
hello am manasa
my age is 21
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
parameterised constructor
}
class Demo
{
public static void main(String args[])
{
//create manasa object, here default constructor is called.
Person manasa=new Person();
//call the talk() method
manasa.talk();
//create m object. here parameterised constructor is called.
person m=new person();
//call the talk() method
m.talk();
}
}
OUTPUT:-
c:\> javac Person.java
c:\> java Person
hello am manasa
my age is 21
hello am manasa
my age is 21
****************
METHODS IN JAVA
write a program for a method without parameters but with a return type.
import java.lang.*;
class Sample
{
private double num1,num2; //instance variables
sample(double x, double y)
{
num1=x;
num2=y;
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
}
double sum()
{
double res=num1+num2;
return res;
}
}
class Methods
{
public static void main(String args[])
{
Sample s=new Sample(10,22.5);
double x=s.sum(); //call the method and store the result in x
System.out.println("sum="+x);
}
}
OUTPUT:-
c:\>javac Method.java
c:\>java Method
sum=32.5
Static Method
A static method is a method that does not act upon instance variables of a class.
A static method is declared by using the keyword ‘static’. Static methods are called by
using the Classname.methodname(). The reason why static methods cannot act on
instance variables is that the JVM first executes the static methods then only it create
the objects. Since the objects are not available at the time of calling the static
methods. The instance variables are also not available.
Program: Write a program to test whether a static method can access the instance
variables are not
int x;
// parameterized constructor
Test (int x)
{
this.x=x;
}
// static method can accessing x values
static void access()
{
System.out.println(“x=”+ x);
}
}
class Demo
{
public static void main(String args[])
{
Test obj=new Test(55);
Test.access();
}
}
Output:
Syste.out.println(“x=”+ x):
Program: Write a program to test whether a static method can access a static variable
or not.
}
}
class Demo
{
Public static void main(String args[])
{
Test.access();
}
}
Outout:
C:\> javac Demo.java
C:\> java Demo
X=55
Static Blocks
JVM executes a static block on a highest priority basis. This means JVM first goes to a
static block even before it looks for the main() method in the program. This can be
understood from the below program
Program: Write a program to test which are executed by JVM, the basic block are
static method.
System.out.println(“Static method”);
}
}
Output:
C:\> javac Test.java
C:\> java Test
Static block
Static method
THIS keyword
This is a keyword that refers to the object of class where is used. In other words, this
refers to the object of present class. Generally we write instance variables,
constructors and methods in a class. All these members are referenced from by ‘this’.
When an object is created to the class, a default reference is also created internally to
the object. The default reference is nothing but ‘this’. So, ‘this’ can refer to all the
things of the present object.
Program: Write a program to use ‘this’ to refer the current class and parameterized
constructor.
// method
void access()
{
System.out.println(“x=”+x);
}
}
class ThisDemo
{
public static void main(String args[])
{
Sample.s=new Sample();
}
}
Output:
C:\> javac ThisDemo.java
C:\> java ThisDemo
x=55
INSTANCE METHOD
Instance methods are the methods which are act upon the instance variables. To call
the instance methods object is needed, since the instance variable contained in the
object. We call the instance methods by using objectname.methodname(). It can
access static variables directly.
There are two types of instance methods:
Accessor methods
Mutator methods
Accessor methods are the methods that are simply access or read the instance
variables. They do not modify the instance variables. Mutator methods can access and
also modify the instance variables
Output:
C:\> javac Methods.java
C:\> java Methods
Name= Raju
Age= 20
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
Primitive data types are fundamental data types represent single entities or single
values. For example char, byte, short, int, long, float, double and Boolean are called
primitive data types. They are passed to method by values. If any changes are made
them inside the method will not affect them outside the method.
We can also pass class objects to methods, and return objects from the
methods. For example,
Employee myMethod(Employee obj)
{
statements;
return obj;
}
}
class PassObjects
{
public static void main(String args[])
{
//take two Employee class objects
Employee obj1=new Employee(10);
Employee obj2=new Employee(20);
//create Check class object
Check obj=new Check();
//display data before calling
System.out.println(obj1.id+”\t”+obj2.id);
//call swap and pass Employee class objects
obj.swap(obj1, obj2);
//display data after calling
System.out.println(obj1.id+”\t”obj2.id);
}
}
Output:
C:\> javac PassObjects.java
C:\> java PassObjects
10 20
10 20
Example:
int[] myMethodd(int arr[][])
import java.io.*;
class Primes
Boolean isPrime=true;
for(int i=2;i<=num-1;i++)
if(num %i==0)isPrime=false;
return isPrime;
Long c=1,num=2;
while(c<=max)
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
System.out.println(num);
++c;
++num;
class PrimeDemo
int max=Integer.parseInt(br.readLine());
Primes.generate(max);
}
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
output:
c:\> javac PrimeDemo.java
11
13
17
19
23
29
Recursion
A method calling itself is known as a ‘recursive method’, and this phenomenon is
called’recursion’. It is possible to write recursive methods in java. Let us take an
example to find factorial value of a given number. Factorial value for a number num is
defined as: num*(num-1)*(num-2)*….*1.
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
class Kist
long fact=1;
while(num>0)
fact *=num--;
return fact;
{
System.out.println(“Factorial of s=”);
System.out.println(“NoRecursion.factorial(5));
Output :
C:/> javac Kist.java
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
Factorial of s: 170
Factory Method
Factory methods are static methods only. But their intention is to create an object
depending on the user choice, precisely, a factory method is a method that returns an
object to the class,to which a belongs.For example, getNumberInstance() is a factory
method.why? Because it belongs to NumberFormat class and returns an object to
NumberFormat class.
class Circle
double area=PI*r*r;
System.out.println(“Area=”+area);
Output:
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
Area=755.0714285714286
Example:
interface Fees{
import java.io.*;
interface Fees{
}
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
return 60000.00;
return 55000.50;
class CourseFees{
if(course.equalsIgnoreCase(“CSE))
else if(course.equalsIgnoreCase(“ECE”))
}
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
/*using the factory method getFees() to display any course fees depending on user
option */
class Myclass
String name=br.readLine();
Fees f=CourseFees.getFees(name);
output:
c:\> javac Myclass.java
c:\>java Myclass
to pass more than 2 values to this method.we should write a new method every time,
when we change the number of arguments.on the other hand,think that if the same
method can accept any number of arguments, then that method would be very useful
to the programmer.
EX:
Int sum(int a, int b)
class VArgs
int max=x[0];
for(int i=1;i<x.length;i++)
/* If the biggest is less than the other number then take that other number as
biggest.*/
if(max<x[i]) max=x[i];
return max;
int arr1[]={20,10,5,35,40};
int result=max(arr1);
System.out.println(“Maximum=”+result);
Int arr2[]={1,2,3};
Result=max(arr2);
System.out.println(“Maximum=”+result);
Result=max(10,30);
System.out.println(“Maximum=”+result);
}
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
Output:
C:\> javac VArgs.java
Maximum=40
Maximum=3
Maximum=30.
Example:
class One
{
Two t; //t is a reference of class Two
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
}
write a program to take class One and class Two, and create reference of class Two
in class One. Using this reference, refer to the instance variables and methods of
class Two.
import java.lang.*;
//relating class Two with class One
class One
{
//instance variables
int x;
Two t;// class Two's reference
//constructor that receives Two's reference
One(Two t)
{
//copy Two's reference into t
this.t=t;
x=10;
}
//method to display cass One and class Two variables
void display()
{
System.out.println("one's x="+x);
//call class Two's method
t.display();
//access class Two's variable
System.out.println("Two's var="+t.y);
}
}
class Two
{
//instance variables
int y;
//initialize y
Two(int y)
{
this.y=y;
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
}
//method to display y
void display()
{
System.out.println("Two's y="+y);
}
}
class Relate
{
public static void main(String args[])
{
Two obj2=new Two(22) //object creation and stores 22
One obj1=new One(obj2);//stores obj2
obj1.display();//calls class One's method
}
}
OUTPUT:-
c:\> javac Relate.java
c:\> java Relate
One's x=10
Two's y=22
Two's var=22
INNER CLASS
Inner class is a class written within another class. Inner class is basically a
safety mechanism, since it is hidden from other classes in its outer class.
To make instance variables not available outside the class, we use 'private' access
specifier to protect the class and variables inside the class. but that class is not
available to java compiler in JVM.so it is illegal.
But, 'private' is allowed before an inner class to provide security to entire inner
class.yhus it is not available to other classes. This means an object to inner class
cannot be cfeated any other class.
write a program to create the outer class BankAcct and the inner class Interest in it.
import java.lang.*;
//this is the outer class
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
class BankAcct
{
//balance amount is the variable
private double bal;
//initialise the balance
BankAcct(double b)
{
bal=b;
}
//in this method, inner class object is created after verifying
// the authentication of user, r is rate of interest
//this method accepts rate of interest r
void contact(double r) throws IOException
{
//accept the password from keyboard and verify
BufferedReader br=new BufferedReader(new InputStreamReader
(System.in));
System.out.println("enter password");
string paswd=br.readLine();
if(paswd.equals("xyz123"));
{
//if password is correct then calculate interest
Interest in=new Interest(r);
in.calculateInterest();
}
else
{
System.out.println("sorry, u are not an authorised person");
return;
}
}
//inner class
private class Interest
{
//rate of interest
private double rate;
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
OUTPUT:-
c:\>javac InnerClass.java
c:\>java InnerClass
Enter password: xyz123
updated bal=10950.0
It is an inner class without a name and for which only a sigle object is created.
Anonymous Inner classes are very useful in writing implementation classes for listener
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
write a program by taking Myclassas an anonymous inner class whose name is not
mentioned in the 'Mad' class's addActionListener() method
import java.awt.*;
import java.awt.event.*;
class But extends Frame
{
But()
{
//create a push button b
Button b=new Button("ok");
//add push button to frame
add(b);
//add action listener to button
//Myclass is hidden inner class of Action listener interface
//whose name is not written but an object to it created
b.addActionListener(newActionListener()
{
//this method is executed when button is clicked
public void actionperformed(ActionEvent ae)
{
//exit the application
System.exit(0);
}
);
}
}
public static void main(String args[])
{
//create a frame by creating But class object
But obj=new But();
obj.setSize(400,300);
obj.setVisible(true);
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
}
}
OUTPUT:-
c:\>javac But.java
c:\>java But
INHERITANCE
Inheritance is a concept where new classes can be produed from exsting classes.
The newly created class aquires all the features of the existing class from where it is
derived. Inheritance is used in java for method overriding and for code reusability. It is
one of the key feature of oop. To inherit the features from super class to sub class, we
will use extends keyword ..where as in c++ we will use public keyword
syntax:
class Super
{
..............;
.............;
}
class Sub extends Super
{
...........;
}
Example:-
write a program to display sum, product and difference between two numbers.
import java.lang.*;
class Calculation
{
int z;
public void addition(int x,int y)
{
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
z=x+y;
System.out.println("sum of two numbers is="+z);
}
public void subtraction(int x,int y)
{
z=x-y;
System.out.println("subtraction of two numbers is="+z);
}
}
public class Final extends Calculation
{
public static void main(String args[])
{
public void multiplication(int x,int y)
{
z=x*y;
System.out.println("multiplication of two numbers is="+z);
}
int a=20,b=10;
Final mca=new Final();
mca.addition(a,b);
mca.subtraction(a,b);
mca.multiplication(a,b);
}
}
OUTPUT:-
c:\>javac Final.java
c:\>java Final
addition of two numbers=30
subractionof two numbers=10
multiplication of two numbers=200
If we create an object to the super class, we can access only super class methods.
when we create object to sub class we can access both super and sub class objects.
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
sometimes, super class and sub class members may have same names, In that case by
default sub class members are accessible.
write a program to access the super class method instance variables by using super
keyword from sub class.
import java.lang.*;
class one
{
int i=10; //super class variable
void show() //super class method
{
System.out.println("super class method: i="+i);
}
}
class Two extends One
{
int i=20; //sub class variable
void show() //sub class method
{
System.out.println("sub class method:i="+i);
super.show(); //using 'super' keyword to call super class method(One class)
//using super to access super class variables i.e., One class
System.out.println("super i="+super.i);
}
}
class Super1
{
public static void main(String args[])
{
Two t=new Two(); //create sub class object
t.show(); //this will call sub class method only i.e., Two class method
}
}
OUTPUT:-
c:\>javac Super1.java
c:\>java Super1
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
The 'private' members of super class are not accessible to sub class directly. But
sometimes it need to access super class variables in sub class. For this purpose we use
'protected' keyword to access super class variables directly to the sub class variables.
enter age=21
Types of Inheritance
1.single Inheritance:
producing sub classes from a single super class is called "single Inheritance". In this a
single super class will be there. There can be one or more sub classes.
syntax:class Super
{
}
class Sub extends Super
{
}
2.Multiple Inheritance:
producing sub classes from multiple super classes is called "Multiple Inheritance".
There can be more than one super class and one or more sub classes.
syntax:
class Super
{
}
class Sub
{
}
class Final extends Super,Sub
{
}
NOTE:
Multiple inheritance is available in c++, whis is not available in java. This leads to
dissappointment in java programmers. A java programmer wishes to use multiple
inheritance in some cases. Javasoft people have provided interface concept,
expecting the programmers to acheive multiple inheritance by using multiple
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
Department Bird
Employee
Peacock Parrot Sparrow
Class employee extends Department
Multiple Inheritance:
Tea
Child 1 Child 2
class Child1 extends Father, Mother class Tea extends Milk, Sugar, Tea-Powder
class Child2 extends Father, Mother
x x
class A class B
x
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
***
Polymasrphism
Polymorphism is one of the best feature of object oriented programming language. Actually it a greek word
which is the combination of the two words , poly and marphism.poly means many and marphism means forms
so polymarphism means many forms.In java , avariable,an object or a method can exist in different forms.in
this concept the same variable or method can perform different tasks.so the programmer has more flexible to
write code .
STATIC POLYMARPHISM : The polymarphism exhibited at the compilation time is called Static
Polymarphism. Here the java compailar knows wothout any ambiguity which method is called at the time
of compilation. Ofcourse JVM executes method later, but the compiler knows and can bind the method
call with method code(body)at the time of compailaton.so it is also called static biniding.or compail time
polymarphism.
A static method is a method whose single copy in memory is shared by all the objects of lthe class.
Class One
{ System.out.println(“square value=”+(x*x));
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
class Poly
o.calculate( 25);
DYNAMIC POLYMARPHISM : The Polymarphism exhibited at runtime is called dynamic plymorphism. This
means when a method is called , the method call is bound to the method body at the time of running the
program, dynamically. In this case the compailar does not know which method is called at the time of
compilation. Only JVM knows at runtime which method is to be executed. Hence this is also called runtime
polymarphism or dynamic binding .
FOR EXAMPLE :
Consider a class sample with two instance methods having same name as
}
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
Void add
Here the bodies of the methods are different and they perform different tasks. Now who will decide which
mehtod is to be executed ? java compiler or JVM. Because the method are called by the objects. So java
compiler cannot decide at the time of compilation which mehtod is actually called by the user. It has to wait
till the object is created for Sample Class.so the objects are created by the JVM at run time .Now JVM should
decide which method is actually called by the user at runtime(dynamically).
Here JVM recognizes the signatures of the methods ie,nothing but the parameters passed in side the method
and execurte.
class Sample
} }
class Poly
s.add(10,20,30);
}
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
Private methods are methods which are declared by using the access specifier ‘private’ . This
access specifier makes the method non available outside the class. So other programmers cannot
access the private methods. Even private methods are not available in the sub classes. This
means there no possibility to override the private methods of the super class in its sub classes.
So only method overloading is possible in case of private methods
The method in super class and method in sub class act as different methods. The super
class will get its own copy and sub class will have it own copy. It does not come under method
overriding.
The only way to call private methods of a class is by calling them with in the class. For this
purpose, we should create a public method and call the private method within it. When this
public method is called, its called the private method.
For example:
class A
{
final void method1()
{
System.out.println(“Hello”);
}
}
class B
{
void method2()
{
A.method(); //call the final method
}
}
Now JVM physically copies the code of method1() into method2() of class B as:
class B
{
void method2()
{
System.out.println(“Hello”);// body of final method copied
}
}
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
Final class
A final class is a class which is declared as ‘final’. ‘final’ keyword befor a class prevents inheritance this means
sub classes cannot be created in a final class.
For example:
final class A
class B extends A //invalid
Program:
Write a program to show how to override the calculateBill() method of commercial class inside the Domestic
class.
Output:
C:\> javac ElectricityBill.java
C:\> java ElectricityBill
Customer: Raj kumar
Bill amount= 500.0
Customer: Vijaya lakshmi
Bill amount= 250.0
5. method overloading is done when the programmer 5. method overriding is done when the programmer
wants to extends the already available feature. wants to provide a different implementation (body of
the method)for the same feature.
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU
6. method overloading is code refinement. Same 6. method overriding is code replacement . the sub
method is refined to perform the different task. class method overrides (replaces )the super class
method .