Iv Semester Ooc (18CS45) Notes
Iv Semester Ooc (18CS45) Notes
(18CS45)
COMMON TO BOTH
COMPUTER SCIENCE AND ENGINEERING
AND
INFORMATION SCIENCE ENGINEERING
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
Syllabus:
Class and Objects: Introduction, member functions and data, objects and
functions.
1|P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
INTRODUCTION TO OBJECT ORIENTED CONCEPTS
2|P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
Overview of C++
✓ C++ extension was first invented by “Bjarne Stroustrup” in 1979.
✓ c++ is an extension of the C language, in that most C programs are also c++programs.
➢ Most real world objects have internal parts (Data Members) and interfaces
Object:
✓ An object is a collection of variables that hold the data and functions that operate
on the data.
✓ The functions that operate on the data are called Member Functions.
✓ In OOPs the data is tied more closely to the functions and does not allow the data
to flow freely around the entire program making the data more secure.
✓ Compliers implementing OOP does not allow unauthorized functions to access the
✓ Only the associated functions can operate on the data and there is no change of
✓ The main advantage of OOP is its capability to model real world problems.
Functions
Functions Functions
Communication
2. Classes
3. Data abstraction
4. Data encapsulation
5. Inheritance
6. Polymorphism
➢ Objects with similar properties and methods are grouped together to form
class.
❖ Data abstraction
➢ Abstraction refers to the act of representing essential features without
including the background details or explanation.
➢ Ex: Let's take one real life example of a TV, which you can turn on and off,
change the channel, adjust the volume, and add external components such as
speakers, VCRs, and DVD players, BUT you do not know its internal details,
that is, you do not know how it receives signals over the air or through a cable,
int main( )
{
cout << "Hello C++" <<endl;
return 0;
}
➢ Here, you don't need to understand how cout displays the text on the user's
screen. You need to only know the public interface and the underlying
❖ Data encapsulation
➢ Information hiding
➢ Wrapping (combining) of data and functions into a single unit (class) is known
as data encapsulation.
➢ Data is not accessible to the outside world, only those functions which are
❖ Inheritance
➢ Acquiring qualities.
➢ The new class that is formed is called derived class, child or sub class.
➢ Derived class has all the features of the base class plus it has some extra
features also.
5|P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
❖ Polymorphism
➢ The dictionary meaning of polymorphism is “having multiple forms”.
Advantages of OOPS
➔ Data security
➔ Reusability of existing code
➔ Creating new data types
➔ Abstraction
➔ Less development time
➔ Reduce complexity
➔ Better productivity
Benefits of OOP
➔ Reusability
➔ Saving of development time and higher productivity
➔ Data hiding
➔ Multiple objects feature
➔ Easy to partition the work in a project based on objects.
➔ Upgrade from small to large systems
➔ Message passing technique for interface.
➔ Software complexity can be easily managed.
Applications of OOP
➔ Real time systems
6|P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
➔ Simulation and modeling
➔ Object oriented databases
➔ Hypertext, hypermedia
➔ AI (Artificial Intelligence)
➔ Neural networks and parallel programming
➔ Decision support and office automation systems
➔ CIM/CAD/CAED system
Oriented Programming)
3. Procedures are being separated from Procedures are not separated from data,
together.
4. A piece of code uses the data to The data uses the piece of code to perform
5. Data is moved freely from one Data is hidden and can be accessed only by
parameters.
8. Debugging is the difficult as the code Debugging is easier even if the code size is
7|P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
Sl.No C C++
3. The data and functions are separate The data and functions are combined
inheritance etc.
equivalent C program
definitions
Since Cin and Cout are C++ objects, they are somewhat “Intelligent”.
✓ They do not require the usual format strings and conversion specifications.
✓ They do require the use of the stream extraction (>>) and insertion (<<) operators.
✓ To get input from the keyboard we use the extraction operator and the object Cin.
✓ Syntax: Cin>> variable;
✓ The compiler figures out the type of the variable and reads in the appropriate type.
8|P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
o Example:
#include<iostream.h>
Void main( )
{
int x;
float y;
cin>> x;
cin>>y;
}
➢ To send output to the screen we use the insertion operator on the object Cout.
➢ Syntax: Cout<<variable;
➢ Compiler figures out the type of the object and prints it out appropriately.
Example:
#include<iostream.h>
void main( )
{
cout<<5;
cout<<4.1;
cout<< “string”;
cout<< ‘\n’;
}
Programs
#include<iostream.h>
void main( )
{
int a,b;
float k;
char name[30];
cout<< “Enter your name \n”;
cin>>name;
cout<< “Enter two Integers and a Float \n”;
cin>>a>>b>>k;
cout<< “Thank You,” <<name<<”,you entered\n”;
cout<<a<<”,”<<b<<”,and”<<k<<’/n’;
}
Output:
Enter your name
Mahesh
9|P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
Enter two integers and a Float
10
20
30.5
Thank you Mahesh, you entered
10, 20 and 30.5
#include<iostream.h>
int main( )
{
int i;
cout<< “this is output\n”;
cout<< “Enter a number”;
cin>>i;
cout<<i<< “Square is” << i*i<<”\n”;
return 0;
}
Output:
This is output
Enter a number 5
5 square is 25
Variables
Variable are used in C++, where we need storage for any value, which will change in program.
Variable can be declared in multiple ways each with different memory requirements and
functioning. Variable is the name of memory location allocated by the compiler depending
10 | P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
✓ Variable must be declared before they are used. Usually it is preferred to declare
them at the starting of the program, but in C++ they can be declared in the middle
Example :
char c;
int i; // declaration
i = 10; // initialization
11 | P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
✓ If a variable is declared and not initialized by default it will hold a garbage value.
Also, if a variable is once declared and if try to declare it again, we will get a compile
time error.
int i,j;
i=10;
j=20;
int j=i+j; //compile time error, cannot redeclare a variable in same scope
Scope of Variables
All the variables have their area of functioning, and out of that boundary they don't hold
their value, this boundary is called scope of the variable. For most of the cases its between
the curly braces, in which variable is declared that a variable exists, not outside it. we can
• Global Variables
• Local variables
Global variables
Global variables are those, which are once declared and can be used throughout the
lifetime of the program by any class or any function. They must be declared outside the
main() function. If only declared, they can be assigned different values at different time in
program lifetime. But even if they are declared and initialized at the same time outside the
main() function, then also they can be assigned any value at any point in the program.
include <iostream>
int main()
Local Variables
Local variables are the variables which exist only between the curly braces, in which its
declared. Outside that they are unavailable and leads to compile time error.
Example :
include <iostream>
int main()
int i=10;
declaration.
#include<iostream>
using namespace std;
int main()
{
int x = 10;
13 | P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
// ref is a reference to
x. int& ref = x;
return 0;
}
Output:
x = 20
ref = 30
Functions in c++:
Definition: Dividing the program into modules, these modules are called as functions.
Where,
return_type:
14 | P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
Components of function:
❖ Function definition
❖ Return statement
❖ Function call
Example:
#include<iostream.h>
int a, b, c;
cin>>a>>b;
cout<<c<<endl;
Function prototype:
❖ The number and types of the arguments that must be supplied in a call to the
function.
15 | P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
❖ Function prototyping is one of the key improvements added to the C++ functions.
When a function is encountered, the compiler checks the function call with its
❖ It informs the compiler that the function max has 2 arguments of the type integer.
❖ The function max( ) returns an integer value the compiler knows how many bytes to
Function definition:
❖ The first line of the function definition is known as function declarator and is
❖ The declarator and declaration must use the same function name, number of
{
if(x>y) //function body
return x;
else
return y;
}
Function call:
c= max (a, b) ;
❖ Invokes the function max( ) with two integer parameters, executing the call
function body and after execution of the function body the control is resumed to
the statement following the function call. The max( ) returns the maximum of the
parameters a and b. the return value is assigned to the local variable c in main( ).
Function parameters:
❖ The parameters specified in the function call are known as actual parameters and
❖ Here a and b are actual parameters. The parameters x and y are formal parameters.
the actual and the formal parameters. In this case the value of the variable aa is
Function return:
❖ Functions can be grouped into two categories. Functions that do not have a return
the value returned by the function max( ) is assigned to the local variable c in main( ).
❖ The return statement in a function need not be at the end of the function. It can
Argument passing:
Two types
1. Call by value
2. Call by reference
➔ Call by value:
✓ The default mechanism of parameter passing( argument passing) is called call
by value.
Example 1:
#include<iostream.h>
void main( )
int a, b;
17 | P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
cout<< “enter values for a and b”;
// 10 and 20
cin>>a>>b;
exchange(a,b);
int temp;
temp=x;
x=y;
y=temp;
cout<<x<<y;output:20,10
}
Example 2:
#include<iostream.h>
void main( )
int a, b;
cin>>a>>b;
sub(a, b);
getch( );
18 | P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
Example 3:
#include<iostream.h>
void main( )
temp=add(a);
cout<<temp<<”,”<<a;
int add(int a)
{
a=a+a;
return a;
}
Output: 20
19 | P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
➔ Call by reference:
• We pass address of an argument to the formal parameters.
Example 1:
#include<iostream.h>
void exchange(int *x, int *y);
void main( )
{
int a, b;
cout<< “enter values for a and b”; //10, 20
cin>>a>>b;
exchange(&a,&b);
cout<<a<<b;
}
void exchange(int *x, int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
cout<<x<<y; // output: 20, 10
Example 2:
#include<iostream.h>
void main( )
{
int a=10, temp;
temp=add(&a);
cout<<temp<<”,”<<a;
getch();
}
int add(int *a)
{
a=*a+*a;
return a;
}
Output: 20
20 | P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
Default arguments:
Example:
#include <iostream.h>
void main( )
{
add(1,2,3);
add(1,2);
add(1);
add( );
}
void add(int a, int b, int c)
{
cout<< a+b+c;
}
➢ A default argument is checked for type at the time of declaration and evaluated at
the time of call.
➢ We must add defaults from right to left.
➢ We cannot provide a default value to a particular argument in the middle of an
argument list.
Example:
int mul (int i, int j=5, int k=10); //legal.
int mul (int i=5, int j); //illegal.
int mul (int i=0,int j, int k=10); //illegal.
int mul (int i=2, int j=5, int k=10); //legal.
➢ Default arguments are useful in situations where some arguments always have the
same value.
21 | P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
Classes & Objects
Programming language is most popular language after C Programming language. C++ is first
• Actually this section can be considered as sub section for the global
declaration section.
• Class declaration and all methods of that class are defined here
22 | P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
➔ Main function:
• Each and every C++ program always starts with main function.
• This is entry point for all the function. Each and every method is called
Class specification:
➢ A Class is way to bind(combine) the data and its associated functions together.
➢ When we define a class, we are creating a new abstract data type that can be
class class_name
{
access specifier: data
};
✓ The keyword class specifies that what follows is an abstract data of type
semicolon.
23 | P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
Access specifier can be of 3 types:
Private:
Public:
Protected:
Note:
By default data and member functions declared within a class are private.
Variables declared inside the class are called as data members and functions
are called as member functions. Only member functions can have access to data
➢ The binding of functions and data together into a single class type variable is
referred as Encapsulation.
Example:
#include<iostream.h>
class student
{
private:
char name[10]; // private variables
int marks1,marks2;
public:
void getdata( ) // public function accessing private members
{
cout<<”enter name,marks in two subjects”;
cin>>name>>marks1>>marks2;
}
24 | P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
void display( ) // public function
{
cout<<”name:”<<name<<endl;
cout<<”marks”<<marks1<<endl<<marks2;
}
}; // end of class
void main( )
{
student obj1;
obj1.getdata( );
obj1.display( );
}
Output:
Enter name,marks in two subjects
Mahesh 25 24
Name: Mahesh
Marks 25 24
In the above program,class name is student,with private data members name,marks1 and
Functions,the getdata( ) accepts name and marks in two subjects from user and display( )
✓ Scope resolution operator links a class name with a member name in order to tell
the compiler what class the member belongs to.
Syntax to define the member functions outside the class using Scope resolution
operator:
Example:
#include<iostream.h>
class student
{
private:
char name[10]; // private variables
int marks1,marks2;
public:
void getdata( );
void display( );
};
void main( )
{
student obj1;
obj1.getdata( );
obj1.display( );
}
Example:
#include<iostream.h>
int a=100; // declaring global variable
class x
{
int a;
public:
void f( )
{
a=20; // local variable
26 | P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
cout<<a; // prints value of a as 20
}
};
void main( )
{
x g;
g.f( ); // this function prints value of a(local variable) as 20
cout<<::a; // this statement prints value of a(global variable) as 100
}
In the above program, the statement ::a prints global variable value of a as 100.
#include<iostream.h>
class item
{
private:
int number,cost;
public:
void getdata(int a,int b );
void display( );
};
output:
number:10
cost:20
27 | P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
Access members
➢ Class members(variables(data) and functions) Can be accessed through an object
➢ Private members can be accessed by the functions which belong to the same class.
Object_name.function_name(actual arguments);
#include<iostream.h>
class item
{
Private: int a;
public: int b;
};
void main( )
{
item i1,i2;
i1.a=10; // illegal private member cannot be accessed outside the class
i2.b=20;
cout<<i2.b; // this statement prints value of b as 20.
}
Note: private members cannot be accessed outside the class but public members can be
accessed.
28 | P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
Example: private members can be accessed by the functions which belongs to the same class
#include<iostream.h>
class item
{
int a=10; // private member
public:
void display( )
{
cout<<a; // it prints a as10
}
};
void main( )
{
item i1;
i1.display( );
}
➢ A member function can call another function directly, without using dot operator.
Example:
#include<iostream.h>
class item
{
private:
int cost,number;
public:
29 | P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
void getdata(int a,int b ) // defining function inside the class
{
number=a;
cost=b;
}
void display( )
{
cout<<”cost:”<<number<<endl;
cout<<”number:”<<cost<<endl;
}
};
void main( )
{
item i1;
i1.getdata(10,30 );
i1.display( );
}
output:
number:10
cost:30
✓ Two or more functions have the same names but different argument lists. The arguments
may differ in type or number, or both. However, the return types of overloaded methods
can be the same or different is called function overloading. An example of the function
#include<iostream.h>
#include<stdlib.h>
#include<conio.h>
#define pi 3.14
class fn
{
public:
void area(int); //circle
void area(int,int); //rectangle
void area(float ,int,int); //triangle
};
void fn::area(int a)
30 | P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
{
cout<<"Area of Circle:"<<pi*a*a;
}
void fn::area(int a,int b)
{
cout<<"Area of rectangle:"<<a*b;
}
void fn::area(float t,int a,int b)
{
cout<<"Area of triangle:"<<t*a*b;
}
void main()
{
int ch;
int a,b,r;
clrscr();
fn obj;
cout<<"\n\t\tFunction Overloading";
cout<<"\n1.Area of Circle\n2.Area of Rectangle\n3.Area of Triangle\n4.Exit\n:”;
cout<<”Enter your Choice:";
cin>>ch;
switch(ch)
{
case 1:
cout<<"Enter Radious of the Circle:";
cin>>r;
obj.area(r);
break;
case 2:
cout<<"Enter Sides of the Rectangle:";
cin>>a>>b;
obj.area(a,b);
break;
case 3:
cout<<"Enter Sides of the Triangle:";
cin>>a>>b;
obj.area(0.5,a,b);
break;
case 4:
exit(0);
}
getch();
}
31 | P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
Static data members
➢ Data members of class be qualified as static.
➢ Only one copy of the data member is created for the entire class and is shared by all the
➢ Static variables are normally used to maintain values common to entire class objects.
Example
class item
{
static int count; // static data member
int number;
public:
void getdata( )
{
number=a;
count++;
}
void putdata( )
{
cout<<”count value”<<count<<endl;
}
};
void main( )
{
item i1,i2,i3; // count is initialized to zero
i1.putdata( );
i2.putdata( );
i3.putdata( );
i1.getdata( );
i2.getdata( );
i3.getdata( );
i1.putdata( ); // display count after reading data
i2.putdata( );
i3.putdata( );
}
Output:
Count value 0
32 | P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
Count value 0
Count value 0
Count value 3
Count value 3
Count value 3
In the above program,the static variable count is initialized to zero when objects are
created.count is incremented whenever data is read into object.since three times getdata(
) is called,so 3 times count value is created.all the 3 objects will have count value as 3
because count variable is shared by all the objects,so all the last 3 statements in
i1 i2 i3
3
Count(common for all objects)
✓ A static member function can have access to only other static members declared in
✓ A static member function can be called using the class name, instead of objects.
Syntax:
class_name : : function_name ;
Example:
class item
{
33 | P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
int number;
static int count;
public:
void getdata(int a )
{
number=a;
count++;
}
static void putdata( )
{
cout<<”count value”<<count;
}
};
void main( )
{
item i1,i2;
i1.getdata(10);
i2.getdata(20);
item::putdata( );
// call static member function using class name with scope resolution operator.
}
Output:
Count value 2
➢ In the above program, we have one static data member count, it is initialized to zero, when
first object is created, and one static member function putdata( ),it can access only static
member.
➢ When getdata( ) is called,twice,each time, count value is incremented, so the value of count
Inline functions:
➢ First control will move from calling to called function. Then arguments will be pushed on to
the stack, then control will move back to the calling from called function.
➢ When a function is declared as inline, compiler replaces function call with function
code.
Example:
#include<iostream.h>
34 | P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
void main( )
{
cout<< max(10,20);
cout<<max(100,90);
getch( );
}
inline int max(int a, int b)
{
if(a>b)
return a;
else
return b;
}
Output: 20
100
Note: inline functions are functions consisting of one or two lines of code.
35 | P a g e
Object Oriented Concepts-MODULE 1 18CS45
_____________________________________________________________________________________________
Questions
1. State the important features of object oriented programming. Compare object
3. Write the general form of function. Explain different argument passing techniques
with example
4. Define function overloading. Write a C++ program to define three overloaded functions
to swap two integers, swap two floats and swap two doubles
5. Write a C++ program to overload the function area() with three overloaded function to
find area of rectangle and area rectangle box and area of circle
9. Implement a C++ program to find prime number between 200 and 500 using for loop.
11. What is class?how it is created? Write a c++ program to create a class called Employee
with data members name age and salary. Display atleast 5 employee information
12. What is nested class? What is its use? Explain with example.
13. What is static data member?explain with example. What is the use of static members
14. Write a class rectangle which contains data items length and breadth and member
36 | P a g e
Object Oriented Concepts-MODULE 2 18CS45
Syllabus:
Constructors, Destructors.
Introduction to Java: Java and Java applications; Java Development Kit (JDK);
programs.
Data types and other tokens: Boolean variables, int, long, char, operators,
arrays, white spaces, literals, assigning values; Creating and destroying
objects; Access specifiers.
1|P a g e
Object Oriented Concepts-MODULE 2 18CS45
Arrays of Objects:
➢ It is possible to have arrays of objects.
➢ The syntax for declaring and using an object array is exactly the same as it is for
Program:
#include<iostream.h>
class c1
{
int i;
public:
void get_i(int j)
{
i=j;
}
void show( )
{
cout<<i<<endl;
}
};
void main( )
{
c1 obj[3]; // declared array of objects
for(int i=0;i<3;i++)
obj[i].get_i(i);
for(int i=0;i<3;i++)
obj[i].show( );
}
In the above program,we have declared object obj as an array of objects[i.e created 3
objects].
2|P a g e
Object Oriented Concepts-MODULE 2 18CS45
obj[i].get_i(i);
invokes get_i( ) function 3 times,each time it stores value of i in the index of obj[i].that is
after the execution of complete loop,the array of object “obj” looks like this:
obj[i].show( );
output: 0
2
Namespace
Namespace is a new concept introduced by the ANSI C++ standards committee. For
using identifiers it can be defined in the namespace scope as below.
Syntax:
In the above syntax "std" is the namespace where ANSI C++ standard class libraries are
defined. Even own namespaces can be defined.
Syntax:
namespace namespace_name
{
//Declaration of variables, functions, classes, etc.
}
3|P a g e
Object Oriented Concepts-MODULE 2 18CS45
Example :
#include <iostream.h>
using namespace std; namespace Own
{
int a=100;
}
int main()
{
cout << "Value of a is:: " << Own::a;
return 0;
}
Result :
In the above example, a name space "Own" is used to assign a value to a variable. To
get the value in the "main()" function the "::" operator is used.
Nested class is a class defined inside a class that can be used within the scope of the
class in which it is defined. In C++ nested classes are not given importance because of the
strong and flexible usage of inheritance. Its objects are accessed using "Nest::Display".
4|P a g e
Object Oriented Concepts-MODULE 2 18CS45
Example :
#include <iostream.h>
class Nest
{
public:
class Display
{
private:
int s;
public:
void sum( int a, int b)
{
s =a+b;
}
void show( )
{
cout << "\nSum of a and b is:: " << s;
}
}; //closing of inner class
}; //closing of outer class
void main()
{
Nest::Display x; // x is a object, objects are accessed using "Nest::Display".
x.sum(12, 10);
x.show();
}
5|P a g e
Object Oriented Concepts-MODULE 2 18CS45
Constructors
✓ Constructors are special class functions which performs initialization of every object. The
class A
{
int x;
public: A(); //Constructor
};
✓ While defining a contructor you must remeber that the name of constructor will be
same as the name of the class, and contructors never have return type.
✓ Constructors can be defined either inside the class definition or outside class
class A
{
int i;
public:
A(); //Constructor declared
};
Types of Constructors
1. Default Constructor
2. Parametrized Constructor
3. Copy Constructor
6|P a g e
Object Oriented Concepts-MODULE 2 18CS45
Default Constructor
Default constructor is the constructor which doesn't take any argument. It has no
parameter.
Syntax :
class_name ()
{
Constructor Definition
}
Example :
class Cube
{
int side;
public: Cube() //constructor
{
side=10;
}
};
int main()
{
Cube c; //constructor is going to call
cout << c.side;
}
Output : 10
In this case, as soon as the object is created the constructor is called which initializes its data
members.
class Cube
{
int side;
};
int main()
{
Cube c;
cout << c.side;
} Output : 0
7|P a g e
Object Oriented Concepts-MODULE 2 18CS45
In this case, default constructor provided by the compiler will be called which will initialize the
object data members to default value, that will be 0 in this case.
Parameterized Constructor
These are the constructors with parameter. Using this Constructor you can provide different
values to data members of different objects, by passing the appropriate values as argument.
Example :
class Cube
{
int side;
public:
Cube(int x)
{
side=x;
}
};
int main()
{
Cube c1(10);
Cube c2(20);
Cube c3(30);
cout << c1.side;
cout << c2.side;
cout << c3.side;
}
OUTPUT : 10 20 30
By using parameterized construcor in above case, we have initialized 3 objects with user
defined values. We can have any number of parameters in a constructor.
copy constructor
copy of an original existing object.It is used to initialize one object from another of
Example :
#include<iostream>
8|P a g e
Object Oriented Concepts-MODULE 2 18CS45
int main()
{
copycon obj(10,20);
copycon obj2=obj; //Copy Constructor
cout<<"\nI am Constructor";
obj.Display(); // Constructor invoked.
cout<<"\nI am copy Constructor";
obj2.Display();
return 0;
}
Result :
I am Constructor
Values:10 20
I am Copy Constructor
Values:10 20
Constructor Overloading
✓ Just like other member functions, constructors can also be overloaded. In fact when you
have both default and parameterized constructors defined in your class you are having
✓ You can have any number of Constructors in a class that differ in parameter list.
9|P a g e
Object Oriented Concepts-MODULE 2 18CS45
class Student
{
int rollno;
string name;
public:
Student(int x)
{
rollno=x;
name="None";
}
Student(int x, string str)
{
rollno=x ;
name=str ;
}
};
int main()
{
Student A(10);
Student B(11,"Ram");
}
In above case we have defined two constructors with different parameters, hence overloading
the constructors.
One more important thing, if you define any constructor explicitly, then the compiler will not
In the above case if we write Student S; in main(), it will lead to a compile time error, because we
haven't defined default constructor, and compiler will not provide its default constructor because
Destructors
✓ Destructor is a special class function which destroys the object as soon as the scope
of object ends. The destructor is called automatically by the compiler when the object
goes out of scope.
✓ The syntax for destructor is same as that for the constructor, the class name is used
for the name of destructor, with a tilde ~ sign as prefix to it.
10 | P a g e
Object Oriented Concepts-MODULE 2 18CS45
class A
{
public:
~A();
};
~A()
{
cout << "Destructor called";
}
};
int main()
{
A obj1; // Constructor Called
int x=1
if(x)
{
A obj2; // Constructor Called
} // Destructor Called for
obj2 } // Destructor called for
obj1
11 | P a g e
Object Oriented Concepts-MODULE 2 18CS45
Introduction to JAVA
12 | P a g e
Object Oriented Concepts-MODULE 2 18CS45
Java Environment:
Java environment includes a large number of development tools and hundreds of classes
and methods. The Java development tools are part of the systems known as Java development kit
(JDK) and the classes and methods are part of the Java standard library known as Java standard
Library (JSL) also known as application program interface (API).
13 | P a g e
Object Oriented Concepts-MODULE 2 18CS45
stage, java interpreter generates machine code that can be directly executed by
the machine that is running the java program.
3. Object oriented
In java everything is an Object. Java can be easily extended since it is based on
the Object model.java is a pure object oriented language.
5. Distributed.
Java is designed for the distributed environment of the internet.java applications
can open and access remote objects on internet as easily as they can do in the local
system.
8. High performance
Because of the intermediate bytecode java language provides high performance
Java Development kits(java software:jdk1.6): Java development kit comes with a number
of
Java development tools. They are:
(1) Appletviewer: Enables to run Java applet.
(2) javac:Java compiler.
14 | P a g e
Object Oriented Concepts-MODULE 2 18CS45
15 | P a g e
Object Oriented Concepts-MODULE 2 18CS45
16 | P a g e
Object Oriented Concepts-MODULE 2 18CS45
Virtual Machine). A Java virtual machine (JVM) is a virtual machine that can execute Java
bytecode. It is the code execution component of the Java software platform.
More Examples:
Java program with multiple lines:
Example:
import java.lang.math;
class squreroot
{
public static void main(String args[])
{
double x = 5;
double y;
y = Math.sqrt(x);
System.out.println(“Y = “ + y);
}
}
(3) Import statements: Import statements instruct the compiler to load the specific
class belongs to the mentioned package.
(4) Interface statements: An interface is like a class but includes a group of method
deceleration. This is an optional statement.
(5) Class definition: A Java program may contain multiple class definition The class are
used to map the real world object.
(6) Main method class: The main method creates objects of various classes and establish
communication between them. On reaching to the end of main the program terminates and the
control goes back to operating system.
Java command line arguments: Command line arguments are the parameters that are
supplied to the application program at the time when they are invoked. The main() method of Java
program will take the command line arguments as the parameter of the args[ ] variable which is a
string array.
Example:
Class Comlinetest
{
17 | P a g e
Object Oriented Concepts-MODULE 2 18CS45
Java Tokens
Constants: Constants in Java refers to fixed value that do not change during the
execution of program. Java supported constants are given below:
(5) Backslash character constants: Java supports some backslash constants those are
used in output methods. They are :
1. \b Backspace
2. \f Form feed
3. \n New Line
4. \r Carriage return.
5. \t Horizontal tab.
6. \’ Single quotes.
7. \” Double quotes
8. \\ Back slash
Integers Type: Java provides four types of Integers. They are byte, sort, Int, long. All
these are sign, positive or negative.
Byte: The smallest integer type is byte. This is a signed 8-bit type that has a range from
–128 to 127. Bytes are useful for working with stream or data from a network or file. They are
also useful for working with raw binary data. A byte variable is declared with the keyword “byte”.
byte b, c;
Short: Short is a signed 16-bit type. It has a range from –32767 to 32767. This
data type is most rarely used specially used in 16 bit computers. Short variables are
declared using the keyword short.
short a, b;
int: The most commonly used Integer type is int. It is signed 32 bit type has a
range from –2147483648 to 2147483648.
int a, b, c;
long: Long is a 64 bit type and useful in all those occasions where Int is not enough.
The range of long is very large.
long a, b;
Floating point types: Floating point numbers are also known as real numbers are useful when
evaluating a expression that requires fractional precision. The two floating-point data types
are float and double.
float: The float type specifies a single precision value that uses 32-bit storage.
Float keyword is used to declare a floating point variable.
float a, b;
double: Double DataTips is declared with double keyword and uses 64-bit value.
Characters: The Java data type to store characters is char. char data type of Java uses
Unicode to represent characters. Unicode defines a fully international character set that can
have all the characters of human language. Java char is 16-bit type. The range is 0 to 65536.
Boolean: Java has a simple type called boolean for logical values. It can have only one of two
possible values. They are true or false.
Key Words: Java program is basically a collection of classes. A class is defined by a set of
declaration statements and methods containing executable statements. Most statement contains
an expression that contains the action carried out on data. The compiler recognizes the tokens
20 | P a g e
Object Oriented Concepts-MODULE 2 18CS45
for building up the expression and statements. Smallest individual units of programs are known as
tokens. Java language includes five types of tokens. They are
(a) Reserved Keyword
(b) Identifiers
(c) Literals.
(d) Operators
(e) Separators.
(1) Reserved keyword: Java language has 60 words as reserved keywords. They implement
specific feature of the language. The keywords combined with operators and
separators according to syntax build the Java language.
(2) Identifiers: Identifiers are programmer-designed token used for naming classes
methods variable, objects, labels etc. The rules for identifiers are
1. They can have alphabets, digits, dollar sign and underscores.
2. They must not begin with digit.
3. Uppercase and lower case letters are distinct.
4. They can be any lengths.
5. Name of all public method starts with lowercase.
6. In case of more than one word starts with uppercase in next word.
7. All private and local variables use only lowercase and underscore.
8. All classes and interfaces start with leading uppercases.
9. Constant identifier uses uppercase letters only.
(3) Literals: Literals in Java are sequence of characters that represents constant values
to be stored in variables. Java language specifies five major types of Literals. They
are:
1. Integer Literals.
2. Floating-point Literals.
3. Character Literals.
4. String Literals.
5. Boolean Literals.
(4) Operators: An operator is a symbol that takes one or more arguments and operates
on them to produce an result.
(5) Separators: Separators are the symbols that indicates where group of code are
divided and arranged. Some of the operators are:
1. Parenthases()
2. Braces{ }
3. Brackets [ ]
4. Semicolon ;
5. Comma ,
6. Period .
21 | P a g e
Object Oriented Concepts-MODULE 2 18CS45
Java character set: The smallest unit of Java language are its character set used to write Java
tokens. This character are defined by unicode character set that tries to create character for a
large number of character worldwide.
The Unicode is a 16-bit character coding system and currently supports 34,000 defined
characters derived from 24 languages of worldwide.
Variables: A variable is an identifier that denotes a storage location used to store a data
value. A variable may have different value in the different phase of the program. To
declare one identifier as a variable there are certain rules. They are:
Variable-name = Value;
Initializing by read statements: Using read statements we can get the values in
the variable.
Scope of Variable: Java variable is classified into three types. They are
22 | P a g e
Object Oriented Concepts-MODULE 2 18CS45
Instance Variable: Instance variable is created when objects are instantiated and
therefore they are associated with the object. They take different values for each object.
Class Variable: Class variable is global to the class and belongs to the entire set of object
that class creates. Only one memory location is created for each class variable.
Local Variable: Variable declared inside the method are known as local variables. Local
variables are also can be declared with in program blocks. Program blocks can
be nested. But the inner blocks cannot have same variable that the outer blocks are
having.
Arrays in Java
Array which stores a fixed-size sequential collection of elements of the same type. An
array is used to store a collection of data, but it is often more useful to think of an array as a
collection of variables of the same type.
To use an array in a program, you must declare a variable to reference the array, and you
must specify the type of array the variable can reference. Here is the syntax for declaring an
array variable:
Example:
Creating Arrays:
You can create an array by using the new operator with the following syntax:
Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below:
23 | P a g e
Object Oriented Concepts-MODULE 2 18CS45
Example:
Following picture represents array myList. Here, myList holds ten double values and the
indices are from 0 to 9.
Processing Arrays:
When processing array elements, we often use either for loop or foreach loop because all of
the elements in an array are of the same type and the size of the array is known.
Example:
Here is a complete example of showing how to create, initialize and process arrays:
24 | P a g e
Object Oriented Concepts-MODULE 2 18CS45
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
JDK 1.5 introduced a new for loop known as for-each loop or enhanced for loop, which
enables you to traverse the complete array sequentially without using an index variable.
Example:
The following code displays all the elements in the array myList:
25 | P a g e
Object Oriented Concepts-MODULE 2 18CS45
1.9
2.9
3.4
3.5
Type Casting: It is often necessary to store a value of one type into the variable of
another type. In these situations the value that to be stored should be casted to destination
Type Casting
Assigning a value of one type to a variable of another type is known as Type Casting.
Example :
int x = 10;
byte y = (byte)x;
• Widening Casting(Implicit)
Example :
Output :
When you are assigning a larger type value to a variable of smaller type, then you need to
perform explicit type casting.
Example :
Output :
27 | P a g e
Object Oriented Concepts-MODULE 2 18CS45
Java operators:
! : Logical NOT
Assignment Operator:
+= : Plus and assign to
-= : Minus and assign to
*= : Multiply and assign to.
/= : Divide and assign to.
%= : Mod and assign to.
= : Simple assign to.
Increment and decrement operator:
++ : Increment by One {Pre/Post)
-- : Decrement by one (pre/post)
Conditional Operator: Conditional operator is also known as ternary operator.
The conditional operator is :
Exp1 ? exp2 : exp3
Bitwise Operator: Bit wise operator manipulates the data at Bit level. These operators are
used for tasting the bits. The bit wise operators are:
28 | P a g e
Object Oriented Concepts-MODULE 2 18CS45
! : Bitwise OR
^ : Bitwise exclusive OR
~ : One’s Complement.
<< : Shift left.
>> : Shift Right.
>>> : Shift right with zero fill
Example:
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a =
60; and b = 13; now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
Binary Left Shift Operator. The left operands value is moved left by
>> the number of bits specified by the right operand.
Binary Right Shift Operator. The left operands value is moved right
<< by the number of bits specified by the right operand.
Shift right zero fill Operator. The left operands value is moved right
>>> by the number of bits specified by the right operand and shifted values
are filled up with zeros.
29 | P a g e
Object Oriented Concepts-MODULE 2 18CS45
Special Operator:
Instanceof operator: The instanceof operator is a object refrence operator
that returns true if the object on the right hand side is an instance of the class given in the
left hand side. This operator allows us to determine whether the object belongs to the
particular class or not.
Person instanceof student
The expression is true if the person is a instance of class student.
Dot operator:The dot(.) operator is used to access the instance variable or
method of class object.
Example Programs
class arithmeticop
{
public static void main(String args[])
{
float a=20.5f;
float b=6.4f;
System.out.println("a = " + a);
System.out.println("b = " + b );
System.out.println("a + b = " + (a+b));
}
}
30 | P a g e
Object Oriented Concepts-MODULE 2 18CS45
class Bitlogic
{
public static void main(String args[])
{
String binary[] = {"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010",
"1011","1100","1101","1110","1111"};
int a = 3;
int b = 6;
int c = a | b;
int d = a & b;
int e = a ^ b;
int f = (~a&b)|(a & ~b);
System.out.println("a or b :"+binary[c]);
System.out.println("a and b : "+binary[d]);
System.out.println("a xor b : "+binary[e]);
System.out.println("(~a&b)|(a & ~b) : "+binary[f]);
}
}
Control Statements
Decision making statements:
1.Simple If statement:
The general form of single if statement is :
If ( test expression)
{
statement-Block;
}
statement-Blocks;
2. If- Else statement:
The general form of if-else statement is
If ( test expression)
{
statement-block1;
}
else
{
statement-block2
}
3. Else-if statement:
The general form of else-if statement is:
If ( test condition)
{
statement-block1;
}
else if(test expression2)
{
statement-block2;
}
else
{
31 | P a g e
Object Oriented Concepts-MODULE 2 18CS45
statement block3;
}
4. Nested if – else statement:
The general form of nested if-else statement is:
If ( test condition)
{
if ( test condition)
{
statement block1;
}
else
{
statement block2;
}
}
else
{
statement block 3
}
5. The switch statements:
The general form of switch statement is:
Switch ( expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
......
default:
default block;
break;
}
Loops In Java: In looping a sequence of statements are executed until a number of time or until
some condition for the loop is being satisfied. Any looping process includes following four steps:
(1) Setting an initialization for the counter.
(2) Execution of the statement in the loop
(3) Test the specified condition for the loop.
(4) Incrementing the counter.
Java includes three loops. They are:
(1) While loop:
The general structure of a while loop is:
Initialization
While (test condition)
{
body of the loop
}
32 | P a g e
Object Oriented Concepts-MODULE 2 18CS45
(2) Do loop:
The general structure of a do loop is :
Initialization
do
{
Body of the loop;
}
while ( test condition);
class BreakTest
{
public static void main(String args[])
{
boolean t= true;
first:
{
second:
{
third:
{
System.out.println("Third stage");
if(t)
break second;
System.out.println("Third stage complete");
}
System.out.println("Second stage");
}
System.out.println("First stage");
}
}
}
33 | P a g e
Object Oriented Concepts-MODULE 2 18CS45
class ContinueTest
{
public static void main(String args[])
{
outer: for(int i=0;i<10;i++)
{
for(int j = 0; j<10;j++)
{
if(j>i)
{
System.out.println("\n");
continue outer;
}
System.out.print(" "+(i*j));
}
}
//System.out.println(" ");
}
}
class ReturnTest
{
public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return");
if(t) return;
System.out.println("After return");
}
}
Methods, Variables and Constructors that are declared private can only be accessed
within the declared class itself.
Private access modifier is the most restrictive access level. Class and interfaces cannot be
private.
Using the private modifier is the main way that an object encapsulates itself and hides data from
the outside world.
A class, method, constructor, interface etc declared public can be accessed from any
other class. Therefore fields, methods, blocks declared inside a public class can be accessed
from any class belonging to the Java Universe.
However if the public class we are trying to access is in a different package, then the public
class still need to be imported.
Because of class inheritance, all public methods and variables of a class are inherited by its
subclasses.
The protected access modifier cannot be applied to class and interfaces. Methods, fields
can be declared protected, however methods and fields in a interface cannot be declared
protected.
Default access modifier means we do not explicitly declare an access modifier for a
class, field, method, etc.A variable or method declared without any access control
modifier is available to any other class in the same package. The fields in an interface are
implicitly public static final and the methods in an interface are by default public.
Advantages of JAVA:
• It is an open source, so users do not have to struggle with heavy license fees each year.
• Platform independent.
35 | P a g e
Object Oriented Concepts-MODULE 2 18CS45
Questions
1. List & explain the characteristics features of java language.
2. Briefly discuss about the java development tool kit.
3. Explain the process of building and running java application program .
4. Explain the following: a)JVM b)Type casting.
5. Class Example{
public static void main(String s[]) {
int a;
for(a=0;a<3;a++){
int b=-1;
System.out.println(“ “+b);
b=50;
System.out.println(“ “+b);
}
}}
What is the output of the above code? If you insert another ‘int b’ outside the for loop
what is the output.
6. With example explain the working of >> and >>>.
7. What is the default package & default class in java?
8. Write a program to calculate the average among the elements {4, 5, 7, 8}, using for
each in java. How for each is different from for loop?
9. Briefly explain any six key consideration used for designing JAVA
language.
10. Discuss three OOP principles.
11. How compile once and run anywhere is implemented in JAVA language?
12. List down various operators available in JAVA language.
13. What is polymorphism?explain with an example.
14. Explain the different access specifiers in java, with examples.
15. a)int num,den;
if(den!=0&&num|den>2)
{
}
b)int num,den;
if(den!=0&num|den==2)
{
}
Compare & explain the above two snippets.
16. Write a note on object instantiation.
17. Explain type casting in JAVA
18. With a program explain break, continue and return keyword in java
19. List the characteristics of a constructor. Implement a C++ program to define a
suitable parameterized constructor with default values for the class distance
with data members feet and inches.
20. What is parameterized constructor. Explain different ways of passing parameters
to the constructor.
36 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
Syllabus:
1|P a g e
Object Oriented Concepts-MODULE 3 18CS45
1. CLASSES:
Definition
A class is a template for an object, and defines the data fields and methods
of the object. The class methods provide access to manipulate the data fields. The
Example Program:
class RectangleArea
{
public static void main(String args[])
{
Rectangle rect1=new Rectangle(); //object creation
rect1.getdata(10,20); //calling methods using object with dot(.)
int area1=rect1.rectArea();
System.out.println("Area1="+area1);
}
}
2|P a g e
Object Oriented Concepts-MODULE 3 18CS45
class. Each object occupies some memory to hold its instance variables (i.e. its
state).
✓ The above two statements declares an object rect1 and rect2 is of type
memory for an object and returns a refernce to it.in java all class objects
The Constructors:
✓ Typically, you will use a constructor to give initial values to the instance
3|P a g e
Object Oriented Concepts-MODULE 3 18CS45
✓ All classes have constructors, whether you define one or not, because
Example:
// A simple constructor.
class MyClass
{
int x;
class ConsDemo
{
public static void main(String args[])
{
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
System.out.println(t1.x + " " + t2.x);
}
}
Parameterized Constructor:
✓ Most often you will need a constructor that accepts one or more
way that they are added to a method: just declare them inside
4|P a g e
Object Oriented Concepts-MODULE 3 18CS45
Example:
// A simple constructor.
class MyClass
{
int x;
class ConsDemo
{
public static void main(String args[])
{
MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
System.out.println(t1.x + " " + t2.x);
}
}
10 20
static keyword
5|P a g e
Object Oriented Concepts-MODULE 3 18CS45
static variable
class Counter
{
int count=0;//will get memory when instance is created
Counter()
{
count++;
System.out.println(count);
}
}
Class MyPgm
{
public static void main(String args[])
{
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
Output: 1
1
1
As we have mentioned above, static variable will get the memory only
once, if any object changes the value of the static variable, it will retain its
value.
6|P a g e
Object Oriented Concepts-MODULE 3 18CS45
class Counter
{
static int count=0;//will get memory only once and retain its value
Counter()
{
count++;
System.out.println(count);
}
}
Class MyPgm
{
public static void main(String args[])
{
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
Output:1
2
3
static method
If you apply static keyword with any method, it is known as static method
class Calculate
{
static int cube(int x)
{
return x*x*x;
}
}
7|P a g e
Object Oriented Concepts-MODULE 3 18CS45
Class MyPgm
{
public static void main(String args[])
{
//calling a method directly with class (without creation of object)
int result=Calculate.cube(5);
System.out.println(result);
}
}
Output:125
this keyword
8|P a g e
Object Oriented Concepts-MODULE 3 18CS45
Output: 0 null
0 null
In the above example, parameter (formal arguments) and instance variables are same
that is why we are using this keyword to distinguish between local variable and
instance variable.
9|P a g e
Object Oriented Concepts-MODULE 3 18CS45
Inner class
✓ It has access to all variables and methods of Outer class and may refer to
them directly. But the reverse is not true, that is, Outer class cannot directly
access members of Inner class.
✓ One more important thing to notice about an Inner class is that it can be
created only within the scope of Outer class. Java compiler generates an
error if any code outside Outer class attempts to instantiate Inner class.
class Inner
{
public void show()
{
System.out.println("Inside inner");
}
}
}
class Test
{
public static void main(String[] args)
{
Outer ot=new Outer();
ot.display();
}
}
Output:
Inside inner
10 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
Garbage Collection
In Java destruction of object from memory is done automatically by the JVM. When
needed and the memories occupied by the object are released. This technique is
No, the Garbage Collection cannot be forced explicitly. We may request JVM for
garbage collection by calling System.gc() method. But this does not guarantee that
3. Increases memory efficiency and decreases the chances for memory leak.
finalize() method
Sometime an object will need to perform some specific task before it is destroyed
such as closing an open connection or releasing any resources held. To handle such
thread before collecting object. It’s the last chance for any object to perform
cleanup utility.
//finalize-code
}
11 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
gc() Method
gc() method is used to call garbage collector explicitly. However gc() method does
not guarantee that JVM will perform the garbage collection. It only requests the
JVM for garbage collection. This method is present in System and Runtime class.
Output :
Garbage Collected
Inheritance:
purpose.
✓ The derived class is called as child class or the subclass or we can say
the extended class and the class from which we are deriving the
Types of Inheritance
2. Multilevel Inheritance
✓ When a subclass is derived simply from its parent class then this
there is only a sub class and its parent class. It is also called single
class A
{
int x;
int y;
int get(int p, int q)
{
x=p;
y=q;
return(0);
}
13 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
void Show()
{
System.out.println(x);
}
}
class B extends A
{
public static void main(String args[])
{
A a = new A();
a.get(5,6);
a.Show();
}
void display()
{
System.out.println("y");
//inherited “y” from class A
}
}
✓ The syntax for creating a subclass is simple. At the beginning of your class
declaration, use the extends keyword, followed by the name of the class to inherit
from:
class A
{
14 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
Multilevel Inheritance
✓ The derived class is called the subclass or child class for it's parent
class and this parent class works as the child class for it's just above (
parent ) class.
class A
{
int x;
int y;
int get(int p, int q)
{
x=p;
y=q;
return(0);
}
void Show()
{
System.out.println(x);
}
}
class B extends A
{
void Showb()
{
System.out.println("B");
}
}
class C extends B
{
void display()
{
System.out.println("C");
}
public static void main(String args[])
{
A a = new A();
a.get(5,6);
15 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
a.Show();
}
}
OUTPUT
5
Multiple Inheritance
✓ The mechanism of inheriting the features of more than one base class into a
single class is known as multiple inheritance. Java does not support multiple
interface.
✓ Here you can derive a class from any number of base classes. Deriving a
class from more than one direct base class is called multiple inheritance.
super keyword
✓ The super is java keyword. As the name suggest super is used to access the
✓ The first use of keyword super is to access the hidden data variables of the
Example: Suppose class A is the super class that has two instance variables as
int a and float b. class B is the subclass that also contains its own data members
16 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
named a and b. then we can access the super class (class A) variables a and b inside
super.member;
super most useful to handle situations where the local members of a subclass
hides the members of a super class having the same name. The following
Example:
class A
{
int a;
float b;
void Show()
{
System.out.println("b in super class: " + b);
}
}
class B extends A
{
int a;
float b;
B( int p, float q)
{
a = p;
super.b = q;
}
void Show()
{
super.Show();
System.out.println("b in super class: " + super.b);
System.out.println("a in sub class: " + a);
}
}
class Mypgm
{
public static void main(String[] args)
{
17 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
Use of super to call super class constructor: The second use of the keyword super
in java is to call super class constructor in the subclass. This functionality can be
super(param-list);
✓ Here parameter list is the list of the parameter requires by the constructor
in the super class. super must be the first statement executed inside a super
class constructor. If we want to call the default constructor then we pass the
empty parameter list. The following program illustrates the use of the super
Example:
class A
{
int a;
int b;
int c;
A(int p, int q, int r)
{
a=p;
b=q;
c=r;
}
}
class B extends A
{
int d;
B(int l, int m, int n, int o)
{
18 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
super(l,m,n);
d=o;
}
void Show()
{
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
class Mypgm
{
public static void main(String args[])
{
B b = new B(4,3,8,7);
b.Show();
}
}
OUTPUT
a=4
b=3
c=8
d=7
Method Overriding
method.
extend the super class. In the example class B is the sub class and class A is
19 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
Example:
class A
{
int i;
A(int a, int b)
{
i = a+b;
}
void add()
{
System.out.println("Sum of a and b is: " + i);
}
}
class B extends A
{
int j;
B(int a, int b, int c)
{
super(a, b);
j = a+b+c;
}
void add()
{
super.add();
System.out.println("Sum of a, b and c is: " + j);
}
}
class MethodOverriding
{
public static void main(String args[])
{
B b = new B(10, 20, 30);
b.add();
}
}
OUTPUT
Sum of a and b is: 30
Sum of a, b and c is: 60
20 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
Method Overloading
✓ Two or more methods have the same names but different argument lists. The
arguments may differ in type or number, or both. However, the return types
Example:
class MethodOverloading
{
int add( int a,int b)
{
return(a+b);
}
float add(float a,float b)
{
return(a+b);
}
double add( int a, double b,double c)
{
return(a+b+c);
}
}
class MainClass
{
public static void main( String arr[] )
{
MethodOverloading mobj = new MethodOverloading
(); System.out.println(mobj.add(50,60));
System.out.println(mobj.add(3.5f,2.5f));
System.out.println(mobj.add(10,30.5,10.5));
}
}
OUTPUT
110
6.0
51.0
21 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
Abstract Class
Example Program:
}
double area()
{
System.out.println("Traingle Area");
22 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
return dim1*dim2/2;
}
}
class MyPgm
{
public static void main(String args[])
{
The final keyword in java is used to restrict the user. The final keyword can be
used in many context. Final can be:
1. variable
2. method
3. class
1) final variable: If you make any variable as final, you cannot change the value of
final variable(It will be constant).
Example:There is a final variable speedlimit, we are going to change the value of this
variable, but It can't be changed because final variable once assigned a value can
never be changed.
class Bike
{
final int speedlimit=90;//final variable
void run()
{
speedlimit=400;
}
}
23 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
Class MyPgm
{
public static void main(String args[])
{
Bike obj=new Bike();
obj.run();
}
}
Output:Compile Time Error
2) final method: If you make any method as final, you cannot override it.
Example:
class Bike
{
final void run()
{
System.out.println("running");
}
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}
}
Class MyPgm
{
public static void main(String args[])
{
Honda honda= new Honda();
honda.run();
}
}
Output:Compile Time Error
24 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
3) final class:If you make any class as final, you cannot extend it.
Example:
Class MyPgm
{
25 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
Exception handling:
Introduction
execution and disrupts the normal flow of instructions. The abnormal event can be an
programming language.
Concepts of Exceptions
program.
Example: If you divide a number by zero or open a file that does not exist, an
exception is raised.
In java, exceptions can be handled either by the java run-time system or by a user-
The unexpected situations that may occur during program execution are:
26 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
1. try:
2. catch.
3. throw.
4. throws.
5. finally.
Exceptions are handled using a try-catch-finally construct, which has the Syntax.
try
{
<code>
}
catch (<exception type1> <parameter1>)
{
// 0 or more<statements>
}
finally
{
// finally block<statements>
}
1. try Block: The java code that you think may produce an exception is
placed within a try block for a suitable catch block to handle the error.
If no exception occurs the execution proceeds with the finally block else it
will look for the matching catch block to handle the error.
Again if the matching catch handler is not found execution proceeds with
the finally block and the default exception handler throws an exception.
27 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
2. catch Block: Exceptions thrown during execution of the try block can be caught
and handled in a catch block. On exit from a catch block, normal execution continues
and the finally block is executed (Though the catch block throws an exception).
3. finally Block: A finally block is always executed, regardless of the cause of exit
from the try block, or whether any catch block was executed. Generally finally block
Example:
The following is an array is declared with 2 elements. Then the code tries to
28 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
A try block can be followed by multiple catch blocks. The syntax for multiple catch
try
{
// code
}
catch(ExceptionType1 e1)
{
//Catch block
}
catch(ExceptionType2 e2)
{
//Catch block
}
catch(ExceptionType3 e3)
{
//Catch block
}
The previous statements demonstrate three catch blocks, but you can have any
try/catch statements.
class Multi_Catch
{
public static void main (String args [])
{
try
{
int a=args.length;
System.out.println(“a=”+a);
int b=50/a;
int c[]={1}
}
catch (ArithmeticException e)
{
System.out.println ("Division by zero");
}
29 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println (" array index out of bound");
}
}
}
OUTPUT
Division by zero
array index out of bound
✓ Just like the multiple catch blocks, we can also have multiple try blocks. These
try blocks may be written independently or we can nest the try blocks within
each other, i.e., keep one try-catch block within another try-block. The
Syntax
try
{
// statements
// statements
try
{
// statements
// statements
}
catch (<exception_two> obj)
{
// statements
}
// statements
// statements
}
catch (<exception_two> obj)
{
// statements
}
30 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
✓ Consider the following example in which you are accepting two numbers from
the command line. After that, the command line arguments, which are in the
✓ If the numbers were not received properly in a number format, then during
to the next try block. Inside this second try-catch block the first number is
divided by the second number, and during the calculation if there is any
Example
class Nested_Try
{
public static void main (String args [ ] )
{
try
{
int a = Integer.parseInt (args [0]);
int b = Integer.parseInt (args [1]);
int quot = 0;
try
{
quot = a / b;
System.out.println(quot);
}
catch (ArithmeticException e)
{
System.out.println("divide by zero");
}
}
catch (NumberFormatException e)
{
System.out.println ("Incorrect argument type");
}
}
}
31 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
The output of the program is: If the arguments are entered properly in the
command prompt like:
OUTPUT
java Nested_Try 2 4 6
4
OUTPUT
java Nested_Try 2 4 aa
Incorrect argument type
OUTPUT
java Nested_Try 2 4 0
divide by zero
throw Keyword
new NullPointerException("test");
32 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
class Test
{
static void avg()
{
try
{
throw new ArithmeticException("demo");
}
catch(ArithmeticException e)
{
System.out.println("Exception caught");
}
}
public static void main(String args[])
{
avg();
}
}
In the above example the avg() method throw an instance of ArithmeticException,
which is successfully handled using the catch statement.
throws Keyword
✓ Any method capable of causing exceptions must list all the exceptions possible
during its execution, so that anyone calling that method gets a prior knowledge
about which exceptions to handle. A method can do so by using the throws
keyword.
Syntax :
NOTE : It is necessary for all exceptions, except the exceptions of type Error
and RuntimeException, or any of their subclass.
33 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
class Test
{
static void check() throws
ArithmeticException {
System.out.println("Inside check function");
throw new ArithmeticException("demo");
}
finally
✓ The finally clause is written with the try-catch statement. It is guaranteed
Syntax
try
{
// statements
}
34 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
✓ Take a look at the following example which has a catch and a finally block. The
error like divide-by-zero. After executing the catch block the finally is also
executed and you get the output for both the blocks.
Example:
class Finally_Block
{
static void division ( )
{
try
{
int num = 34, den = 0;
int quot = num / den;
}
catch(ArithmeticException e)
{
System.out.println ("Divide by zero");
}
finally
{
System.out.println ("In the finally block");
}
}
class Mypgm
{
public static void main(String args[])
{
OUTPUT
Divide by zero
In the finally block
35 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
Java defines several exception classes inside the standard package java.lang.
✓ The most general of these exceptions are subclasses of the standard type
available.
Java defines several other types of exceptions that relate to its various class
Exception Description
Exception Description
✓ Here you can also define your own exception classes by extending Exception.
These exception can represents specific runtime condition of course you will
have to throw them yourself, but once thrown they will behave just like
ordinary exceptions.
✓ When you define your own exception classes, choose the ancestor carefully.
Most custom exception will be part of the official design and thus checked,
37 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
}
public String toString()
{
if(marks <= 40)
msg = "You have failed";
if(marks > 40)
msg = "You have Passed";
return msg;
}
}
class test
{
public static void main(String args[])
{
test t = new test();
t.dd();
}
public void add()
{
try
{
int i=0;
if( i<40)
throw new MyException();
}
catch(MyException ee1)
{
System.out.println("Result:"+ee1);
}
}
}
OUTPUT
Result: You have Passed
38 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
Chained Exception
✓ Chained exceptions are the exceptions which occur one after another i.e. most
another exception.
exceptions.
handling the exception, which occur one after another i.e. most of the time
exception.
chained exceptions help the programmer to know when one exception causes
another.
Throwable initCause(Throwable)
Throwable(Throwable)
Throwable(String, Throwable)
Throwable getCause()
39 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
Questions
9. Write a java program to find the area and volume of a room. Use
a base class rectangle with a constructor and a method for
finding the area. Use its subclass room with a constructor that
gets the value of length and breadth from the base class and
has a method to find the volume. Create an object of the class
room and obtain the area and volume.
40 | P a g e
Object Oriented Concepts-MODULE 3 18CS45
13. Write a java program to find the distance between two points
whose coordinates are given. The coordinates can be 2-
dimensional or 3-dimensional (for comparing the distance
between 2D and a 3D point, the 3D point, the 3D x and y
components must be divided by z). Demonstrate method
overriding in this program.
41 | P a g e
Object Oriented Concepts-MODULE 4 18CS45
Syllabus:
1|P a g e
Object Oriented Concepts-MODULE 4 18CS45
Packages in JAVA
There are many built-in packages such as java, lang, awt, javax, swing, net, io,
util, sql etc.
1) Java package is used to categorize the classes and interfaces so that they
can be easily maintained.
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages.
The import keyword is used to make the classes and interface of another
package accessible to the current package.
2|P a g e
Object Oriented Concepts-MODULE 4 18CS45
//save by A.java
package pack;
public class A
{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be
accessible.
package pack;
public class A
{
public void msg(){System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.A;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:Hello
3|P a g e
Object Oriented Concepts-MODULE 4 18CS45
If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified
name every time when you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A();//using fully qualified
name obj.msg();
}
}
Output:Hello
Access Modifiers/Specifiers
The access modifiers in java specify accessibility (scope) of a data member,
method, constructor or class.
1. private
2. default
3. protected
4. public
4|P a g e
Object Oriented Concepts-MODULE 4 18CS45
The protected access modifier is accessible within package and outside the
package but through inheritance only.
The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.
5|P a g e
Object Oriented Concepts-MODULE 4 18CS45
Interface in java
be only abstract methods in the java interface does not contain method
✓ Interface fields are public, static and final by default, and methods are
There are mainly three reasons to use interface. They are given below.
6|P a g e
Object Oriented Concepts-MODULE 4 18CS45
Example 1
interface printable
{
void print();
}
class IntefacePgm1
{
public static void main(String args[])
{
Pgm1 obj = new Pgm1 ();
obj.print();
}
}
Output:
Hello
Example 2
In this example, Drawable interface has only one method. Its implementation is
And, it is used by someone else. The implementation part is hidden by the user
interface Drawable
{
void draw();
}
7|P a g e
Object Oriented Concepts-MODULE 4 18CS45
d.draw();
}
}
Output:
drawing circle
8|P a g e
Object Oriented Concepts-MODULE 4 18CS45
Example
interface Printable
{
void print();
}
interface Showable
{
void show();
}
Class InterfaceDemo
{
public static void main(String args[])
{
Pgm2 obj = new Pgm2 ();
obj.print();
obj.show();
}
}
Output:
Hello
Welcome
9|P a g e
Object Oriented Concepts-MODULE 4 18CS45
Example
interface Printable
{
void print();
}
interface Showable
{
void print();
}
Output:
Hello
✓ As you can see in the above example, Printable and Showable interface
Interface inheritance
interface Printable
{
void print();
}
interface Showable extends Printable
{
void show();
}
10 | P a g e
Object Oriented Concepts-MODULE 4 18CS45
Class InterfaceDemo2
{
public static void main(String args[])
{
InterfacePgm2 obj = new InterfacePgm2 ();
obj.print();
obj.show();
}
}
Output:
Hello
Welcome
11 | P a g e
Object Oriented Concepts-MODULE 4 18CS45
{
top--;
System.out.println("Pop operation done !");
}
else
{
System.out.println("Stack Underflow !");
}
}
public void printElements()
{
if (top >= 0)
{
System.out.println("Elements in stack :");
for (int i = 0; i <= top; i++)
{
System.out.println(arr[i]);
}
}
}
class MyPgm
{
stackDemo.pop();
stackDemo.push(23);
stackDemo.push(2);
stackDemo.push(73);
stackDemo.push(21);
stackDemo.pop();
stackDemo.pop();
stackDemo.pop();
stackDemo.pop();
}
Output
12 | P a g e
Object Oriented Concepts-MODULE 4 18CS45
➢ Multithreading enables you to write very efficient programs that make maximum
use of the CPU, because idle time can be kept to a minimum. Multitasking threads
require less overhead than multitasking processes.
➢ Java’s multithreading system is built upon the Thread class, its methods, and its
companion interface, Runnable.
➢ The Thread class defines several methods that help manage threads (shown
below)
When a Java program starts up, one thread begins running immediately. This is usually
called the main thread of your program, because it is the one that is executed when your
program begins. The main thread is important for two reasons:
Although the main thread is created automatically when your program is started, it can
be controlled through a Thread object. To do so, you must obtain a reference to it by
calling the method currentThread( ), which is a public static member of Thread. Its
general form is shown here:
static Thread currentThread( )
13 | P a g e
Object Oriented Concepts-MODULE 4 18CS45
This method returns a reference to the thread in which it is called. Once you have a
reference to the main thread, you can control it just like any other thread.
Example:
➢ In this program, a reference to the current thread (the main thread, in this
case) is obtained by calling currentThread( ), and this reference is stored in
the local variable t.
➢ Next, the program displays information about the thread. The program then calls
setName( ) to change the internal name of the thread. Information about the
thread is then redisplayed.
➢ Next, a loop counts down from five, pausing one second between each line.
➢ The pause is accomplished by the sleep( ) method. The argument to sleep( )
specifies the
delay period in milliseconds.
Output:
14 | P a g e
Object Oriented Concepts-MODULE 4 18CS45
These displays, in order: the name of the thread, its priority, and the name of its
group. By default, the name of the main thread is main. Its priority is 5, which is the
default value, and main is also the name of the group of threads to which this thread
belongs. The general form of sleep() is:
Creating a Thread
Implementing Runnable
The easiest way to create a thread is to create a class that implements the Runnable
interface. You can construct a thread on any object that implements Runnable. To
implement Runnable, a class need only implement a single method called run( ), which is
declared like this:
public void run( )
run( ) establishes the entry point for another, concurrent thread of execution within
your program. This thread will end when run( ) returns.
After the new thread is created, it will not start running until you call its start( ) method,
which is declared within Thread. In essence, start( ) executes a call to run( ).
The start( ) method is shown here:
void start( )
15 | P a g e
Object Oriented Concepts-MODULE 4 18CS45
Example:
Next, start( ) is called, which starts the thread of execution beginning at the run( )
method. This causes the child thread’s for loop to begin. After calling start( ),
NewThread’s constructor
returns to main( ). When the main thread resumes, it enters its for loop. Both threads
continue running, sharing the CPU, until their loops finish.
16 | P a g e
Object Oriented Concepts-MODULE 4 18CS45
Output:
➢ The second way to create a thread is to create a new class that extends
Thread, and then to create an instance of that class.
➢ The extending class must override the run( ) method, which is the entry
point for the new thread.
➢ It must also call start( ) to begin execution of the new thread.
Example:
17 | P a g e
Object Oriented Concepts-MODULE 4 18CS45
18 | P a g e
Object Oriented Concepts-MODULE 4 18CS45
As you can see, once started, all three child threads share the CPU. Notice the call to
sleep(10000) in main( ). This causes the main thread to sleep for ten seconds and
ensures that it will finish last.
➢ To make main to finish last First, you can call isAlive( ) on the thread.
➢ This method is defined by Thread, and its general form is shown here:
final boolean isAlive( )
➢ The isAlive( ) method returns true if the thread upon which it is called is still
running. It returns false otherwise.
➢ While isAlive( ) is occasionally useful, the method that you will more
commonly use to wait for a thread to finish is called join( ), shown
here:
final void join( ) throws InterruptedException
➢ This method waits until the thread on which it is called terminates.
Here is an improved version of the preceding example that uses join( ) to ensure that
the main thread is the last to stop. It also demonstrates the isAlive( ) method.
19 | P a g e
Object Oriented Concepts-MODULE 4 18CS45
Output:
As you can see, after the calls to join( ) return, the threads have stopped executing.
Thread Priorities
➢ Thread priorities are used by the thread scheduler to decide when each thread
should be allowed to run.
➢ In theory, higher-priority threads get more CPU time than lower-priority threads.
➢ In practice, the amount of CPU time that a thread gets often depends on several
factors besides its priority.
➢ To set a thread’s priority, use the setPriority( ) method, which is a member of
Thread. This is its general form:
o Here, level specifies the new priority setting for the calling thread.
20 | P a g e
Object Oriented Concepts-MODULE 4 18CS45
➢ You can obtain the current priority setting by calling the getPriority( ) method
of Thread, shown here:
The following example demonstrates two threads at different priorities, One thread is
set two levels above the normal priority, as defined by Thread.NORM_PRIORITY, and
the other is set to two levels below it. The threads are started and allowed to run for
ten seconds. Each thread executes a loop, counting the number of iterations. After ten
seconds, the main thread stops both threads. The number of times that each thread
madeit through the loop is then displayed.
21 | P a g e
Object Oriented Concepts-MODULE 4 18CS45
Output:
The higher-priority thread got the majority of the CPU time.
Low-priority thread: 4408112
High-priority thread: 589626904
Synchronization
➢ When two or more threads need access to a shared resource, they need some way
to ensure that the resource will be used by only one thread at a time. The process
by which this is achieved is called synchronization.
➢ Key to synchronization is the concept of the monitor (also called a semaphore).
➢ A monitor is an object that is used as a mutually exclusive lock, or mutex.
➢ Only one thread can own a monitor at a given time.
➢ When a thread acquires a lock, it is said to have entered the monitor.
➢ All other threads attempting to enter the locked monitor will be suspended until
the first thread exits the monitor.
➢ These other threads are said to be waiting for the monitor.
➢ To enter an object’s monitor, just call a method that has been modified with the
synchronized keyword.
➢ While a thread is inside a synchronized method, all other threads that try to call
it (or any other synchronized method) on the same instance have to wait.
➢ To exit the monitor and relinquish control of the object to the next waiting
thread, the owner of the monitor simply returns from the synchronized method.
• Finally, the Synch class starts by creating a single instance of Callme, and
three instances of Caller, each with a unique message string. The same
instance of Callme is passed to each Caller.
22 | P a g e
Object Oriented Concepts-MODULE 4 18CS45
Example:
As you can see, by calling sleep( ), the call( ) method allows execution to switch
to another thread. This results in the mixed-up output of the three message strings.
23 | P a g e
Object Oriented Concepts-MODULE 4 18CS45
In this program, nothing exists to stop all three threads from calling the same
method, on the same object, at the same time. This is known as a race condition, because
the three threads are racing each other to complete the method.
To fix the preceding program, you must serialize access to call( ). That is, you must
restrict its access to only one thread at a time. To do this, you simply need to precede
call( )’s definition with the keyword synchronized, as shown here:
class Callme {
synchronized void call(String msg) {
...
After
synchronized has been added to call( ), the output of the program is as follows:
[Hello]
[Synchronized]
[World]
The synchronized Statement
You simply put calls to the methods defined by this class inside a synchronized
block. This is the general form of the synchronized statement:
synchronized(object) {
// statements to be synchronized
}
• Here, object is a reference to the object being synchronized.
• Here is an alternative version of the preceding example, using a synchronized
block within the run( ) method:
24 | P a g e
Object Oriented Concepts-MODULE 4 18CS45
Interthread Communication
Java supports interprocess communication mechanism via the wait( ), notify( ), and
notifyAll( ) methods.
➢ wait( ) tells the calling thread to give up the monitor and go to sleep until some
other thread enters the same monitor and calls notify( ).
➢ notify( ) wakes up a thread that called wait( ) on the same object.
➢ notifyAll( ) wakes up all the threads that called wait( ) on the same object.
One of the threads will be granted access.
The following sample program that incorrectly implements a simple form of the producer/
consumer problem. It consists of four classes: Q, the queue that you’re trying to
synchronize; Producer, the threaded object that is producing queue entries; Consumer,
the threaded object that is consuming queue entries; and PC, the tiny class that creates
the single Q, Producer, and Consumer.
25 | P a g e
Object Oriented Concepts-MODULE 4 18CS45
Although the put( ) and get( ) methods on Q are synchronized, nothing stops the
producer from overrunning the consumer, nor will anything stop the consumer from
consuming the same queue value twice. Thus, you get the erroneous output shown here.
Put: 1
Got: 1
Got: 1
Got: 1
Got: 1
Got: 1
Put: 2
Put: 3
Put: 4
Put: 5
Put: 6
Put: 7
Got: 7
As you can see, after the producer put 1, the consumer started and got the same 1 five
times in a row. Then, the producer resumed and produced 2 through 7 without letting
the consumer have a chance to consume them.
The proper way to write this program in Java is to use wait( ) and notify( ) to signal in
both directions, as shown here:
26 | P a g e
Object Oriented Concepts-MODULE 4 18CS45
27 | P a g e
Object Oriented Concepts-MODULE 4 18CS45
Inside get( ), wait( ) is called. This causes its execution to suspend until the Producer
notifies you that some data is ready. When this happens, execution inside get( ) resumes.
After the data has been obtained, get( ) calls notify( ). This tells Producer that it is
okay to put more data in the queue. Inside put( ), wait( ) suspends execution until the
Consumer has removed the item from the queue. When execution resumes, the next item
of data is put in the queue, and notify( ) is called. This tells the Consumer that it should
now remove it.
28 | P a g e
Object Oriented Concepts-MODULE 4 18CS45
Questions
1. What is an interface? Write a program to illustrate multiple
6. Explain multi threading . write a java program that create two thread
with message.
8. Explian briefly
i) Isalive ( ) ii) Join ( ) iii) thread priority iv)suspending & stopping
thread
29 | P a g e
Object Oriented Concepts-MODULE 5 18CS45
Syllabus:
1|P a g e
Object Oriented Concepts-MODULE 5 18CS45
Event Handling
The Delegation Event Model
➢ Delegation event model defines standard and consistent mechanisms to
generate and process events.
➢ A source generates an event and sends it to one or more listeners. In this
scheme, the listener simply waits until it receives an event. Once an event is
received, the listener processes the event and then returns.
➢ In the delegation event model, listeners must register with a source in order
to receive an event notification. This provides an important benefit:
notifications are sent only to
listeners that want to receive them.
Events:
➢ An event is an object that describes a state change in a source.
➢ It can be generated as a consequence of a person interacting with the
elements in a graphical user interface.
➢ Some of the activities that cause events to be generated are pressing a
button, entering a character via the keyboard, selecting an item in a list, and
clicking the mouse.
Event Sources:
➢ A source is an object that generates an event. This occurs when the internal
state of that object changes in some way. Sources may generate more than
one type of event.
➢ A source must register listeners in order for the listeners to receive
notifications about a specific type of event.
➢ Each type of event has its own registration method. General form:
public void addTypeListener(TypeListener el)
➢ Here, Type is the name of the event, and el is a reference to the event listener.
For example, the method that registers a keyboard event listener is called
addKeyListener( ). The method that registers a mouse motion listener is
called addMouseMotionListener( ).
➢ A source must also provide a method that allows a listener to unregister an
interest in a specific type of event. The general form of such a method is
this:
public void removeTypeListener(TypeListener el)
➢ Here, Type is the name of the event, and el is a reference to the event
listener. For example, to remove a keyboard listener, you would call
removeKeyListener( ).
Event Listeners
➢ A listener is an object that is notified when an event occurs.
➢ It has two major requirements. First, it must have been registered with one
or more sources to receive notifications about specific types of events.
Second, it must implement methods to receive and process these notifications.
2|P a g e
Object Oriented Concepts-MODULE 5 18CS45
Event Classes
ActionEvent Class
Here, src is a reference to the object that generated this event. The type of
the event is specified by type, and its command string is cmd. The argument
modifiers indicates which modifier keys (ALT, CTRL, META, and/or SHIFT)
were pressed when the event was generated. The when parameter specifies
when the event occurred.
➢ You can obtain the command name for the invoking ActionEvent object by
using the getActionCommand( ) method, shown here:
String getActionCommand( )
➢ The getModifiers( ) method returns a value that indicates which modifier keys
(ALT, CTRL, META, and/or SHIFT) were pressed when the event was
generated. Its form is shown here:
int getModifiers( )
➢ The method getWhen( ) returns the time at which the event took place. This
is called the event’s timestamp. The getWhen( ) method is shown here:
long getWhen( )
3|P a g e
Object Oriented Concepts-MODULE 5 18CS45
AdjustmentEvent Class
➢ An AdjustmentEvent is generated by a scroll bar. There are five types of
adjustment events.
➢ AdjustmentEvent constructor:
AdjustmentEvent(Adjustable src, int id, int type, int data)
Here, src is a reference to the object that generated this event. The id
specifies the event. The type of the adjustment is specified by type, and its
associated data is data.
ComponentEvent Class
➢ A ComponentEvent is generated when the size, position, or visibility of a
component is changed.
➢ There are four types of component events.
ContainerEvent Class
➢ A ContainerEvent is generated when a component is added to or removed
from a container.
➢ There are two types of container events. The ContainerEvent class defines int
constants that can be used to identify them: COMPONENT_ADDED and
COMPONENT_REMOVED.
➢ ContainerEvent is a subclass of ComponentEvent and has this
constructor:
ContainerEvent(Component src, int type, Component comp)
Here, src is a reference to the container that generated this event. The type
of the event is specified by type, and the component that has been added to
or removed from the container is comp.
4|P a g e
Object Oriented Concepts-MODULE 5 18CS45
➢ You can obtain a reference to the container that generated this event by
using the getContainer( ) method, shown here:
Container getContainer( )
➢ The getChild( ) method returns a reference to the component that was
added to or removed from the container. Its general form is shown here:
Component getChild( )
FocusEvent Class
➢ A FocusEvent is generated when a component gains or loses input focus.
These events are identified by the integer constants FOCUS_GAINED and
FOCUS_LOST.
➢ FocusEvent is a subclass of ComponentEvent and has these
constructors:
FocusEvent(Component src, int type)
FocusEvent(Component src, int type, boolean temporaryFlag)
FocusEvent(Component src, int type, boolean temporaryFlag, Component other)
Here, src is a reference to the component that generated this event. The type
of the event is specified by type. The argument temporaryFlag is set to true
if the focus event is temporary. Otherwise, it is set to false.
➢ You can determine the other component by calling getOppositeComponent( ),
shown here:
Component getOppositeComponent( )
The opposite component is returned.
➢ The isTemporary( ) method indicates if this focus change is temporary. Its
form is shown here:
boolean isTemporary( )
The method returns true if the change is temporary. Otherwise, it returns
false.
InputEvent Class
➢ It is the superclass for component input events.
➢ Its subclasses are KeyEvent and MouseEvent.
➢ InputEvent defines several integer constants that represent any modifiers,
such as the control key being pressed, that might be associated with the
event.
➢ To test if a modifier was pressed at the time an event is generated, use the
isAltDown( ), isAltGraphDown( ), isControlDown( ), isMetaDown( ), and
isShiftDown( ) methods. The forms of these methods are shown here:
boolean isAltDown( )
boolean isAltGraphDown( )
boolean isControlDown( )
boolean isMetaDown( )
boolean isShiftDown( )
5|P a g e
Object Oriented Concepts-MODULE 5 18CS45
➢ You can obtain a value that contains all of the original modifier flags by
calling the getModifiers( ) method. It is shown here:
int getModifiers( )
ItemEvent Class
➢ An ItemEvent is generated when a check box or a list item is clicked or when
a checkable menu item is selected or deselected.
➢ There are two types of item events, which are identified by the following
integer constants:
KeyEvent Class
➢ A KeyEvent is generated when keyboard input occurs. There are three types
of key events, which are identified by these integer constants:
KEY_PRESSED, KEY_RELEASED, andKEY_TYPED.
➢ There are many other integer constants that are defined by KeyEvent. For
example, VK_0 through VK_9 and VK_A through VK_Z define the ASCII
equivalents of the numbers and letters. Here are some others:
6|P a g e
Object Oriented Concepts-MODULE 5 18CS45
MouseEvent Class
➢ There are eight types of mouse events.
7|P a g e
Object Oriented Concepts-MODULE 5 18CS45
MouseWheelEvent Class
➢ The MouseWheelEvent class encapsulates a mouse wheel event. It is a
subclass of MouseEvent.
➢ MouseWheelEvent defines these two integer constants:
TextEvent Class
➢ These are generated by text fields and text areas when characters are
entered by a user or program. TextEvent defines the integer constant
TEXT_VALUE_CHANGED.
➢ The one constructor for this class is shown here:
TextEvent(Object src, int type)
Here, src is a reference to the object that generated this event. The type
of the event is specified by type.
WindowEvent Class
➢ There are ten types of window events.
8|P a g e
Object Oriented Concepts-MODULE 5 18CS45
➢ getWindow( ). It returns the Window object that generated the event. Its
general form is shown here:
Window getWindow( )
Sources of Events
ActionListener Interface
This interface defines the actionPerformed( ) method that is invoked when an
action event occurs. Its general form is shown here:
void actionPerformed(ActionEvent ae)
AdjustmentListener Interface
This interface defines the adjustmentValueChanged( ) method that is
invoked when an adjustment event occurs. Its general form is shown here:
void adjustmentValueChanged(AdjustmentEvent ae)
9|P a g e
Object Oriented Concepts-MODULE 5 18CS45
10 | P a g e
Object Oriented Concepts-MODULE 5 18CS45
{
addMouseListener(this);
addMouseMotionListener(this);
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me)
{
// save coordinates
mouseX = 0; mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
// Handle mouse entered.
public void mouseEntered(MouseEvent me)
{
// save coordinates
mouseX = 0; mouseY = 10;
msg = "Mouse entered.";
repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent me)
{
// save coordinates
mouseX = 0; mouseY = 10;
msg = "Mouse exited.";
repaint();
}
// Handle button pressed.
public void mousePressed(MouseEvent me)
{
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent me)
{
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up"; repaint();
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me)
{
12 | P a g e
Object Oriented Concepts-MODULE 5 18CS45
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me)
{
// show status
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
// Display msg in applet window at
current X,Y location. public void
paint(Graphics g)
{
g.drawString(msg, mouseX, mouseY);
}
}
➢ It displays the current coordinates of the mouse in the applet’s status window.
Each time a button is pressed, the word “Down” is displayed at the location of
the mouse pointer.
Each time the button is released, the word “Up” is shown. If a button is
clicked, the message “Mouse clicked” is displayed in the upperleft corner of
the applet display area.
➢ It displays the current coordinates of the mouse in the applet’s status window.
Each time a button is pressed, the word “Down” is displayed at the location of
the mouse pointer. Each time the button is released, the word “Up” is shown.
If a button is clicked, the message “Mouse clicked” is displayed in the
upperleft corner of the applet display area.
➢ The MouseEvents class extends Applet and implements both the
MouseListener and MouseMotionListener interfaces.
➢ Inside init( ), the applet registers itself as a listener for mouse events. This
is done by using addMouseListener( ) and addMouseMotionListener( ), which,
as mentioned, are members of Component. They are shown here:
void addMouseListener(MouseListener ml)
void addMouseMotionListener(MouseMotionListener mml)
13 | P a g e
Object Oriented Concepts-MODULE 5 18CS45
// Display keystrokes.
public void paint(Graphics g)
{
g.drawString(msg, X, Y);
}
}
14 | P a g e
Object Oriented Concepts-MODULE 5 18CS45
Adapter Classes
For example, the MouseMotionAdapter class has two methods, mouseDragged( ) and
mouseMoved( ), which are the methods defined by the MouseMotionListener
interface. If you were interested in only mouse drag events, then you could simply
extend MouseMotionAdapter and override mouseDragged( ). The empty
implementation of mouseMoved( ) would handle the mouse motion events for you.
// Demonstrate
an adapter. import
java.awt.*; import
java.awt.event.*;
import java.applet.*;
/*
<applet code="AdapterDemo" width=300
height=100> </applet>
*/
public class AdapterDemo extends Applet
{
public void init()
{
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new
MyMouseMotionAdapter(this));
}
}
{
AdapterDemo adapterDemo;
public MyMouseMotionAdapter(AdapterDemo adapterDemo)
{
this.adapterDemo = adapterDemo;
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me)
{
adapterDemo.showStatus("Mouse dragged");
}
}
➢ It displays a message in the status bar of an applet viewer or browser when
the mouse is clicked or dragged. However, all other mouse events are silently
ignored.
➢ The program has three classes.
AdapterDemo extends Applet. Its init( ) method creates an instance of
MyMouseAdapter and registers that object to receive notifications of mouse
events. It also creates an instance of MyMouseMotionAdapter and registers
that object to receive notifications of mouse motion events.
Inner Classes
An inner class is a class defined within another class, or even within an expression.
// Inner class demo.
import java.applet.*;
import java.awt.event.*;
/*
<applet code="InnerClassDemo" width=200
height=100> </applet>
*/
public class InnerClassDemo extends Applet
{
public void init()
{
addMouseListener(new MyMouseAdapter());
}
class MyMouseAdapter extends MouseAdapter
{
public void mousePressed(MouseEvent me)
{
16 | P a g e
Object Oriented Concepts-MODULE 5 18CS45
showStatus("Mouse Pressed");
}
}
}
17 | P a g e
Object Oriented Concepts-MODULE 5 18CS45
Swings
Introduction
Swing contains a set of classes that provides more powerful and flexible GUI
components than those of AWT. Swing provides the look and feel of modern
Java GUI. Swing library is an official Java GUI tool kit released by Sun
Microsystems. It is used to create graphical user interface with Java.
Swing is a set of program component s for Java programmers that provide the ability
to create graphical user interface ( GUI ) components, such as buttons and scroll bars,
that are independent of the windowing system for specific operating system . Swing
The original Java GUI subsystem was the Abstract Window Toolkit (AWT).
(peers).
Under AWT, the look and feel of a component was defined by the platform.
1. Platform Independent
2. Customizable
3. Extensible
4. Configurable
5. Lightweight
18 | P a g e
Object Oriented Concepts-MODULE 5 18CS45
Model-View-Controller
Components
Swing components are derived from the JComponent class. The only
exceptions are the four top-level containers: JFrame, JApplet, JWindow,
and JDialog.
All the Swing components are represented by classes in the javax.swing package.
All the component classes start with J: JLabel, JButton, JScrollbar, ...
Containers
There are two types of containers:
19 | P a g e
Object Oriented Concepts-MODULE 5 18CS45
All the component classes start with J: JLabel, JButton, JScrollbar, ...
JRootPane manages the other panes and can add a menu bar.
The content pane is the container used for visual components. The
content pane is an instance of JPanel.
Swing is a very large subsystem and makes use of many packages. These are
The main package is javax.swing. This package must be imported into any
program that uses Swing. It contains the classes that implement the basic
javax.swing javax.swing.plaf.synth
javax.swing.border javax.swing.table
javax.swing.colorchooser javax.swing.text
javax.swing.event javax.swing.text.html
javax.swing.filechooser javax.swing.text.html.parser
javax.swing.plaf javax.swing.text.rtf
javax.swing.plaf.basic javax.swing.tree
javax.swing.plaf.metal javax.swing.undo
javax.swing.plaf.multi
20 | P a g e
Object Oriented Concepts-MODULE 5 18CS45
We can write the code of swing inside the main(), constructor or any
other method.
By creating the object of Frame class
import javax.swing.*;
public class FirstSwing
{
public static void main(String[] args)
{
JFrame f=new JFrame(“ MyApp”);
//creating instance of JFrame and title of the frame is
MyApp. JButton b=new JButton("click");
//creating instance of JButton and name of the button is click.
b.setBounds(130,100,100, 40); //x axis, y axis, width, height
f.add(b); //adding button in JFrame
f.setSize(400,500); //400 width and 500 height
f.setLayout(null); //using no layout managers
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true); //making the frame visible
}
}
Output:
21 | P a g e
Object Oriented Concepts-MODULE 5 18CS45
Explanation:
➢ The program begins by importing javax.swing. As mentioned, this package
contains the components and models defined by Swing.
➢ For example, javax.swing defines classes that implement labels, buttons,
text controls, and menus. It will be included in all programs that use
Swing. Next,
➢ the program declares the FirstSwing class
➢ It begins by creating a JFrame, using this line of code:
JFrame f = new JFrame("My App");
f.setSize(400,500);
➢ The setSize( ) method (which is inherited by JFrame from the AWT class
Component) sets the dimensions of the window, which are specified in
pixels. in this example, the width of the window is set to 400 and the height
is setto 500.
➢ By default, when a top-level window is closed (such as when the user clicks
the close box), the window is removed from the screen, but the application
is not terminated.
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Swing by inheritance
22 | P a g e
Object Oriented Concepts-MODULE 5 18CS45
import javax.swing.*;
public class MySwing extends JFram //inheriting JFrame
{
JFrame f;
MySwing()
{
JButton b=new JButton("click");//create
button b.setBounds(130,100,100, 40);
add(b);//adding button on
frame setSize(400,500);
setLayout(null);
setVisible(true);
}
public static void main(String[] args)
{
new MySwing();
}
}
JLabel(Icon icon)
JLabel(String str)
23 | P a g e
Object Oriented Concepts-MODULE 5 18CS45
import javax.swing.*;
public class JTextFieldPgm
{
f.add(namelabel);
f.add( passwordLabel);
f.add(userText);
f.add(passwordText);
f.setSize(300, 300);
f.setLayout(null);
f.setVisible(true);
24 | P a g e
Object Oriented Concepts-MODULE 5 18CS45
Output:
➢
JLabel can be used to display text and/or an icon. It is a passive component in
that it does not respond to user input. JLabel defines several constructors. Here
are three of them:
JLabel(Icon icon)
JLabel(String str)
Here, str and icon are the text and icon used for the label.
➢
These constants are defined in the Swing Constants interface, along with
several others used by the Swing classes. Notice that icons are specified
by
objects of type Icon, which is an interface defined by Swing.
➢
The easiest way to obtain an icon is to use the ImageIcon class. ImageIcon
implements Icon and encapsulates an image. Thus, an object of type
ImageIcon can be passed as an argument to the Icon parameter of
JLabel’s constructor.
ImageIcon(String filename)
25 | P a g e
Object Oriented Concepts-MODULE 5 18CS45
➢ It obtains the image in the file named filename. The icon and text
associated with the label can be obtained by the following methods:
Icon getIcon( )
String getText( )
The icon and text associated with a label can be set by these methods:
Here, icon and str are the icon and text, respectively. Therefore, using
setText( ) it is possible to change the text inside a label during program
execution.
import javax.swing.*;
JFrame jf=new
JFrame("Image Icon");
jf.setLayout(null);
26 | P a g e
Object Oriented Concepts-MODULE 5 18CS45
1. JButton
2. JRadioButton
3. JCheckBox
4. JComboBox
JButton(Icon ic)
JButton(String str)
import javax.swing.*;
class FirstSwing
{
public static void main(String args[])
{
JFrame jf=new JFrame("My App");
jf.add(jb);
jf.add(jb1);
jf.setSize(300, 600);
jf.setLayout(null);
jf.setVisible(true);
}
}
27 | P a g e
Object Oriented Concepts-MODULE 5 18CS45
import javax.swing.*;
public class RadioButton1
{
public static void main(String args[])
{
f.setSize(500,500);
f.setLayout(null);
f.setVisible(true);
}
}
28 | P a g e
Object Oriented Concepts-MODULE 5 18CS45
class FirstSwing
{
public static void main(String args[])
{
JFrame jf=new JFrame("CheckBox");
JCheckBox jb1=new
JCheckBox("Python");
jb1.setBounds(30, 200, 100, 50);
jf.add(jb);
jf.add(jb1);
jf.setSize(300, 600);
jf.setLayout(null);
jf.setVisible(true);
}
}
29 | P a g e
Object Oriented Concepts-MODULE 5 18CS45
import java.awt.*;
import javax.swing.*;
{
JFrame f=new JFrame("Combo demo");
String Branch[]={"cse","ise","ec","mech"};
jc.setBounds(50,50,80,50);
f.add(jc);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
30 | P a g e
Object Oriented Concepts-MODULE 5 18CS45
The JTable class is used to display the data on two dimensional tables of cells.
✓
JScrollPane is a lightweight container that automatically handles the
scrolling of another component.
✓
The component being scrolled can either be an individual component,
such as a table, or a group of components contained within another
lightweight container, such as a JPanel.
✓ In either case, if the object being scrolled is larger than the viewable
area, horizontal and/or vertical scroll bars are automatically provided,
and the component can be scrolled through the pane. Because
JScrollPane automates scrolling, it usually eliminates the need to manage
individual scroll bars.
✓
The viewable area of a scroll pane is called the viewport.
✓ It is a window in which the component being scrolled is displayed.
✓
Thus, the view port displays the visible portion of the component being
scrolled. The scroll bars scroll the component through the viewport.
✓
In its default behavior, a JScrollPane will dynamically add or remove a
scroll bar as needed. For example, if the component is taller than the
viewport, a vertical scroll bar is added. If the component will completely
fit within the viewport, the scroll bars are removed.
31 | P a g e
Object Oriented Concepts-MODULE 5 18CS45
import javax.swing.*;
public class TableExample1
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
JFrame f=new JFrame("Table Demo");
String data[][]={
{"100","CSE","VTU"}
,
{"101","ISE","VTU"}
,
{"102","CSE","VTU"}
,
{"103","ISE","VTU"}
,
{"105","ISE","VTU"}
,
{"106","ISE","VTU"}
};
String column[]={"courseID","Branch","University"};
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
}
}
32 | P a g e
Object Oriented Concepts-MODULE 5 18CS45
JTabbedpane
✓
JTabbedPane encapsulates a tabbed pane. It manages a set of components
by linking them with tabs.
✓ Selecting a tab causes the component associated with that tab to come to
the forefront. Tabbed panes are very common in the modern GUI.
✓
Given the complex nature of a tabbed pane, they are surprisingly easy
to create and use. JTabbedPane defines three constructors. We will
use its
default constructor, which creates an empty control with the tabs
positioned across the top of the pane.
✓
The other two constructors let you specify the location of the tabs, which
can be along any of the four sides.
✓
JTabbedPane uses the SingleSelectionModel model. Tabs are added by calling addTab( )
method. Here is one of its forms:
✓
Here, name is the name for the tab, and comp is the component that should
be added to the tab. Often, the component added to a tab is a JPanel that
contains a group of related components. This technique allows a tab to
hold a set of components.
import javax.swing.*;
{
public static void main(String[] a)
{
JFrame f = new JFrame("JTab");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JTabbedPaneDemo());
f.setSize(500, 500);
f.setVisible(true);
33 | P a g e
Object Oriented Concepts-MODULE 5 18CS45
{
makeGUI();
}
void makeGUI()
{
JTabbedPane jtp = new JTabbedPane();
add(jtp);
}
}
add(b1);
add(b2);
add(b3);
add(b4);
}
JCheckBox("Red"); add(cb1);
JCheckBox("Green"); add(cb2);
JCheckBox cb3 = new
JCheckBox("Blue"); add(cb3);
}
}
public FlavorsPanel()
{
JComboBox jcb = new JComboBox();
jcb.addItem("Vanilla");
jcb.addItem("Chocolate");
jcb.addItem("Strawberry");
add(jcb);
}
}
35 | P a g e
Object Oriented Concepts-MODULE 5 18CS45
JList:
JList(Object[ ] items)
✓
This creates a JList that contains the items in the array specified by items.
✓
JList is based on two models. The first is ListModel. This interface
defines how access to the list data is achieved.
✓
The second model is the ListSelectionModel interface, which defines
methods that determine what list item or items are selected.
import java.awt.FlowLayout;
import javax.swing.*;
list.setSelectedIndex(1);
frame.add(new JScrollPane(list));
frame.setSize(300, 400);
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
36 | P a g e
Object Oriented Concepts-MODULE 5 18CS45
3. AWT doesn't support pluggable look Swing supports pluggable look and feel.
and feel.
4. AWT provides less components than Swing provides more powerful
Swing. components such as tables, lists,
scrollpanes, colorchooser, tabbedpane
etc.
5. AWT doesn't follows MVC(Model Swing follows MVC .where model
View represents data, view represents
Controller) presentation and controller acts as an
interface between model and view.
37 | P a g e
Object Oriented Concepts-MODULE 5 18CS45
Questions
38 | P a g e