0% found this document useful (0 votes)
20 views47 pages

Unit 3 in Java R&R

Uploaded by

vinaydarling063
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views47 pages

Unit 3 in Java R&R

Uploaded by

vinaydarling063
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 47

KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY.

, KAKUTURU

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

CLASSES AND OBJECTS


A class is a model for creating objects. This means the properties and actions of the
objects are written in the class. Properties are represented by variables and actions of
the objects are represented by methods. So a class contains variables and methods.
The same variables and methods are also available in the objects because they are
created from the class. These variables are also called as "Instance variables" because
they are created inside the object(instance). For example,

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

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

Employee e1=new Employee(); //e1 is a reference of Employee object


System.out.println(e1.hashCode()); //displays hash code stored in e1

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

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

The hash code displayed by the preceding program may vary from system to system
and dependent on the internal memory address by the JVM.

Initializing the Instance variables:-


It is the duty of the programmer to initialize the instance variables, depending on his
reqirements. There are various ways to do this. First way is to initialize the instance
variables of one class(person class) in the other class(Demo class). For example,

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

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

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

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

c:\> java Demo


hello am manasa
my age is 21
hello am manasa
my age is 21

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.

 A constructor does not return any value, not even void.

 A constructor is automatically called and executed at the time of creating an


object. while creating an object no parameters are passed then default
constructor is called otherwise parameterized constructor is called.
 A constructor is called and executed only once per object. this means when we
create an object constructor is called, when we create second object again the
constructor is called second time.
NOTE
A constructor is called concurrently when the object creation is goin on. JVM first
allocates memory for the objet and then execute the constructor to initialize the
instance variables. By the time, object creation is completed the constructor execution
is also completed.

write a program by using a default constructor to initialise the instance variables


import java.lang.*;
class Person
{
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

//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

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

parameterised constructor

when we passed values or arguments or parameters in side the constructor is said to


be a parameterized constructor. This constructor which accepts data from outside and
initialized the instance variables with that data.

write a program to initialize the instance variables of a class using parameterised


constructor
import java.lang.*;
class Person
{
//instance variables
private string name;
private int age;
//default constructor
person()
{
name="manasa";
age="21";
}
//parameterised constructor
person(string s,int i)
{
name=s;
age=i;
}
//method
void talk()
{
System.out.println("Hello am"+name);
System.out.println("My age is"+age);
}
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

}
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

A method represents a group of statements that performs a task. Here 'task'


represents a calculation or processing of data or generating a report,etc., A method
has two parts:
1.Method header or method prototype
2.Method body
Method Header or Method Prototype:
It contains method name, method parameters and method return datatype. Method
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

prototype is written in the form of:


returndatatype methodname(parameter1,parameter 2,....)
Method Body:
Below the method header,we should write the method body. Method body consists of
a group of statements which contains logic to perform the task. Method body can be
written as:
{
statements:
}
Example:- {
string name="manasa";
int age=21;
}
A method cannot return more than one value.the following are invalid statements
1.return x,y;//invalid
2.return x; return y; //invalid
Understanding Methods
to understand how to write methods, let us take a simple example program. We write
Sample class with two instance variables num1,num2. To find the sum of these
values,as follows:
void sum()
{
double res=num1+num2;
System.out.println("sum="+res)
}

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

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

}
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

//static method trying to access the instance variables


class Test
{
// instance var
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

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:

C:\> javac Demo.java

Demo.java:16: non static variable cannot be referenced from a static context

Syste.out.println(“x=”+ x):

Program: Write a program to test whether a static method can access a static variable
or not.

// static method accessing a static variable


class Test
{
// static variable
static int x=55;
//static method accessing x value
static void access()
{
System.out.println(“x=”+ x):
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

}
}
class Demo
{
Public static void main(String args[])
{
Test.access();
}
}

Outout:
C:\> javac Demo.java
C:\> java Demo
X=55

Static Blocks

A static block is a block of statements declared as static , something like this


static {
statements;
}

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.

// static block or static method?


class test
{
static
{
System.out.println(“Static block”);
}
Public static void main(String args[])
{
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

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.

//this refers to all the members of a present class


class Sample
{
// x is a instance variable
private int x;
//default constructor
Sample()
{
this(55); //call the present class para constructor and
send 55
this.access(); //call present class method
}
// parameterized constructor
Sample(int x)
{
this.x=x; // refer present class instance variable
}
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

// 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

Program: Write a program to create a Person class object.


// Accessor and mutator methods
Class Person
{
//instance variables
private String name;
private int age;
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

//mutator methods to store data


public void setName(String name)
{
this.name=name;
}
public void setAge(int age)
{
this.age=age;
}
//accessor methods to read data
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
class Methods
{
public static void main(String args[])
{
//create an empty Person class object
Person p1=new Person();
//store some data into the object
p1.setName(“Raju”);
p1.setAge(20);
//access data from object
System.out.println(“Name=”+p1.getName());
System.out.println(“Age=”+p1.getAge());
}
}

Output:
C:\> javac Methods.java
C:\> java Methods
Name= Raju
Age= 20
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

Passing Primitive Data Types To methods

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.

Program: Write a program to interchange two integers 10 and 20 by passing them to


swap() method.
//Primitive data types are passed to methods by value
class Check
{
//to interchange num1 and num2 values
void swap(int num1,int num2);
{
int temp; //take a tempory variable
temp=num1;
num1=num2;
num2=temp;
}
}
class PassPrimitive
{
public static void main(String args[])
{
//take two primitive data types
int num1=10, int num2=20;
//create a Check class object
Check obj=new.Check();
//display data before calling
System.out.println(num1+”\t”+num2);
//call swap and pass primitive data types
Obj.swap(num1, num2);
//display data after calling
System.out.println(num1+”\t”+num2);
}
}
Output:
C:\> javac PassPrimitive.java
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

C:\> java PassPrimitive


10 20
10 20

Passing Objects To Method

We can also pass class objects to methods, and return objects from the
methods. For example,
Employee myMethod(Employee obj)
{
statements;
return obj;
}

Program: Write a program to interchange two Employee objects by passing them to


swap() method

//objects are also passes to methods by value


Class Employee
{
//instance variable
int id;
//to initialize id value
Employee(int id)
{
this.id=id;
}
}
class Check
{
//to interchange Employee class objects
void swap(Employee obj1, Employee obj2)
{
Employee temp; //take a temporary reference
temp=obj1;
obj1=obj2;
obj2=temp;
}
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

}
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

Passing Array to Methods:


Just like objects are passed to methods,it is also possible to pass arrays to methods
and return arrays from methods.In this case,an array name should be understood as
an object reference.

Example:
int[] myMethodd(int arr[][])

program: write a program to generate required number of primes using


methods.
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

//prime number series

import java.io.*;

class Primes

//to test and return true if num is prime

static Boolean prime(long num)

//initially isprime is true,it becomes false if

//num is not prime

Boolean isPrime=true;

//from 2 to num-1,if any number divides num,it is not prime

for(int i=2;i<=num-1;i++)

if(num %i==0)isPrime=false;

return isPrime;

//accept how many primes required into max.

//c is counter for no.of primes generated.

static void generate(Long max)

Long c=1,num=2;

while(c<=max)
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

if(prime(num)) //call prime() method directly

System.out.println(num);

++c;

++num;

class PrimeDemo

public static void main(String args[]) throws IOException

//accept the number of primes are needed

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.print(“Hoe many primes?”);

int max=Integer.parseInt(br.readLine());

/generate max number of primes

Primes.generate(max);

}
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

output:
c:\> javac PrimeDemo.java

c:\> java PrimeDemo

How many primes? 10

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

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

Program: Wrire a program to find factorial value without recursion.

//Factorial without Recursion

class Kist

static long factorial(int num)

long fact=1;

while(num>0)

fact *=num--;

return fact;

public static void main (String args[])

{
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

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

C:/> java Kist

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.

Program: write a program for calculating and displaying area of a


circle.The area is not formatted and displayed as it is.
//Area of a circle

class Circle

public static void main (String args[])

final double PI=(double )22/7; //constant

double r=15.5; //radius

double area=PI*r*r;

System.out.println(“Area=”+area);

Output:
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

C:\> javac Circle.java

C:\> java Circle

Area=755.0714285714286

Creating our own factory methods


We already understood that the aim of a factory method is to create an object
depending on the user option. we have used an already existing factory method
getNumberInstance() of NumberFormat class in the previous program. Now, we wish to
know how to create such a factory method on our own. Any factory method is created
as a method belonging to an interface or abstract class. Hence, that method is
implemented in the implementation classes or sub classes as the case may be.

Example:
interface Fees{

double showFees(); //this method does not have body

Program : write a program to create a factory method to display course


fees depending on the user’s choice.
//creating our own factory method

import java.io.*;

//an interface with an abstract method

interface Fees{

double showFees(); //this method does not have body

}
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

//implementation class to implement showfees() method

class CSE implements Fees{

public double showFees(){

return 60000.00;

//another implementation class to implement showFees()

class ECE implements Fees{

public double showFees(){

return 55000.50;

//factory class with a factory method getFees()

class CourseFees{

public static Fees getFees(String course){

if(course.equalsIgnoreCase(“CSE))

return new CSE();

else if(course.equalsIgnoreCase(“ECE”))

return new ECE();

else return null;

}
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

/*using the factory method getFees() to display any course fees depending on user
option */

class Myclass

public static void main(String args[]) throws IOException

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.print(“Enter course name:”);

String name=br.readLine();

Fees f=CourseFees.getFees(name);

System.out.println(“The fees is Rs.”+f.showFees());

output:
c:\> javac Myclass.java

c:\>java Myclass

Enter course name:cse

The fees is Rs.60000.00

Methods with Variable Arguments


Suppose,we write a method in the form. Sum(int a,int b).Since this method has only 2
parameters. We can pass only 2 arguments or value to this method. It is not possible
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

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)

Int sum(int a, int b, int c)

Int sum (int a, int b, int c, int d)

Program:write a method with variable arguments that accepts a group of


numbers and returns the biggest number among them.
//Demo of varargs method to find biggest number.

class VArgs

/*This is varargs method.it can accept arbitrary number of arguments.*/

static int max(int …. X)

//take the first number in the array as biggest

int max=x[0];

//compare the biggest number with other numbers


KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

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 the biggest number

return max;

public static void main(String args[])

{ //pass any array of 5 elements to varargs method

int arr1[]={20,10,5,35,40};

int result=max(arr1);

System.out.println(“Maximum=”+result);

//pass an array of 3 elements to varargs method

Int arr2[]={1,2,3};

Result=max(arr2);

System.out.println(“Maximum=”+result);

//pass 2 individual elements to varargs method

Result=max(10,30);

System.out.println(“Maximum=”+result);

}
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

Output:
C:\> javac VArgs.java

C:\> java VArgs

Maximum=40

Maximum=3

Maximum=30.

RELATIONSHIP BETWEEN OBJECTS


It is possible to create objects for different classes and establish relationship
between them. When the objects are related, it is a possible to access and use
members of one object in another object. This becomes an advantage when an object
should start processing data where another obbject has left. It is also helpful to pass
data from one object to another object and from there to another object in a chained
form.
There are three ways to relate objects in java:
1. using references
2. using Inner class object
3. using Inheritance
Relating objects using References:-
let us create two classes, 'One' and 'Two'. suppose we want to access the members of
class Two, in class One, we should relate their objects. For this just declare the
reference variable of class Two as an instance variable in class One.

Example:

class One
{
Two t; //t is a reference of class Two
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

}
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

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

}
//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

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

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

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

//initialise the rate


Interest(double r)
{
rate=r;
}
//calculate interest amt and update bal
void calculateInterest()
{
double interest=bal *rate/100;
bal+=interest;
System.out.println("updated bal="+bal);
}
}
}
//using inner class
class InnerClass
{
public static void main(String args[])
{
//bank account is holding a balance of 10,000
BankAcct account=new BankAcct(10000);
//updated balance amount by adding interest at 9.5%
account.contact(9.5);
}
}

OUTPUT:-
c:\>javac InnerClass.java
c:\>java InnerClass
Enter password: xyz123
updated bal=10950.0

ANONYMOUS INNER CLASS

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

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

interfaces in graphics programming. To understand the use of anonymous inner class.


ex: b.addActionListener(new Myclass());

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

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

}
}
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

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

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

The keyword 'super'

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

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

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

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

sub class method:i=20


super class method:i=20
super i=10
The protected specifier

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.

write a program to display details of person using inheritance concept.


import java.lang.*;
class Person
{
protected:
char name:
}
public class P extends Person
{
public static void main(String args[])
{
protected:
int age;
void show()
{
System.out.println("enter name="+name);
System.out.println("enter age="+age);
}
P obj=new P();
P.show();
}
}
OUTPUT:-
c:\>javac P.java
c:\>java P
enter name=manasa
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

enter age=21
Types of Inheritance

There are two types of Inheritance:


single Inheritance
multiple 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

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

interface. Java supports only single inheritance.


Single inheritance

Department Bird

Employee
Peacock Parrot Sparrow
Class employee extends Department

Class peacock extends Bird


Class parrot extends Bird
Class Sparrow extends Bird

Multiple Inheritance:

Father Mother Milk Sugar Tea-Powder

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

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

***

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 .

There are two types in polymarphism I,e

 Static Polymarphism or Static binding or compail time binding


 Dynamic Polymarphism or Dynamic binding or run time binding.

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.

Ex. Consider the example of the Static polymarphism.

Class One

// method to calculate square value

static void calculate (double x)

{ System.out.println(“square value=”+(x*x));
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

class Two extends One

{ // method to calculate square root value

static void calculate (double x)

{ System.out.println(“square root =”+ math.sqrt(x));

class Poly

{ public static void main (String args[ ])

// super class reference refers to sub class object

One o =new Two();

// call calculate method using super class reference

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

Void add(int a, int b)

{ System.out .println(“sum of two number=”+(a+b));

}
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

Void add

{ System.out .println(“the sum of three numbers=”+ (a+b+c));

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.

EXAMPLE OF DYNAMIC POLYMARPHISM

class Sample

{ //mehtod is to add two values

Void add(int a, int b)

{ System.out.println(“the sum of a and b =”+ (a+b));

// method is to add three values .

Void add (int a, int b, int c )

{ System.out .println(“The sum of three numbers =”(a+b+c));

} }

class Poly

public static void main (String args[ ])

{ Sample s= new Sample ();

s. add (10,20); // depending on the parameteres method can be executed.

s.add(10,20,30);

}
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

Polymorphism with private methods

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.

Polymorphism with final methods:


Methods which are declared as ‘final’ are called final methods. Final methods cannot be overrides
because they are not available to the sub classes. Therefore , only method overloaded is possible
with final methods.

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

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

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.

//Electricity bill for a commercial connection


class Commercial
{
//take a customer name
private string name;
//store a customer name into name
void setName(String name)
{
this.name=name;
}

//retrieve the name


String getName()
{
return name;
}
//to calculate bill taking for Rs.5.00 per unit
void calculateBill(int units)
{
System.out.println(“Customer:”+ getName());
System.out.println(“Bill amount=”+ units*5.00);
}
}
//Electricity bill for domestic connection
class Domestic extends commercial
{
//override the claculateBill() of commercial class, to calculate
//bill at 2.50 per unit
void claculateBill(int units)
{
System.out.println(“Customer:”+ getName());
KRISHNA CHAITANYA INSTITUTE OF SCIENCE AND TECHNOLOGY., KAKUTURU

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

System.out.println(“Bill amount=”+ units*2.50);


}
}
//calculate electricity bill for commercial and domestic users
class ElectricityBill
{
public static void main (String args[])
{
//call calculateBill using the Commercial object
Commercial c=new Commercial();
c.setName(“Raj kumar”);
c.calculateBill(100);
//call calculateBill() using the Domestic object
Domestic d=new Domestic();
d.setName(“Vijaya lakshmi”);
d.calculateBill(100);
}
}

Output:
C:\> javac ElectricityBill.java
C:\> java ElectricityBill
Customer: Raj kumar
Bill amount= 500.0
Customer: Vijaya lakshmi
Bill amount= 250.0

DIFFERENCES BETWEEN METHOD OVER LOADING AND OVERRIDING

METHOD OVER LOADING METHOD OVERRIDING


1 . writing two or more methods with the same name 1.writing same method name and same parameters is
but different parameters is called method called method overriding .
overlaoding .
2. method overloading is done in the same class 2. method overriding is done in super and sub classes
3.In method overloading method return type can be 3.here method return type should also be same .
same or different.
4. JVM decides which method is called depending on 4. JVM decides which method is called depending on
the parameters passed by the programmer the data types (class)of the object used to call the
method.

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

PROBLEM SOLVING THROUGH JAVA


UNIT - 3
PHANI

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 .

You might also like