UNIT22024

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

OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.

Sc

UNIT – II

ARRAYS

Array:

An array is set of similar data items share a common name. The individual values in an
array are called elements. The elements of an array can be of any data type. All the elements in an
array are of the same type. Array elements are variables. A particular value in indicated by writing
a number called index number (or) subscript in brackets after array name. There are two types of
arrays.

1. One-dimensional arrays
2. Multi-dimensional arrays

1. One-dimensional arrays:

A list of items can be given one variable name using only one subscript and such a variable
is called a single-subscripted variable (or) a one-dimensional array.

Declaring of Arrays:

Arrays in Java may be declared in two forms

Form1: type arrayname[ ];


Form2: type[ ] arrayname;

Form1 Examples:
int number[ ];
float average[ ];
Form2 Examples:
int[] counter;
float[ ] marks;

Remember , we do not enter the size of the arrays in the declaration.

Creation of Arrays:

After declaring an array , we need to create it in the memory. Java allows us to create arrays
using new operator only, as shown below

array name = new type[ size]

Example:
number = new int[5];
average = new float[10];

DEPARTMENT OF COMPUTER SCIENCE 1 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

These lines create necessary memory locations for the arrays number and average and
designate them as int and float respectively. Now the variable number refers to an array of 5
integers and average refers to an array of 10 floating point values.

It is also possible to combine the two steps declaration and creation into one as shown
below

int number[ ]= new int[5];


float average[ ]=new float[10];

Initialization of Arrays:

The final is to put values into the array created. This process is known as initialization .
That is done using the array subscripts as shown below.

arrayname [subscript] = value;

Example:
number[ 0 ]= 35;
number[1] = 40;
…………………
…………………
number[4] = 50;

Note that Java creates arrays starting with the subscript of 0 and ends with a value one less
than the size specified.

Unlike C ,Java protects array from overruns and under runs. Typing to access an array
bound its boundaries will generate an error message.

We can also initialize arrays automatically in the same way as the ordinary variables when
they are declared as shown below.

type arrayname[ ] = { list of values};

The array initializer is a list of values separated by commas and surrounded by curly braces.
Note that no size is given in this case. The compiler allocates enough space for all the elements
specified in the list.

Example:
int number[ ] = { 35,40,20,50};
Array length:

In Java all arrays store the allocated size in a variable named length. We can obtain the
length of the array a using a.length.

DEPARTMENT OF COMPUTER SCIENCE 2 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

Example:
int size = a.length;

This information will be useful in the manipulation of arrays when their size are not known.

Example1:

Program to add the 5 numbers and print the sum of it.

class array1
{
Public static void main(String args[ ] )
{
int sum = 0;
int a[ ] = {10,20,3,4,5};
for ( int i = 0;i < 5; i++)
{
sum = sum+a[i];
}
System.out.println(“Total = “+sum);
}
}
Output:
C:/>javac array1.java
C:/>java array1
Total=42

Example2:
(4th lab program)Write a java program to find the searching element in a given array
elements(using java.util.scanner class).

import java.util.Scanner;
class searcharray
{
public static void main(String args[])
{
int n,x,flag=0,i=0;
Scanner dis=new Scanner(System.in);
System.out.println("enter the no.of elements of the array");
n=dis.nextInt();
int a[]=new int[n];
System.out.println("enter the array elements");
for(i=0;i<n;i++)
{
a[i]=dis.nextInt();
}

DEPARTMENT OF COMPUTER SCIENCE 3 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

System.out.print("Enter the element you want to find: ");


x=dis.nextInt();
for(i=0;i<n;i++)
{
if (a[i]==x)
{
flag=1;
break;
}
else
{
Flag=0;
}
}

if(flag==1)
{
System.out.println("Element found at position: "+(i+1));
}
else
{
System.out.println("Element is not found");
}
}
}
Output:
C:/>javac searcharray.java
C:/>java searcharray
Enter the number of elements of the array
4
Enter the array elements
1
2
3
4
Enter the element you want to find
3
Element found at position:3

Example2(repeat):
Write a java program to find the searching element in a given array elements(using
DataInputStream class).

import java.io.*;
class searcharray1
{public static void main(String args[])throws IOException

DEPARTMENT OF COMPUTER SCIENCE 4 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

{
int i,j,x,n,flag=0;
DataInputStream s=new DataInputStream(System.in);
System.out.println("enter the size of the array ");
n=Integer.parseInt(s.readLine());
int a[]=new int[n];
System.out.println("enter the array elements");
for(i=0;i<n;i++)
a[i]=Integer.parseInt(s.readLine());
System.out.println("the array elements are ");
for(i=0;i<n;i++)
System.out.print("\t"+a[i]);
System.out.println();

System.out.print("Enter the element you want to find: ");


x=Integer.parseInt(s.readLine());
for(i=0;i<n;i++)
{
if (a[i]==x)
{
flag=1;
break;
}
else
{
flag=0;
}
}

if(flag==1)
{
System.out.println("Element found at position: "+(i+1));
}
else
{
System.out.println("Element is not found");
}
}}
Output:
C:/>javac searcharray1.java
C:/>java searcharray1
Enter the size of the array
4
Enter the array elements
1
2

DEPARTMENT OF COMPUTER SCIENCE 5 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

3
4
the array elements are
1 2 3 4
enter the element you want to find
6
Element is not found

2. Two- dimensional Arrays:


A Two-dimensional array is a collection of homogeneous data items that share a common
name using two subscripts. It stores table of data . This representation is very useful for matrix
representations as first subscript represents the number of rows and second subscript represents
the number of columns.

Syntax : datatype arrayname[ ] [ ]; //declaration

new datatype [size1][size2]; // allocation of memory


(or)
datatype arrayname[ ] [ ] = new datatype[size1][size2];
Where ,

datatype defines the datatype of the variables stored in the array


arrayname defines the name of the array
new operator is used to allocate dynamic memory in the computer for the array
size1 defines the number of rows of memory location of the array
size2 defines the number of columns of memory locations of the array

Example:
int number[ ] [ ] = ;
number = new int[5][5];

It can also be initialize arrays automatically when they are declared. The syntax is as
follows

Syntax: type arrayname[ ] [ ] = {list of values};


Or
type arrayname[ ] [ ]={ row1 values},{row2 values};

Example:-

(5th lab program)Write a java program to find the addition, subtraction and multiplication
of two matrices.

import java.io.*;
class matrixaddsubmultiplication

DEPARTMENT OF COMPUTER SCIENCE 6 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

{
public static void main(String args[])throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
int i,j,k,c1,r1,c2,r2;
System.out.println("enter the row and column size of the matrix A");
r1=Integer.parseInt(dis.readLine());
c1=Integer.parseInt(dis.readLine());
System.out.println("enter the row and column size of the matrix B");
r2=Integer.parseInt(dis.readLine());
c2=Integer.parseInt(dis.readLine());
int a[][]=new int[r1][c1];
int b[][]=new int[r2][c2];
int c[][]=new int[r1][c1];
int d[][]=new int[r1][c1];
int e[][]=new int[r1][c2];
System.out.println("enter the matrx A elements");
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
a[i][j]=Integer.parseInt(dis.readLine());
System.out.println("enter the matrx B elements");
for(i=0;i<r2;i++)
for(j=0;j<c2;j++)
b[i][j]=Integer.parseInt(dis.readLine());
System.out.println("Matrix A:=");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
System.out.print(a[i][j]+"\t");
System.out.println("\n");
}
System.out.println("Matrix B:=");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
System.out.print(b[i][j]+"\t");
System.out.println();
}

if((r1==r2)&&(c1==c2))
{

for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
{
c[i][j]=a[i][j]+b[i][j];

DEPARTMENT OF COMPUTER SCIENCE 7 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

d[i][j]=a[i][j]-b[i][j];
}
System.out.println("Matrix addition:=");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
System.out.print(c[i][j]+"\t");
System.out.println();
}
System.out.println("Matrix subtraction:=");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
System.out.print(d[i][j]+"\t");
System.out.println();
}
}
else
System.out.println("The matrix addition is not possible");

if((c1==r2))
{

for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
e[i][j]=0;
for(k=0;k<r2;k++)
e[i][j]=e[i][j]+a[i][k]*b[k][j];
}
}
System.out.println("Matrix multiplication:=");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
System.out.print(e[i][j]+"\t");
System.out.println("\n");
}
}
else
System.out.println("The matrix multiplication is not possible");

}
}
Output:

DEPARTMENT OF COMPUTER SCIENCE 8 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

C:/>javac matrixaddsubmultiplication.java
C:/>java matrixaddsubmultiplication
Enter the row and column size of the matrix A
2
2
Enter the row and column size of the matrix B
2
2
Enter the elements of the matrix A
2
2
2
2
Enter the elements of the matrix B
1
1
1
1
Matrix A:=
2 2
2 2
Matrix B:=
1 1
1 1
Matrix addition:=
3 3
3 3
Matrix subtraction:=
1 1
1 1
Matrix multiplication:=
4 4
4 4
COMMAND LINE ARGUMENTS

Java has the facility of command line arguments. Java main method consists array of string
objects .When we run the program, the array will fill with the values of any arguments it was given
in the command line.

Example: Write a java program for command line arguments.

class CommandLine
{
public static void main(String[] args)
{

DEPARTMENT OF COMPUTER SCIENCE 9 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

if (args.length > 0)
{

System.out.println("The command line arguments are:");

for (int i=0;i<args.length;i++)


System.out.println(args[i]);

System.out.println(args.length);
}
else
System.out.println("No command line "+
"arguments found.");
}
}

STRINGS

Creating strings:

Definition:
A string is a collection of characters .In Java strings are class objects and implemented
using two classes, namely, String and StringBuffer. A Java string is an instantiated object of the
String class. Java strings as compared to C strings are more reliable and predictable. This is
basically due to C’s lack ok of bounds-checking .A Java string is not a character array and is not
NULL terminated. Strings may be declared and created as follows:
String stringname;
Stringname = new String(“ string”);
Example:

DEPARTMENT OF COMPUTER SCIENCE 10 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

String firstname;
firstname = new String(“ Java ”);

The two statements may be combined as follows:


String firstname = new String (“ java ”);

Like arrays , it is possible to get the length of the string using length method of the String class.
int m = firstname.length;

String arrays:
We can also create and use arrays that contain strings. The statement
,

String itemArray[ ] = new String[5];


We will create an itemArray of size 5 to hold constants. We can assign the strings to the
itemArray element by element using three different statements or more efficiently using a for
loop.

String Class Methods

The String class defines number methods that allow us to accomplish a variety of string
manipulation tasks. The String functions are

1. toLowerCase( ):
This function converts the given entire string to lower case.
Syntax: String.toLowerCase( );
Example:
class lower
{
public static void main(String args [ ] )
{
String s1 = new String (“JAVA “);
System.out.println(s1.toLowerCase( ));
}
}
Output: java

2. toUpperCase( ):

This function converts the given entire string to uppercase.


Syntax: String.toUpperCase( );
Example:
class upper
{
public static void main (String args[ ])
{

DEPARTMENT OF COMPUTER SCIENCE 11 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

String s1 = new String (“java”);


System.out.println(s1.toUpperCase( ));
}
}

Output: JAVA

3. replace ( ):

This function replace all the appearances of char1 with char2.


Syntax: String.replace(‘char1’, char2’)
Example:
class replace
{
Public static void main( String args[ ])
{
String s1= “ java”;
String s2= s1. replace(‘j’,’J’);
System.out.println(s2);
}
}

Output: Java

4. trim ( ):
This function remove white spaces at the beginning and end of the String
Syntax: String .trim( );

Example:
class trim
{
public static void main(String args[])
{
String s1=new String(" JAVA ");
System.out.println("Before trim string length is"+s1.length());
s1=s1.trim();
System.out.println("After trim string length is"+s1.length());
}
}

Output:
Befor trim sting length is 6
After trim string length is 4

5. equals( ):

DEPARTMENT OF COMPUTER SCIENCE 12 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

This function compare two given strings s1 , s2 and returns the Boolean value ‘true’ if
they are equal and the Boolean value ‘false’ otherwise.

Syntax: String1.equals(String2);

Example:
class equal
{
Public static void main( String args[ ] )
{
String s1 = “java”;
String s2 = “java”;
System.out.println( s1.equals(s2));
}
}

Output: true

6. equalsIgnoreCase( ):

This function compare two strings s1 ,s2 and returns the Boolean value ‘true’ if they are
equal otherwise it returns ‘false’ ignoring the case of characters.
Syntax: string1.equalsIgnoreCase(string2)

Example:
class equalignore
{
Public static void main( String args[ ] )
{
String s1 = “java”;
String s2 = “JAVA”;
System.out.println( s1.equalsIgnoreCase(s2));
}
}
Output: true

7. length( ):
This function returns the length of the given string.
Syntax: String.length( );
Example:
class length
{
Public static void main( String args[ ] )
{
String s1=”java”;

DEPARTMENT OF COMPUTER SCIENCE 13 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

int l = s1.length ( );
System.out.println(l);
}
}

Output: 4
8. charAt( ):
This function returns the character at the specified position in the given string.
Syntax: String.charAt(n);
Example:
class ch
{
Public static void main (String args[ ] )
{
String s1 = ” Program”;
char c = s1.charAt(1);
System.out.println(c) ;
}
}

Output: r

9. compareTo( ):
This function compare two strings s1 and s2 and returns negative value if s1<s2 , positive
value if s1>s2 , and returns zero if they are equal.
Syntax: String1.compareTo(String2);

Example:
class compare
{
Public static void main( String args[ ])
{
String s1 = “ java”;
String s2 = “ program”;
if(s1 . compareTo(s2) > 0)
System.out.println(“ String s1 is greater than s2”);
else if(s1.compareTo(s2) < 0)
System.out.println(“ String s2 is greater than s1”);
else
System.out.println(“ S1 is equal to s2”);
}
}

Output: String s2 is greater than s1

10. concat( ):

DEPARTMENT OF COMPUTER SCIENCE 14 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

This function concatenates two strings .


Syntax: String1.concat(String2)
Example:
class concatenate
{
Public static void main( String args[ ])
{
String s1 = “java”;
String s2 = “ program”;
String s3 = s1.concat(s2);
System.out.println(s3);
}
}

Output: javaprogram

11. substring( );
This function returns the substring of the given string.
Syntax: String.substring(n)
Example:
class sub
{
Public static void main( String args[ ] )
{
String s1=”java program”;
String s2= s1.substring(4);
System.out.println(s2);
}
}
Output: program

12.indexOf( ):
This function gives the position of the first occurance of the given character in the string.
Syntax: String.indexOf(‘char’);
Example:
class index
{
Public static void main(String args[ ])
{
String s1=”java”;
int n= s1.indexOf(‘a’);
System.out.println(n);
}
}

DEPARTMENT OF COMPUTER SCIENCE 15 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

Output: 1

13. startsWith( ):
This function determines whether a given string begins with a specified string or not and
returns the Boolean value true if yes other wise false .
Syntax: String.startsWith(String);
Example:
class starts
{
Public static void main( String args[ ] )
{
String s1 = “java”;
System.out.println(s1.startsWith(“ja”));
}
}

Output: true

14. endsWith( ):

This function determines whether a given string ends with a specified string or not and
returns the Boolean value true if yes other wise false .
Syntax: String.endsWith(String);
Example:
class ends
{
Public static void main( String args[ ] )
{
String s1 = “java”;
System.out.println(s1.endsWith(“ja”));
}
}

Output: false

15. toString( ):

This function creates the String representation for given Objects.


Syntax: Object.toString( )
Example:
class tostring
{
Public static void main( String args[ ])
{
Integer a = new Integer(10);

DEPARTMENT OF COMPUTER SCIENCE 16 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

System.out.println(a.toString( ));
}
}

Output: 10

(6th lab program)Write a java program to perform various string operations.

class stringclassmethods
{
public static void main(String args[])
{
String s1="priya",s2="darsan",s3="ASN";
System.out.println("length"+s1.length());
System.out.println("concatination"+s1.concat(s2));
System.out.println("uppercase"+s2.toUpperCase());
System.out.println("lowercase "+s3.toLowerCase());
System.out.println("substring(2)"+s1.substring(2));
System.out.println("replace"+s3.replace('N','K'));
System.out.println("end with "+s2.endsWith("n"));
System.out.println("start with "+s1.startsWith("p"));
System.out.println("character at 3 is "+s2.charAt(3));

System.out.println("\nsearching functions");
String s="this is his wish";
System.out.println("length"+s.length());
System.out.println("First occurence of is "+s.indexOf("is"));
System.out.println("last occurence of is"+s.lastIndexOf("is"));

System.out.println("\ncomparison functions\n");
String x="RAVI",y="RAJESH",z="ravi";
int k=x.compareTo(y);
if(k>0)
System.out.println(x+"is big");
else if (k<0)
System.out.println(y+"is big");
else
System.out.println(x+"and "+y+"are equal");

if(x.equals(y))
System.out.println(x+"and "+y+"are equal");
else
System.out.println(x+"and "+y+"are not equal");
if(x.equalsIgnoreCase(z))
System.out.println(x+"and "+z+"are equal");
else
System.out.println(x+"and "+z+"are equal");

DEPARTMENT OF COMPUTER SCIENCE 17 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

}
}
Output:
C:\javac stringclassmethods.java
C:\java stringclassmethods
Length 5
Concatenation priyadarsan
Upper case DARSAN
Lower case asn
Substring(2)iya
Replace ASK
Endswith true
Startwith true
Character at position 3 is s
Searching functions

First occurrence of is 2
Last occurrence of is 13

Comparision functions

RAVI is big
RAVI and RAJESH are not equal
RAVI and ravi are equal

(7th lab program)Write a java program for sorting a given list of names in ascending order.

import java.io.*;
class ascendingnames
{
public static void main(String args[])
{
int i,j,n=4;
String names[]={“srinivas”,”ajay”,”vasu”,”Krishna”};
String temp;
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
{
if(names[i].compareTo(names[j]) > 0)
{
temp=names[i];
names[i]=names[j];
names[j]=temp;
}
}
System.out.println(“The names in ascending order are”);
for(i=0;i<n;i++)

DEPARTMENT OF COMPUTER SCIENCE 18 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

System.out.println(names[i]);
}
}
Output:
C:>javac ascendingnames.java
C:>java ascendingnames
The names in ascending order are
ajay
krishna
srinavas
vasu
CLASSES, OBJECTS & METHODS
Creating Classes:

A class is a non-primitive data type that contains member variables (data) and
member functions (methods) that operates on the variable. A class is declared by the use
of the class keyword. The general form of class definition is as follows.

Syntax: class class-name


{
datatype instance-variable _1;
datatype instance-variable _2;
……………………………….
……………………………….
datatype instance-variable_n;

datatype methodname1(parameter-list)
{
method body
}
……………………………….
……………………………….
datatype methodname-n(parameter-list)
{
method body;
}
}
The data or variables defined with in a class are called instance variables. The code
is present with in methods. Collection of methods and variables defined with in a class
are called members of class.

Variable declaration:

DEPARTMENT OF COMPUTER SCIENCE 19 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

Data is encapsulated in a class by placing data fields inside the body of the
class definition. These variables are called instance variables because they are created
whenever an object of the class is instantiated. we can declare the instance variables
exactly the same way as we declare local variables.
Example:
class Rectangle
{
int length;
int width;
}

Methods declaration:
Methods are declared inside the body of the class but immediately after the
declaration of the instance variables. The general form of the method decleration as
follows
returntype methodname(parameterlist)
{
method-body;
}
Method declaration have four basic parts:
➢ The name of the method(Method prototype)
➢ The type of value the method return
➢ A list of parameters
➢ The body of the method

Example: class sample


{
double width,height,depth;
double volume()
{
return width*height*depth;
}
}
Declaring and Creating Objects:
An object in Java, is a block of memory that contain space to store all the instance
variables. Creating an object is a two-step process.

1. Declare a variable of the class type. At this stage , the variable refers to an object
only.

DEPARTMENT OF COMPUTER SCIENCE 20 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

2. Assigning an actual , physical copy of the object and assign it to that variable by
means of new operator. The new operator dynamically allocates memory for an
object and returns a reference to that object.

sample s1; //reference


s1 = new sample ( ) //instantiate
( or )
sample s1 = new sample ( )

The first statement declares variable to hold the object reference

null
s1
The second statement assigns the object reference and allocates memory.
s1
sample object

We are allowed to create any number of objects to the same class


Example:
sample s1 = new sample ( );
sample s2 = new sample( );
Each object contains its own instance variables of its class. This means that any
changes to the variable of one object have no effect on the variables of another. But the
function name is same for both objects.

It is also possible to create two or more references to the same object.


Example:
sample s1 = new sample ( );
sample s2 = s1;

s1
sample object

s2
Accessing class members:
All variables must be assigned values before they are used in our program. All
class members are accessed by means of “dot “operator.

DEPARTMENT OF COMPUTER SCIENCE 21 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

The general format of accessing instance variables of the class by dot operator is
as follows

Syntax : objectname.variablename=value;

where objectname is name of the object , variable name is the name of the instance
variable.

Example: s1.length = 10;


s2 .width = 15;
The general format of accessing instance methods of the class by dot operator is
as follows
Syntax : objectname . methodname(parameter- list );

Where object is name of the object, method name is the name of the instance
method that calls with the object and parameter – list is a list of actual values separated
by commas.
Example: void getdata(int x, int y)
{
length=x;
width=y;
}

s1.getdata(10,20);

Example:
(8th lab program) write a java program to calculate area of a rectangle.

class Rectangle
{
int length,width;
void getdata(int x ,int y)
{
length = x;
width = y;
}
int rectArea( )
{
int area = length * width;
return(area);
}

DEPARTMENT OF COMPUTER SCIENCE 22 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

}
class rectarea
{
public static void main(String args[ ])
{
int area1,area2;
Rectangle rect1 = new Recatangle ( );
Rectangle rect2 = new Rectangle ( );
rect1.length=15;
rect1.width = 10;
area1=rect1.length * rect1.wifdth;
rect2.getdata(10,20);
area2=rect2.rectArea( );
System.out.println(“area1 =” +area1);
System.out.println(“area2 =” +area2);
}
}
Output:
C:\>javac rectarea.java
C:\>java rectarea
area1=150
area2=200

CONSTRUCTORS
A constructor is a special method of class , which is invoked automatically,
whenever an object of a class is created. A constructor has the following characteristics :

➢ It doesn’t have any return type not even void


➢ It has the same name as its class
➢ It can be overloaded
➢ It is normally used to initiate the members of object.

Different Types of constructors:


➢ Default Constructor( constructor with out arguments)
➢ Parameterized Constructor(constructor with arguments)

1). Default Constructor:


A constructor that accepts no parameters is called the default constructor.
If no constructors are defined for a class the java system automatically generates the
default constructor.

DEPARTMENT OF COMPUTER SCIENCE 23 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

Example:
class sample
{
int x;
sample()
{
x=10;
}
void show()
{
System.out.println(“x=”+x);
}
}

class defsample
{
public static void main(String args[])
{
sample s=new sample();
s.show();
}
}
output: x=10;
Parameterized Constructor:
A constructor that takes arguments as parameters is called parameterized
constructor. If any constructors are defined by a class with the parameters, java will not
create a default constructor for the class.

Example:
class sample
{
int x;
sample( int k)
{
x=k;
}
void show()
{
System.out.println(“x=”+x);
}
}

class parsample

DEPARTMENT OF COMPUTER SCIENCE 24 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

{
public static void main(String args[])
{
sample s=new sample(25);
s.show();
}
}
output: x=25

Constructor Overloading:
A class can have multiple constructors. This is called constructor overloading. All
the constructors have the same name as corresponding to the class name and they are
differ only in number of arguments or data types or order.

Example:
(9th lab program) Write a java program to demonstrate the constructor overloading.
class sample
{
int x,y;
sample()
{
x=0;
y=0;
}
sample(int a)
{
x=a;
}
sample(int a,int b)
{
x=a;
y=b;
}
void show()
{
System.out.println(“x=”+x+” “ +”y=”+y);
}
}
class sampleover
{
public static void main(String args[])
{
sample s1=new sample();

DEPARTMENT OF COMPUTER SCIENCE 25 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

sample s2=new sample(10);


sample s3=new sample(11,22);
s1.show();
s2.show();
s3.show();
}
}

output: x=0 y=0


x=10 y=0
x=10 y=20
static FIELDS
Generally each class contains instance variables and instance methods. Every time
the class is instantiated, a new copy of each of them is created. They are accessed using
the objects with the dot operator.
If we define a member that is common to all the objects and accessed without using
a particular object i.e., the member belong to the class as a whole rather than the objects
created from the class. Such facility can be possible by using the keyword “static”.
The members declared with the keyword static are called static members.

Example:
static int a ;
static int show( int x, int y);

The important points about static class members are:


➢ Static members can be accessible without the help of objects.
➢ A static method can access only static variables
➢ A static member store data at same memory for all objects
➢ Static method cannot be referred to ‘this’ or ‘super’ in anyway.

Example1:
class sample
{
static int c=0;
sample( )
{
c++;
}

static void display( )


{

DEPARTMENT OF COMPUTER SCIENCE 26 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

System.out.println(“no of objects=”+c);
}
}
class Test
{
public static void main(String args[ ])
{
sample s1 = new sample ( );
sample s2 = new sample ( );
sample s3 = new sample ( );
sample.display();
}
}
output: no of objects 3

without using static keyword 1 1 1


s1 s2 s3

with static keyword 3


s1 s2 s3

this KEYWORD
Java define “this” keyword that can be used inside any method to refer the current
object. “this” always a reference to the object on which method was invoked. “this”
reference is implicitly used to refer to both the instance variables and methods of
current objects.

Example:
class Box
{
int len,dep,hei;
Box(int len, int dep , int hei)
{
this.len = len;
this.dep = dep;
this.hei = hei;
}

int volume( )
{
return (len * dep * hei);
}
}

DEPARTMENT OF COMPUTER SCIENCE 27 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

class thisdemo
{
public static void main(String args[ ])
{
Box obj = new Box(1,2,3);
int x = obj.volume( );
System.out.println(“volume=”+x);
}
}
output: volume = 6;

“this” key word sis also used explicitly refer to the instance variables.

INHERITANCE

Inheritance:
The mechanism of deriving a new class from an old class is called inheritance. A
class that is inherited (old class) is called super class or base class or parent class. The
class that does the inheriting (new class) is called a sub class or derived class or child
class. Inheritance allows a sub classes to inherit all the variables and methods of their
parent classes.

INHERITANCE HIERARCHIES:
Inheritance is classified into different forms.

a). Single Inheritance:


Derivation of a class from only one super class is called Single Inheritance.

A Super class (or) Base class (or) Parent class

B
Sub class (or) Derived class (or) Child class

b). Multilevel Inheritance:


Derivation of a class from another derived class is called multilevel Inheritance.

B
DEPARTMENT OF COMPUTER SCIENCE 28 A.S.N.COLLEGE,TENALI
OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

c). Hierarchical Inheritance:


Derivation of several classes from a single super class is called Hierarchical
Inheritance.
A

B C D

d). Multiple Inheritance:


Derivation of one class from two or more super classes is called Multiple
Inheritance. But java does not support Multiple Inheritance directly. It can be
implemented by using Interface concept.

A B

e). Hybrid Inheritance:


Derivation of a class involving more than one form of Inheritance is called Hybrid
Inheritance

B C

DEPARTMENT OF COMPUTER SCIENCE 29 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

Defining a sub class:


A subclass is defined as follows
class class_name extends superclass_name
{
variable declaration;
method declaration;
}

The keyword extends signifies that the properties of the super class name are
extended to the subclass name. The sub class will now contain its variables and methods
as well as those of super class. But it is not vice versa.

1).Single Inheritance:
Derivation of a subclass from only one super class is called single Inheritance.

A super class (or) base class (or) parent class

B sub class (or) derived class (or) child class

(10th lab program)Write a java program to illustrate single inheritance.


class Room
{
int length;
int breadth;
Room( int x, int y)
{
length = x;
breadth = y;
}
int area( )
{
return ( length * breadth );
}
}

class BedRoom extends Room


{
int height;
BedRoom(int x , int y , int z)
{

DEPARTMENT OF COMPUTER SCIENCE 30 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

super( x , y);
height = z;
}

int volume ( )
{
return (length * breadth * height );
}
}

class Test
{
public static void main(String args[ ] )
{
BedRoom room1 = new BedRoom (14 , 12 , 10 );
int area1 = room1 . area( );
int volume1 = room1.volume ( );
System.out.println( “Area1=” + area1);
System.out.println(“Volume1 = “ + volume1);
}
}
output: Area1 = 168
Volume1 = 1680

The above program defines a class Room and extends it to another class BedRoom
. Note that BedRoom defines its own data members and methods. The subclass BedRoom
now includes these instance variables, namely, length, breadth and height and two
methods., area and volume.
The constructor in the derived class uses the super keyword to pass values that
are required by the base constructor. The statement
BedRoom room1 = new BedRoom(14 , 12 , 10 );
first calls the BedRoom constructor method, which is in turn calls the Room constructor
method by using the keyword super
Finally the object room1 of the subclass BedRoom calls the method area defined in
the super class as well as the method volume defined in the subclass itself.
‘super’ keyword (or) Subclass Constructor:
A subclass constructor is used to construct the instance variables of both the
subclass and the super class . The subclass constructor uses the keyword super to invoke
the constructor method of the super class. The keyword super is used subject to the
following conditions:

DEPARTMENT OF COMPUTER SCIENCE 31 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

➢ super may only be used within a subclass constructor method


➢ The call to super class constructor must appear as the first statement within the
subclass constructor.
➢ The parameters in the super call must match the order and type of the instance
variable declared in the super class

2). Multilevel Inheritance:


A common requirement in object-oriented programming is the use of a derived
class as a super class . Java supports this concept and uses it extensively in building its
class library This concept allows us to build a chain of classes as shown in figure.
A superclass (or) Grand Father

B
Intermediate superclass (or) Father

C
subclass (or) child

(11th lab program)Write a java program to illustrate Multilevel inheritance.

import java.io.*;
class company
{
int id;
String cname;
DataInputStream dis=new DataInputStream(System.in);
void cgetdata()throws IOException
{
System.out.println("enter the name of the company");
cname=dis.readLine();
System.out.println("Enter the company ID");
id=Integer.parseInt(dis.readLine());
}
void cshow()
{
System.out.println("The company name is"+cname);
System.out.println("The company ID is"+id);
}
}

DEPARTMENT OF COMPUTER SCIENCE 32 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

class product extends company


{
int pid,phand;
String pname;
float prate;
DataInputStream dis=new DataInputStream(System.in);
void pgetdata()throws IOException
{
System.out.println("Enter the product ID");
pid=Integer.parseInt(dis.readLine());
System.out.println("Enter the name of the product");
pname=dis.readLine();
System.out.println("Number of products in hand");
phand=Integer.parseInt(dis.readLine());
System.out.println("Enter each product cost");
prate=Float.parseFloat(dis.readLine());
}
void pshow()
{
System.out.println("The product ID is"+pid);
System.out.println("The name of product is"+pname);
System.out.println("The product cost is"+prate);
}
}

class customer extends product


{
String name;
int req;
DataInputStream dis=new DataInputStream(System.in);
void custgetdata()throws IOException
{
System.out.println("Enter the name of the customer");
name=dis.readLine();
System.out.println("Number of required products are");
req=Integer.parseInt(dis.readLine());
}
void custshow()
{
if(req<=phand)
{
System.out.println("Customer name is "+name);
System.out.println("number of required products are"+req);

DEPARTMENT OF COMPUTER SCIENCE 33 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

double tot=prate*req;
System.out.println("total cose is"+tot);
System.out.println("the remaining products are"+(phand-req));
}
else
{
System.out.println("sorry company does not have the stock");
}
}
}
class multilevelinheritance
{
public static void main(String args[])throws IOException
{
customer c=new customer();
c.cgetdata();
c.pgetdata();
c.custgetdata();
c.cshow();
c.pshow();
c.custshow();
}
}
Output:
C:/>javac multilevelinheritance.java
C:/>java multilevelinheritance
Enter the name of the company
Wipro
Enter the company ID
6797
Enter the product id
4945
Enter the name of the product
LED lamps
Number of products in hand
500
Enter each product cost
30
Enter the name of the customer
Srinivas
Number of required products are
42
The company name is Wipro

DEPARTMENT OF COMPUTER SCIENCE 34 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

The company ID is 6797


The product ID is 4945
The name of the product is LED lamps
The product cost is 30.0
Customer name is srinivas
Number of required products are 42
Total cost is 1260.0
The remaining products are 458

3). Hierarchical Inheritance::


Derivation of several classes from a single super class is called Hierarchical
Inheritance.
A

B C D

(12th lab program)Write a java program to demonstrate hierarchical inheritance.

import java.io.*;
class students
{
int ano;
String sname;
DataInputStream dis=new DataInputStream(System.in);
void sgetdata()throws IOException
{
System.out.println("Enter the student name");
sname=dis.readLine();
System.out.println("enter the student admission number");
ano=Integer.parseInt(dis.readLine());
}
void sshow()
{
System.out.println("student admission number is"+ano);
System.out.println("student name is"+sname);
}
}

class ug extends students


{

DEPARTMENT OF COMPUTER SCIENCE 35 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

int rno,year;
String bname;
DataInputStream dis=new DataInputStream(System.in);
void uggetdata()throws IOException
{
System.out.println("enter the student roll number");
rno=Integer.parseInt(dis.readLine());
System.out.println("enter the student year");
year=Integer.parseInt(dis.readLine());
System.out.println("enter the branch name");
bname=dis.readLine();
}
void ugshow()
{
System.out.println("student roll number is "+rno);
System.out.println("the current studying year is "+year);
System.out.println("branch name is "+bname);
}
}
class pg extends students
{
int rno;
String cname,semno;
DataInputStream dis=new DataInputStream(System.in);
void pggetdata()throws IOException
{
System.out.println("enter the student roll number");
rno=Integer.parseInt(dis.readLine());
System.out.println("enter the student course name");
cname=dis.readLine();
System.out.println("enter the current semester");
semno=dis.readLine();
}
void pgshow()
{
System.out.println("student roll number is "+rno);
System.out.println("the current semester is "+semno);
System.out.println("the student couse name is "+cname);
}
}
class hierarchicalinheritance
{
public static void main(String args[])throws IOException

DEPARTMENT OF COMPUTER SCIENCE 36 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

{
ug u=new ug();
pg p=new pg();
DataInputStream dis=new DataInputStream(System.in);
System.out.println("1.Under Graduation");
System.out.println("2.Post Graduation");
System.out.println("enter your choice");
int ch=Integer.parseInt(dis.readLine());
switch(ch)
{
case 1:
u.sgetdata();
u.uggetdata();
u.sshow();
u.ugshow();
break;
case 2:
p.sgetdata();
p.pggetdata();
p.sshow();
p.pgshow();
break;
}
}
}
Output:
C:/>javac hierarchicalinheritance.java
c:/>java hierarchicalinheritance

4). Multiple Inheritance:

DEPARTMENT OF COMPUTER SCIENCE 37 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

Derivation of one class from two or more super classes is called Multiple
Inheritance. But java does not support Multiple Inheritance directly. It can be
implemented by using Interface concept.

A B

(13th lab program)Write a java program to demonstrate multiple inheritance.

class student
{
int rno,p1,p2;
void getnumber(int n,int m1,int m2)
{
rno=n;
p1=m1;
p2=m2;
}
void putnumber()
{
System.out.println("Roll number"+rno);
System.out.println("part 1 "+p1);
System.out.println("part 2 "+p2);
}
}

interface sports
{
float sportwt=6.0f;
public void putwt();
}

class result extends student implements sports


{
float total;
public void putwt()
{
System.out.println("sports wt is "+sportwt);
total=p1+p2+sportwt;

DEPARTMENT OF COMPUTER SCIENCE 38 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

}
void display()
{
putnumber();
putwt();
System.out.println("total score is "+total);
}
}

class multipleinheritance
{
public static void main(String args[])
{
result r=new result();
r.getnumber(12,90,90);
r.display();
}
}

Output:

C:/>javac multipleinheritance.java
C:/>java multipleinheritance
Rollnumber 12
Part1 90
Part2 90
Sports wt is 6.0
Total score is 186.0
5). Hybrid Inheritance:
Derivation of a class involving more than one form of Inheritance is called Hybrid
Inheritance

B C

(14th lab program)Write a java program to demonstrate the hybrid inheritance.

class student
{

DEPARTMENT OF COMPUTER SCIENCE 39 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

int rno;
void getnumber(int n)
{
rno=n;
}
void putnumber()
{
System.out.println("Roll number"+rno);
}
}

class test extends student


{
float p1,p2;
void getmarks(float m1,float m2)
{
p1=m1;
p2=m2;
}
void putmarks()
{
System.out.println("marks obtained");
System.out.println("part 1 "+p1);
System.out.println("part 2 "+p2);
}
}
interface sports
{
float sportwt=6.0f;
public void putwt();
}

class result extends test implements sports


{
float total;
public void putwt()
{
System.out.println("sports wt is "+sportwt);
total=p1+p2+sportwt;
}
void display()
{
putnumber();

DEPARTMENT OF COMPUTER SCIENCE 40 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

putmarks();
putwt();
System.out.println("total score is "+total);
}
}

class hybridinheritance
{
public static void main(String args[])
{
result r=new result();
r.getnumber(12);
r.getmarks(27.5f,33.0f);
r.display();
}
}
Output:
C:/>javac hybridinheritance.java
C:/>java hybridinheritance

MEMBER ACCESS RULES (or) Access specifiers

For controlling the access to the various members of a class we use access
specifiers. Access specifiers determine how a member of the class can be accessed.
Java supplies a rich set of access specifiers, they are:
1. public
2. private
3. protected
4. default

Public:
When a member is specified by the public specifier, then that member can be
access by any other code i.e. from any other class or from any other package ( A
package is nothing but a group of classes). We can access this member in the
same class also.
Private:

DEPARTMENT OF COMPUTER SCIENCE 41 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

When the private specifier assigned to a member, then tat member can be
accessed by only the member of that class, it is accessed only within the class. We
cannot access the private data outside the class, with the class objects also.
Protected:
This type of members is accessed by all the members within the package and
classes in other package that are subclasses for the class. Generally they are
useful when inheritance involved.
Default:
If no specifier is specified, then by default it taken as default specifier. Default specifier
acts as a public with in its own package, but cannot accessed outside of its package. (default is
not a keyword).

final KEYWORD
A final keyword is used for the three purposes. They are

A) final as constant:
A variable can be declared as constant with the keyword final. It must be
initialized while declaring. One we initialized the variable with final keyword it cannot
be modified in the program. This is similar to the const in c/c++.

Example: final int x = 10;


x = 44 //error because a final variable can not be modified

B) final to prevent method overriding:


A method that is declared as final cannot be overridden in subclass method.
The methods that are declared as private are implicitly final.

DEPARTMENT OF COMPUTER SCIENCE 42 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

Example: class A
{
final void show( )
{
System.out.println(“hello”);
}
}
class B extends A
{
void show( ) // error because a final method can not
be overridden
{
System.out.println(“Hai”);
}
}
C) final to prevent inheritance:
A class that is declared as final cannot be inherited in to subclasses.
Example: final class A
{
void show( )
{
System.out.println(“hello”);
}
}
class B extends A // error can not be inherited
{
void show( )
{
System.out.println(“Hai”);
}
}
POLYMORPHISM

Polymorphism is one of the main aspects of Object-Oriented Programming(OOP). The


word polymorphism can be broken down into “Poly” and “morphs”, as “Poly” means many
and “Morphs” means forms. In simple words, we can say that ability of a message to be
represented in many forms

Example: A lady can have different characteristics simultaneously. She can be a mother, a
daughter, or a wife, so the same lady possesses different behaviour in different situations.

Polymorphism in Java can be achieved in two ways i.e., method overloading and method overriding.
Polymorphism in Java is mainly divided into two types.
Compile-time polymorphism

DEPARTMENT OF COMPUTER SCIENCE 43 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

Runtime polymorphism

Compile-time polymorphism can be achieved by method overloading, and Runtime polymorphism can
be achieved by method overriding

Method Overloading ( Compile-time Polymorphism achieved by method


overloading)
In java it is possible to define two or more methods within the same class that share
the same name as long as these methods have different set of parameters (Based on
the number of parameters, the type of the parameters and the order of the
parameters). Then the methods are said to be overloaded, and the process is referred
as Method Overloading.
When the overload method is called the Java compiler selects the proper method
by examine the number, type and order of the arguments in the cell. Method
Overloading is commonly used to create several methods with same name that
perform fast accessing.

Note: Two methods differ in only by return type will result in a syntax error.

Example:

(15th lab program) Write a java program to demonstrate the method overloading.
class sample
{
int large(int x, int y)
{
if(x>y)
return x;
else
return y;
}

int large(int x, int y, int z)


{
if(x>y&&x>z)
return x;
else if(y>z)
return y;
else
return z;
}
}

class check

DEPARTMENT OF COMPUTER SCIENCE 44 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

{
public static void main(String args[ ])
{
sample s=new sample( );
System.out.println(“ largest of two numbers is:”+s.large(10,20));
System.out.println(“ largest of three numbers is:”+s.large(11,22,33));
}
}

o/p: largest of two numbers is :20


largest of three numbers is :33

Method Overriding(Runtime Polymorphism achieved by method overriding)

A method in a subclass has the same name , type of the variables and order of the
variables as a method in its super class ,then the method in the sub class is said to be
override the method in the super class .The process is called Method overriding. In such
process the method defined by the super class will be hidden.
When the method is called , the method defined the sub class has invoked and
executed instead of the method in the super class .The super reference followed by the
dot( .) operator may be used to access the original super class version of that method from
the sub class.
Example1:
write a java program to demonstrate the method overriding.
class A
{
int i,j;
A( int a, int b)
{
i = a;
j = b;
}
void show( )
{
System.out.println(“i=”+i);
System.out.println(“j=”+j);
}
}
class B extends A
{
int k;
B(int a,int b,int c)
{

DEPARTMENT OF COMPUTER SCIENCE 45 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

super(a,b);
k = c;}
void show( )
{
System.out.println(“k=”+k);
}
}
class Override
{
public static void main9String args[ ]))
{
B obj = new B( 1,2,3);
obj.show( );
}
}

Output:

k=3

Example2:
(16th lab program) Write a java program to demonstrate the method overriding.
class A
{
int i,j;
A( int a, int b)
{
i = a;
j = b;
}
void show( )
{
System.out.println(“i=”+i);
System.out.println(“j=”+j);
}
}

class B extends A
{
int k;
B(int a,int b,int c)
{
super(a,b);

DEPARTMENT OF COMPUTER SCIENCE 46 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

k = c;
}

void show( )
{
super.show( );
System.out.println(“k=”+k);
}
}
class Override1
{
public static void main9String args[ ]))
{
B obj = new B( 1,2,3);
obj.show( );
}
}
Output:
i= 1
j=2
:k=3

Abstract methods and abstract classes:

An abstract class is a class, which contain one or more abstract methods. An


abstract method is a method without method body. An abstract method is written when
single method performs different tasks depending on object call it.

Syntax: abstract class classname


{
…………..
…………..
abstract returntype methodname(parameterlist);
}

while using abstract classes we must satisfy following conditions.

We cannot use abstract classes to instantiate object directly.


The abstract methods of an abstract class must be defined in its subclass.
We cannot declare abstract constructors or abstract static methods.
Example:
(17th lab program)Write a java program to demonstrate the abstract class.

DEPARTMENT OF COMPUTER SCIENCE 47 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

abstract class sample


{
abstract void calculate(double x);
}

class sub1 extends sample


{
void calculate(double x)
{
System.out.println(x*x);
}
}

class sub2 extends sample


{
void calculate(double x)
{
System.out.println(Math.sqrt(x));
}
}

class sub3 extends sample


{
void calculate(double x)
{
System.out.println(x*x*x);
}
}

class abstractdemo
{
Public static void main(String args[])
{
sub1 s1=new sub1();
sub2 s2=new sub2();
sub3 s3=new sub3();
s1.calculate(2);
s2.calculate(9);
s3.calculate(4);
}
}

Output:
C:/>javac abstractdemo.java
C:/>java abstractdemo
4.0

DEPARTMENT OF COMPUTER SCIENCE 48 A.S.N.COLLEGE,TENALI


OBJECT ORIENTED PROGRAMMING USING JAVA III SEMESTER B.Sc

3.0
64.0

DEPARTMENT OF COMPUTER SCIENCE 49 A.S.N.COLLEGE,TENALI

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy