SlideShare a Scribd company logo
2
Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 2 | P a g e
Object & Classes
A class is a blueprint or template or set of instructions to build a specific type of
object. Every object is built from a class. Each class should be designed and
programmed to accomplish some tasks.
The term ‘object’, however, refers to an actual instance of a class. Every object
must belong to a class. Objects are created and eventually destroyed – so they
only live in the program for a limited time.
Or
Object - Objects have states and behaviors. Example: A CAR has states - color,
model, speed as well as behaviors –accelerate, break. An object is an instance
of a class.
Class - A class can be defined as a template/blue print that describes the
behaviors/states that object of its type support.
Following Example illustrate class and object declaration:
public class student {
String name; //Data Members
int age; //Data Members
public void setData(String n, int a) //Member Functions
{
name = n;
age = a;
}
public void getData() //Member Functions
{
System.out.println("Name s :"+name);
System.out.println("age is :"+age);
}
public static void main (String[] arrgs) // Main function
{
student obj=new student(); // Object Creation
obj.setData("abc", 10); // Method Calling using object
obj.getData(); // Method Calling using object
}
}
Most read
4
Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 4 | P a g e
Encapsulation
Encapsulation in Java is a mechanism of wrapping the data (variables) and code
acting on the data (methods) together as single unit. In encapsulation the
variables of a class will be hidden from other classes, No outside class can access
private data member (variable) of other class. However if we setup public getter
and setter methods to update and read the private data fields then the outside
class can access those private data fields via public methods. This way data can
only be accessed by public methods thus making the private fields and their
implementation hidden for outside classes. That’s why encapsulation is known
as data hiding.
Example:
public abstract class student { // making class abstract using abstract keyword
String name;
int age;
public void setData(String n, int a)
{
name= n;
age= a;
}
public void getData()
{
System.out.println("Name s :"+name);
System.out.println("age is :"+age);
}
public static void main (String[] arrgs)
{
student obj=new student(); /* Following is not allowed and raise error */
obj.show();
}
}
Most read
6
Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 6 | P a g e
Now, if we consider the IS-A relationship, we can say:
 Mammal IS-A Animal
 Reptile IS-A Animal
 Dog IS-A Mammal
 Hence: Dog IS-A Animal as well
HAS-A Relationship:
Composition (HAS-A) simply mean use of instance variables that are references
to other objects. For example: Honda has Engine, or House has Bathroom.
Types of inheritance in Java:
Below are various types of inheritance in Java.
 Single Inheritance
Single inheritance is damn easy to understand. When a class extends
another one class only then we call it a single inheritance. The below flow
diagram shows that class B extends only one class which is A. Here A is a
parent class of B and B would be a child class of A.
public class Animal{
}
public class Mammal extends Animal{
}
public class Reptile extends Animal{
}
public class Dog extends Mammal{
}
CAR
Engine
IS-A
HAS-AHonda
Most read
Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 1 | P a g e
Object Oriented Programming Using JAVA
Handouts
Table of Contents
Object & Classes......................................................................................................................................2
Constructor .............................................................................................................................................3
Abstraction..............................................................................................................................................3
Encapsulation..........................................................................................................................................4
Inheritance..............................................................................................................................................5
HAS-A Relationship: ............................................................................................................................6
 Single Inheritance....................................................................................................................6
 Multiple Inheritance................................................................................................................7
 Multilevel Inheritance .............................................................................................................7
 Hierarchical Inheritance ..........................................................................................................8
 Hybrid inheritance...................................................................................................................8
Up-casting & Down-casting.................................................................................................................9
Up-casting: ......................................................................................................................................9
Down-casting: .................................................................................................................................9
Interfaces ..............................................................................................................................................10
Wrapper Classes, Boxing & Unboxing, Packages..................................................................................11
 Wrapper Classes........................................................................................................................11
 Boxing & Unboxing....................................................................................................................12
 Packages....................................................................................................................................12
Exceptions.............................................................................................................................................12
Input/Output Streaming .......................................................................................................................13
 Reading Text File .......................................................................................................................14
 Writing to Text File....................................................................................................................15
Java Collection ......................................................................................................................................16
For-each loop........................................................................................................................................17
Some important Programs....................................................................................................................17
Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 2 | P a g e
Object & Classes
A class is a blueprint or template or set of instructions to build a specific type of
object. Every object is built from a class. Each class should be designed and
programmed to accomplish some tasks.
The term ‘object’, however, refers to an actual instance of a class. Every object
must belong to a class. Objects are created and eventually destroyed – so they
only live in the program for a limited time.
Or
Object - Objects have states and behaviors. Example: A CAR has states - color,
model, speed as well as behaviors –accelerate, break. An object is an instance
of a class.
Class - A class can be defined as a template/blue print that describes the
behaviors/states that object of its type support.
Following Example illustrate class and object declaration:
public class student {
String name; //Data Members
int age; //Data Members
public void setData(String n, int a) //Member Functions
{
name = n;
age = a;
}
public void getData() //Member Functions
{
System.out.println("Name s :"+name);
System.out.println("age is :"+age);
}
public static void main (String[] arrgs) // Main function
{
student obj=new student(); // Object Creation
obj.setData("abc", 10); // Method Calling using object
obj.getData(); // Method Calling using object
}
}
Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 3 | P a g e
Constructor
Constructor is a function in any class that is used to initialize data variables.
Every class has a constructor. If we do not explicitly write a constructor for a
class the Java compiler builds a default constructor for that class. Each time a
new object is created, at least one constructor will be invoked. The main rule of
constructors is that they should have the same name as the class and have no
return type. A class can have more than one constructor.
Example:
Abstraction
Abstraction is a process of hiding the implementation details from the user, only
the functionality will be provided to the user. An abstract class is one that cannot
be instantiated. All their functionality of the class still exists, and its fields,
methods, and constructors are all accessed in the same manner. You just cannot
create an instance of the abstract class. In Java Abstraction is achieved using
Abstract classes, and Interfaces.
Example:
public class student {
String name;
int age;
public student() //constructor
{
name="abc";
age=0;
}
public void show()
{
System.out.println("Name s :"+name);
System.out.println("age is :"+age);
}
public static void main (String[] arrgs)
{
student obj=new student();// constructor automatically calls
obj.show();
}
}
Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 4 | P a g e
Encapsulation
Encapsulation in Java is a mechanism of wrapping the data (variables) and code
acting on the data (methods) together as single unit. In encapsulation the
variables of a class will be hidden from other classes, No outside class can access
private data member (variable) of other class. However if we setup public getter
and setter methods to update and read the private data fields then the outside
class can access those private data fields via public methods. This way data can
only be accessed by public methods thus making the private fields and their
implementation hidden for outside classes. That’s why encapsulation is known
as data hiding.
Example:
public abstract class student { // making class abstract using abstract keyword
String name;
int age;
public void setData(String n, int a)
{
name= n;
age= a;
}
public void getData()
{
System.out.println("Name s :"+name);
System.out.println("age is :"+age);
}
public static void main (String[] arrgs)
{
student obj=new student(); /* Following is not allowed and raise error */
obj.show();
}
}
Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 5 | P a g e
Inheritance
Inheritance can be defined as the process where one class acquires the
properties (methods and fields) of another. With the use of inheritance the
information is made manageable in a hierarchical order. In other words, the
derived class inherits the states and behaviors from the base class. The derived
class is also called subclass and the base class is also known as super-class. The
derived class can add its own additional variables and methods. These additional
variable and methods differentiates the derived class from the base class.
When we talk about inheritance, the most commonly used keyword would be
extends and implements. The superclass and subclass have “is-a” relationship
between them.
IS-A Relationship:
IS-A is a way of saying: This object is a type of that object. Let us see how the
extends keyword is used to achieve inheritance.
public class student {
private String name; //Private Data Members
private int age; //private Data Members
public student() //constructor
{
name="abc";
age=0;
}
public void setData(String n, int a) //Member Functions
{
name = n;
age = a;
}
public void getData() //Member Functions
{
System.out.println("Name s :"+name);
System.out.println("age is :"+age);
}
public static void main (String[] arrgs) // Main function
{
student obj=new student(); // Object Declaration
obj.setData("abc", 10); // Method Calling using object
obj.getData(); // Method Calling using object
}
Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 6 | P a g e
Now, if we consider the IS-A relationship, we can say:
 Mammal IS-A Animal
 Reptile IS-A Animal
 Dog IS-A Mammal
 Hence: Dog IS-A Animal as well
HAS-A Relationship:
Composition (HAS-A) simply mean use of instance variables that are references
to other objects. For example: Honda has Engine, or House has Bathroom.
Types of inheritance in Java:
Below are various types of inheritance in Java.
 Single Inheritance
Single inheritance is damn easy to understand. When a class extends
another one class only then we call it a single inheritance. The below flow
diagram shows that class B extends only one class which is A. Here A is a
parent class of B and B would be a child class of A.
public class Animal{
}
public class Mammal extends Animal{
}
public class Reptile extends Animal{
}
public class Dog extends Mammal{
}
CAR
Engine
IS-A
HAS-AHonda
Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 7 | P a g e
Example:
 Multiple Inheritance
Multiple Inheritance” refers to the concept of one class extending (Or
inherits) more than one base class. Multiple Inheritance is very rarely used
in software projects. Using multiple inheritance often leads to problems
in the hierarchy. Most of the new OOP languages like Small Talk, Java, C#
do not support Multiple inheritance. Multiple Inheritance is supported in
C++.
 Multilevel Inheritance
Multilevel inheritance refers to a mechanism in OOP where one can inherit
from a derived class, thereby making this derived class the base class for the
new class. As you can see in below flow diagram C is subclass or child class of
B and B is a child class of A.
Example:
public class A
{
public void methodA()
{
System.out.println("Base class method");
}
}
public class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}
Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 8 | P a g e
 Hierarchical Inheritance
In such kind of inheritance one class is inherited by many sub classes. In
below example class B,C and D inherits the same class A.
 Hybrid inheritance
Hybrid inheritance is a combination of Single and Multiple inheritance. A
hybrid inheritance can be achieved in the java in a same way as
multiple inheritance can be!! Using interfaces. By using interfaces you can
have multiple as well as hybrid inheritance in Java.
class A
{
public void methodA()
{
System.out.println("Class A method");
}
}
class B extends A
{
public void methodB()
{
System.out.println("class B method");
}
}
class C extends B
{
public void methodC()
{
System.out.println("class C method");
}
public static void main(String arrgs[])
{
C obj = new C();
obj.methodA(); //calling grand parent class method
obj.methodB(); //calling parent class method
obj.methodC(); //calling local method
}
}
Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 9 | P a g e
Up-casting & Down-casting
Casting in java means converting from type to type. When it comes to the talking
about up-casting and down-casting concepts we are talking about converting
the objects references types between the child type classes and parent type
class. Suppose that we have three classes (A, B, C). Class B inherit from class A.
Class C inherit from class B. As follows
Up-casting:
The up casting is casting from the child class to base class. The up casting in java
is implicit which means that you don't have to put the braces (type) as an
indication for casting. Below is an example of up casting where we create a new
instance from class C and pass it to a reference of type A. Then we call the
function display.
Down-casting:
The up casting is casting from the base class to child class. The down-casting in
java is explicit which means that you have to put the braces (type) as an
indication for casting. Below is an example of down-casting
class A
{
void display(){}
}
class B implements A
{
public void display() {
System.out.println("Am in class B");
}
}
class C extends B
{
public void display() {
System.out.println("Am in class C");
}
}
public static void main (String[] arrgs) // Main function
{
A obj=new C(); // up-casting from subclass to super class
obj.display(); // Method Calling of class C
}
Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 10 | P a g e
Interfaces
Interface looks like class but it is not a class. An interface can have methods and
variables just like the class but the methods declared in interface are by default
abstract (only method signature, no body). Also, the variables declared in an
interface are public, static & final by default. We cannot instantiate an interface.
Also an interface does not have any constructor.
Since methods in interfaces are abstract and do not have body, they have to be
implemented by the class before you can access them. The class that
implements interface must implement all the methods of that interface. Also,
java programming language does not support multiple inheritances, using
interfaces we can achieve this as a class can implement more than one
interfaces.
Key Points:
 We can’t instantiate an interface in java.
 Interface provides complete abstraction as none of its methods can have
body.
 Implements keyword is used by classes to implement an interface.
 Any interface can extend any other interface but cannot implement it.
Class implements interface and interface extends interface.
 A class can implements any number of interfaces.
 An interface is written in a file with a .java extension, with the name of
the interface matching the name of the file.
 The interface keyword is used to declare an interface.
Example:
public static void main (String[] arrgs) // Main function
{
A obj=new C(); // upcasting from subclass to
super class
obj.display(); // Method Calling of class C
B objB=(B) obj; //Downcasting of reference to
subclass reference
objB.display(); //method calling of class C
}
Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 11 | P a g e
Wrapper Classes, Boxing & Unboxing, Packages
 Wrapper Classes
Each of Java's eight primitive data types (int, byte, shot, long, float, double,
Boolean, char) has a class dedicated to it. These are known as wrapper classes,
because they "wrap" the primitive data type into an object of that class. So there
is an Integer class that holds an int variable, there is a Double class that holds a
double variable, and so on. The wrapper classes are part of the java.lang
package, which is imported by default into all Java programs.
The following two statements illustrate the difference between a primitive
data type and an object of a wrapper class:
int x = 25;
Integer y = new Integer(33);
interface vehicle
{
/* All of the methods are abstract by default */
public void accelerate();
public void breaking();
}
class CAR implements vehicle
{
public void accelerate() {
System.out.println("Car is accelerating");
}
public void breaking() {
System.out.println("Break applied");
}
public static void main(String[] arrgs)
{
CAR obj=new CAR(); //object of Class CAR
obj.accelerate();
obj.breaking();
}
}
Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 12 | P a g e
The first statement declares an int variable named x and initializes it with the
value 25. The second statement instantiates an Integer object. The object is
initialized with the value 33 and a reference to the object is assigned to the
object variable y.
 Boxing & Unboxing
o Conversion of a primitive type to the corresponding reference type is
called boxing, such as an int to a java.lang.Integer.
o Conversion of the reference type to the corresponding primitive type is
called unboxing, such as Byte to byte.
 Packages
Packages are used in Java in order to prevent naming conflicts, to control
access, to make searching/locating and usage of classes, interfaces,
enumerations and annotations easier, etc. A Package can be defined as a
grouping of related types (classes, interfaces, enumerations and annotations)
providing access protection and name space management.
Some of the existing packages in Java are::
o java.lang - bundles the fundamental classes
o java.io - classes for input , output functions are bundled in this package
Programmers can define their own packages to bundle group of
Classes/interfaces, etc.
Exceptions
An exception (or exceptional event) is a problem that arises during the execution
of a program. When an Exception occurs the normal flow of the program is
disrupted and the program terminates abnormally, therefore these exceptions
are to be handled. An exception can occur for many different reasons, below
given are some scenarios where exception occurs.
o A user has entered invalid data.
o A file that needs to be opened cannot be found.
Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 13 | P a g e
A method catches an exception using a combination of the try and catch
keywords. A try/catch block is placed around the code that might generate an
exception. The syntax for using try/catch looks like the following:
try{
//Do something
}
catch(Exception ex)
{
//Catch exception hare using exception argument ex
}
The code which is prone to exceptions is placed in the try block, when an
exception occurs, that exception occurred is handled by catch block associated
with it.
Example:
public class ExceptionSample {
public static void main (String[] arrgs) // Main function
{
int no1, no2; //Data variables
no1=5; //Contain some value
no2=0; //contain some value
try // Try block
{
System.out.println(no1/no2); //attempt to divide number
by 0
}
catch (Exception ex) // Catch block receive exception
{
/* Display exception message */
System.out.println("Error with defination:
"+ex.getMessage()); }
}
}
Input/Output Streaming
The java.io package contains nearly every class you might ever need to
perform input and output (I/O) in Java. All these streams represent an input
source and an output destination. A stream can represent many different
kinds of sources and destinations, including disk files, devices, other programs,
and memory arrays. Streams support many different kinds of data, including
simple bytes, primitive data types, localized characters, and objects. Some
Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 14 | P a g e
streams simply pass on data; others manipulate and transform the data in
useful ways.
1: Reading information into program using StreamReader
2: Writing information from program using StreamWriter
You can read files using these classes:
• FileReader for text files in your system's default encoding (for example,
files containing Western European characters on a Western European
computer).
• FileInputStream for binary files and text files that contain 'weird'
characters
FileReader (for text files) should usually be wrapped in a BufferedFileReader.
This saves up data so you can deal with it a line at a time or whatever instead of
character by character. If you want to write files, basically all the same stuff
applies, except you'll deal with classes named FileWriter with
BufferedFileWriter for text files, or FileOutputStream for binary files.
 Reading Text File
If you want to read an ordinary text file in your system's default encoding, use
FileReader and wrap it in a BufferedReader. In the following program, we read
a file called "myFile.txt" and output the file line by line on the console.
import java.io.*;
Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 15 | P a g e
public class fileHandling {
String textFile;
String line;
public void ReadTextFile(String FileName)
{
textFile = FileName;
try {
FileReader Reader = new FileReader(textFile);
BufferedReader bufferedReader = new BufferedReader(Reader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close(); // close files.
}
catch(Exception ex) {
System.out.println("Error Reading File");
}
}
public static void main (String[] arrgs)
{
fileHandling obj=new fileHandling();
obj.ReadTextFile("c:MyFile.txt");
}
}
 Writing to Text File
To write a text file in Java, use FileWriter instead of FileReader, and
BufferedOutputWriter instead of BufferedOutputReader. Here's an
example program that creates a file called 'temp.txt' and writes some lines
of text to it.
import java.io.*;
public class fileHandling {
String textFile;
public void WriteFile(String File)
{
textFile = File;
try {
FileWriter Writer = new FileWriter(textFile);
BufferedWriter bufferedWriter =new BufferedWriter(Writer);
bufferedWriter.write("Hello there,");
bufferedWriter.newLine();
bufferedWriter.write("We are writing");
bufferedWriter.close(); // Always close files.
}
Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 16 | P a g e
catch(Exception ex) {
System.out.println("Error writing to file");
}
}
public static void main (String[] arrgs)
{
fileHandling obj=new fileHandling();
obj.WriteFile("c:MyFile.txt");
}
}
Java Collection
Collections in java is a framework that provides an architecture to store and
manipulate the group of objects. All the operations that you perform on a
data such as searching, sorting, insertion, manipulation, deletion etc. can be
performed by Java Collections.
Java Collection simply means a single unit of objects. Java Collection
framework provides many interfaces (Set, List, Queue, Deque etc.) and
classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet,
TreeSet etc).
Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 17 | P a g e
For-each loop
Anew way of iteration was introduced in Java 5 and offers a more convenient
way of iterating over arrays and collections. It is an extension to the classic
for loop and it is widely known as “enhanced for” or “for-each”. The main
difference between the classic for loop and the new loop is the fact that it
hides the iteration variable. As a result, usage of the for-each loop leads to a
more readable code with one less variable to consider each time we want to
create a loop thus the possibility of ending up with a logic error is smaller.
We can use it over both arrays and collections.
Example:
public static void main (String[] arrgs)
{
ArrayList arr=new ArrayList();
arr.add("A");
arr.add("B");
arr.add("C");
arr.add("D");
arr.add("E");
//Using foreach over collection
for (Object s : arr) {
System.out.println(s);
}
Some important Programs
 Write a program that has three fields hours, minute, second. To initialize
these fields it has constructor getter and setter methods, and a print time
method to display time. Also override toString method in this class.
public class TimeClass{
private int hour;
private int minute;
private int second;
public TimeClass()
{
hour = minute = second = 0;
}
Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 18 | P a g e
public void setter(int h, int m, int s)
{
if ( ( h >= 0 && h < 24 ) && ( m >= 0 && m < 60 ) && ( s >= 0 && s < 60 ) )
{
hour = h;
minute = m;
second = s;
}
}
public int getHour() {
return hour;
}
public int getMinute() {
return minute;
}
public int getSecond() {
return second;
}
public String toString()
{
return String.format( "%d:%02d:%02d %s",
( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ),
minute, second, ( hour < 12 ? "AM" : "PM" ) );
} // end method toString
public static void main(String[] arrgs)
{
TimeClass obj=new TimeClass();
obj.setter(12, 36, 25); // set time to 12:36:25
System.out.println(obj.toString()); // output: 12:36:25 PM
}
}
 Write a java program that has two classes point and circle. Circle class
extends point class. Demonstration up casting by using circle class.
class point
{
public void display() {
System.out.println("method of class point");
}
}
class Circle extends point
{
public void display() {
System.out.println("method of class circle");
}
public static void main (String[] arrgs)
{
Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 19 | P a g e
point obj=new Circle(); // up-casting from subclass to super
class
obj.display(); // Method Calling of class circle
}
}
 Use java swing library to create a simple four function arithmetic
calculator
import java.awt.event.*;
import javax.swing.*;
public class LoanCalc extends JFrame{
private JButton btnCalc;
private JTextField number1;
private JTextField number2;
private JTextField op;
private JTextField result;
private JLabel lable1;
private JLabel lable2;
private JLabel lable3;
private JLabel lable4;
LoanCalc()
{
setTitle("Basic Calculator");
setBounds(200,200,400,500);
btnCalc=new JButton("Calculate");
number1=new JTextField();
number2=new JTextField();
op=new JTextField();
result=new JTextField();
lable1=new JLabel("First Number");
lable2=new JLabel("Second Number");
lable3=new JLabel("Operation");
lable4=new JLabel("Result");
setLayout(null);
number1.setBounds(120, 100, 200, 50);
number2.setBounds(120, 150, 200, 50);
op.setBounds(120, 200, 200, 50);
result.setBounds(120, 350, 200, 50);
lable1.setBounds(20,100, 100,50);
lable2.setBounds(20, 150, 100, 50);
lable3.setBounds(20, 200, 100, 50);
lable4.setBounds(20, 350, 100, 50);
Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 20 | P a g e
btnCalc.setBounds(150, 280, 100, 50);
btnCalc.addActionListener(new listner());
btnCalc.setActionCommand("Calculate");
add(number1);
add(number2);
add(op);
add(result);
add(btnCalc);
add(lable1);
add(lable2);
add(lable3);
add(lable4);
}
public class listner implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String btn=e.getActionCommand();
int no1,no2, ans=0;
String opration;
if(btn=="Calculate")
{
no1= Integer.parseInt(number1.getText());
no2= Integer.parseInt(number1.getText());
opration= op.getText();
switch (opration) {
case "+":
ans=no1+no2;
break;
case "-":
ans=no1-no2;
break;
case "*":
ans=no1*no2;
break;
case "/":
if(no2>0)
ans=no1/no2;
else
ans=0;
break;
default:
ans=0;
Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 21 | P a g e
break;
}
result.setText(Integer.toString(ans));
}
}
}
}

More Related Content

What's hot (20)

PHP - Introduction to File Handling with PHP
PHP -  Introduction to  File Handling with PHPPHP -  Introduction to  File Handling with PHP
PHP - Introduction to File Handling with PHP
Vibrant Technologies & Computers
 
Filehandling
FilehandlingFilehandling
Filehandling
Amandeep Kaur
 
Cs8591 Computer Networks
Cs8591 Computer NetworksCs8591 Computer Networks
Cs8591 Computer Networks
Kathirvel Ayyaswamy
 
Distributed DBMS - Unit 1 - Introduction
Distributed DBMS - Unit 1 - IntroductionDistributed DBMS - Unit 1 - Introduction
Distributed DBMS - Unit 1 - Introduction
Gyanmanjari Institute Of Technology
 
Packages in java
Packages in javaPackages in java
Packages in java
Elizabeth alexander
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
Tech_MX
 
CS8651 Internet Programming - Basics of HTML, HTML5, CSS
CS8651   Internet Programming - Basics of HTML, HTML5, CSSCS8651   Internet Programming - Basics of HTML, HTML5, CSS
CS8651 Internet Programming - Basics of HTML, HTML5, CSS
Vigneshkumar Ponnusamy
 
Inter process communication
Inter process communicationInter process communication
Inter process communication
Pradeep Kumar TS
 
Multithreading
MultithreadingMultithreading
Multithreading
sagsharma
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
baabtra.com - No. 1 supplier of quality freshers
 
Object Oriented Relationships
Object Oriented RelationshipsObject Oriented Relationships
Object Oriented Relationships
Taher Barodawala
 
Php array
Php arrayPhp array
Php array
Nikul Shah
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
Hamid Ghorbani
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
AmbigaMurugesan
 
Action Bar in Android
Action Bar in AndroidAction Bar in Android
Action Bar in Android
Prof. Erwin Globio
 
Get and post methods
Get and post methodsGet and post methods
Get and post methods
baabtra.com - No. 1 supplier of quality freshers
 
XML Document Object Model (DOM)
XML Document Object Model (DOM)XML Document Object Model (DOM)
XML Document Object Model (DOM)
BOSS Webtech
 
Control Structure in JavaScript (1).pptx
Control Structure in JavaScript (1).pptxControl Structure in JavaScript (1).pptx
Control Structure in JavaScript (1).pptx
BansalShrivastava
 
XML and XML Applications - Lecture 04 - Web Information Systems (WE-DINF-11912)
XML and XML Applications - Lecture 04 - Web Information Systems (WE-DINF-11912)XML and XML Applications - Lecture 04 - Web Information Systems (WE-DINF-11912)
XML and XML Applications - Lecture 04 - Web Information Systems (WE-DINF-11912)
Beat Signer
 
Association agggregation and composition
Association agggregation and compositionAssociation agggregation and composition
Association agggregation and composition
baabtra.com - No. 1 supplier of quality freshers
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
Tech_MX
 
CS8651 Internet Programming - Basics of HTML, HTML5, CSS
CS8651   Internet Programming - Basics of HTML, HTML5, CSSCS8651   Internet Programming - Basics of HTML, HTML5, CSS
CS8651 Internet Programming - Basics of HTML, HTML5, CSS
Vigneshkumar Ponnusamy
 
Inter process communication
Inter process communicationInter process communication
Inter process communication
Pradeep Kumar TS
 
Multithreading
MultithreadingMultithreading
Multithreading
sagsharma
 
Object Oriented Relationships
Object Oriented RelationshipsObject Oriented Relationships
Object Oriented Relationships
Taher Barodawala
 
XML Document Object Model (DOM)
XML Document Object Model (DOM)XML Document Object Model (DOM)
XML Document Object Model (DOM)
BOSS Webtech
 
Control Structure in JavaScript (1).pptx
Control Structure in JavaScript (1).pptxControl Structure in JavaScript (1).pptx
Control Structure in JavaScript (1).pptx
BansalShrivastava
 
XML and XML Applications - Lecture 04 - Web Information Systems (WE-DINF-11912)
XML and XML Applications - Lecture 04 - Web Information Systems (WE-DINF-11912)XML and XML Applications - Lecture 04 - Web Information Systems (WE-DINF-11912)
XML and XML Applications - Lecture 04 - Web Information Systems (WE-DINF-11912)
Beat Signer
 

Viewers also liked (20)

Java essential notes
Java essential notesJava essential notes
Java essential notes
Habitamu Asimare
 
Java notes
Java notesJava notes
Java notes
jaswanth chodavarapu
 
Writing a sexier research abstract: Making research in life science more disc...
Writing a sexier research abstract: Making research in life science more disc...Writing a sexier research abstract: Making research in life science more disc...
Writing a sexier research abstract: Making research in life science more disc...
University of Michigan Taubman Health Sciences Library
 
Client Server models in JAVA
Client Server models in JAVAClient Server models in JAVA
Client Server models in JAVA
Tech_MX
 
Introduction to datastructure and algorithm
Introduction to datastructure and algorithmIntroduction to datastructure and algorithm
Introduction to datastructure and algorithm
Pratik Mota
 
Data structures and algorithms made easy java
Data structures and algorithms made easy   javaData structures and algorithms made easy   java
Data structures and algorithms made easy java
CareerMonk Publications
 
1 intro of data structure course
1  intro of data structure course1  intro of data structure course
1 intro of data structure course
Mahmoud Alfarra
 
Introduction to Data structure & Algorithms - Sethuonline.com | Sathyabama Un...
Introduction to Data structure & Algorithms - Sethuonline.com | Sathyabama Un...Introduction to Data structure & Algorithms - Sethuonline.com | Sathyabama Un...
Introduction to Data structure & Algorithms - Sethuonline.com | Sathyabama Un...
sethuraman R
 
Ebook En Sams Data Structures & Algorithms In Java
Ebook   En  Sams   Data Structures & Algorithms In JavaEbook   En  Sams   Data Structures & Algorithms In Java
Ebook En Sams Data Structures & Algorithms In Java
Aldo Quelopana
 
Client Server Architecture
Client Server ArchitectureClient Server Architecture
Client Server Architecture
Rence Montanes
 
Introduction of data structure
Introduction of data structureIntroduction of data structure
Introduction of data structure
eShikshak
 
Importance of laboratory equipments for education
Importance of laboratory equipments for educationImportance of laboratory equipments for education
Importance of laboratory equipments for education
eurodyneuk
 
Enterprise application integration
Enterprise application integrationEnterprise application integration
Enterprise application integration
Goa App
 
Carpet In Houston, TX
Carpet In Houston, TXCarpet In Houston, TX
Carpet In Houston, TX
Profloors
 
nibin_Resume
nibin_Resumenibin_Resume
nibin_Resume
Nibin W
 
Resume
ResumeResume
Resume
Ashley Granby
 
мистецтво доброчиності
мистецтво доброчиностімистецтво доброчиності
мистецтво доброчиності
2017oksanasaenko
 
Carpet Flooring In Houston TX
Carpet Flooring In Houston TXCarpet Flooring In Houston TX
Carpet Flooring In Houston TX
Profloors
 
March 2015: Top 10 Things to Know About DC Tech
March 2015: Top 10 Things to Know About DC TechMarch 2015: Top 10 Things to Know About DC Tech
March 2015: Top 10 Things to Know About DC Tech
dctmeetup
 
Quality Management Services
Quality Management ServicesQuality Management Services
Quality Management Services
VBS- Mena
 
Client Server models in JAVA
Client Server models in JAVAClient Server models in JAVA
Client Server models in JAVA
Tech_MX
 
Introduction to datastructure and algorithm
Introduction to datastructure and algorithmIntroduction to datastructure and algorithm
Introduction to datastructure and algorithm
Pratik Mota
 
Data structures and algorithms made easy java
Data structures and algorithms made easy   javaData structures and algorithms made easy   java
Data structures and algorithms made easy java
CareerMonk Publications
 
1 intro of data structure course
1  intro of data structure course1  intro of data structure course
1 intro of data structure course
Mahmoud Alfarra
 
Introduction to Data structure & Algorithms - Sethuonline.com | Sathyabama Un...
Introduction to Data structure & Algorithms - Sethuonline.com | Sathyabama Un...Introduction to Data structure & Algorithms - Sethuonline.com | Sathyabama Un...
Introduction to Data structure & Algorithms - Sethuonline.com | Sathyabama Un...
sethuraman R
 
Ebook En Sams Data Structures & Algorithms In Java
Ebook   En  Sams   Data Structures & Algorithms In JavaEbook   En  Sams   Data Structures & Algorithms In Java
Ebook En Sams Data Structures & Algorithms In Java
Aldo Quelopana
 
Client Server Architecture
Client Server ArchitectureClient Server Architecture
Client Server Architecture
Rence Montanes
 
Introduction of data structure
Introduction of data structureIntroduction of data structure
Introduction of data structure
eShikshak
 
Importance of laboratory equipments for education
Importance of laboratory equipments for educationImportance of laboratory equipments for education
Importance of laboratory equipments for education
eurodyneuk
 
Enterprise application integration
Enterprise application integrationEnterprise application integration
Enterprise application integration
Goa App
 
Carpet In Houston, TX
Carpet In Houston, TXCarpet In Houston, TX
Carpet In Houston, TX
Profloors
 
nibin_Resume
nibin_Resumenibin_Resume
nibin_Resume
Nibin W
 
мистецтво доброчиності
мистецтво доброчиностімистецтво доброчиності
мистецтво доброчиності
2017oksanasaenko
 
Carpet Flooring In Houston TX
Carpet Flooring In Houston TXCarpet Flooring In Houston TX
Carpet Flooring In Houston TX
Profloors
 
March 2015: Top 10 Things to Know About DC Tech
March 2015: Top 10 Things to Know About DC TechMarch 2015: Top 10 Things to Know About DC Tech
March 2015: Top 10 Things to Know About DC Tech
dctmeetup
 
Quality Management Services
Quality Management ServicesQuality Management Services
Quality Management Services
VBS- Mena
 
Ad

Similar to Object Oriented Programming using JAVA Notes (20)

packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
madhavi patil
 
Classes, objects, methods, constructors, this keyword in java
Classes, objects, methods, constructors, this keyword  in javaClasses, objects, methods, constructors, this keyword  in java
Classes, objects, methods, constructors, this keyword in java
TharuniDiddekunta
 
Modules 333333333³3444444444444444444.pptx
Modules 333333333³3444444444444444444.pptxModules 333333333³3444444444444444444.pptx
Modules 333333333³3444444444444444444.pptx
radhikacordise
 
Inheritance in java computer programming app
Inheritance in java computer programming appInheritance in java computer programming app
Inheritance in java computer programming app
figeman282
 
Unit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptxUnit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptx
DrYogeshDeshmukh1
 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methods
farhan amjad
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptx
akila m
 
Oop
OopOop
Oop
dilshod1988
 
constructer.pptx
constructer.pptxconstructer.pptx
constructer.pptx
Nagaraju Pamarthi
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programming
shinyduela
 
Java-U1-C_1.2.pptx its all about the java
Java-U1-C_1.2.pptx its all about the javaJava-U1-C_1.2.pptx its all about the java
Java-U1-C_1.2.pptx its all about the java
delta210210210
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
Sonu WIZIQ
 
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
SAJITHABANUS
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorial
rajkamaltibacademy
 
Jedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented conceptsJedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented concepts
Maryo Manjaruni
 
11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf
Export Promotion Bureau
 
Introduction to OOPs second year cse.pptx
Introduction to OOPs second year cse.pptxIntroduction to OOPs second year cse.pptx
Introduction to OOPs second year cse.pptx
solemanhldr
 
Inheritance
InheritanceInheritance
Inheritance
Daman Toor
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
madhavi patil
 
Classes, objects, methods, constructors, this keyword in java
Classes, objects, methods, constructors, this keyword  in javaClasses, objects, methods, constructors, this keyword  in java
Classes, objects, methods, constructors, this keyword in java
TharuniDiddekunta
 
Modules 333333333³3444444444444444444.pptx
Modules 333333333³3444444444444444444.pptxModules 333333333³3444444444444444444.pptx
Modules 333333333³3444444444444444444.pptx
radhikacordise
 
Inheritance in java computer programming app
Inheritance in java computer programming appInheritance in java computer programming app
Inheritance in java computer programming app
figeman282
 
Unit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptxUnit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptx
DrYogeshDeshmukh1
 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methods
farhan amjad
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptx
akila m
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programming
shinyduela
 
Java-U1-C_1.2.pptx its all about the java
Java-U1-C_1.2.pptx its all about the javaJava-U1-C_1.2.pptx its all about the java
Java-U1-C_1.2.pptx its all about the java
delta210210210
 
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
SAJITHABANUS
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorial
rajkamaltibacademy
 
Jedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented conceptsJedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented concepts
Maryo Manjaruni
 
Introduction to OOPs second year cse.pptx
Introduction to OOPs second year cse.pptxIntroduction to OOPs second year cse.pptx
Introduction to OOPs second year cse.pptx
solemanhldr
 
Ad

Recently uploaded (20)

Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
National Information Standards Organization (NISO)
 
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
Quiz Club of PSG College of Arts & Science
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti MpdBasic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
Quiz Club of PSG College of Arts & Science
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptxRai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptxWhat is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 SlidesHow to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti MpdBasic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptxWhat is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 SlidesHow to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 

Object Oriented Programming using JAVA Notes

  • 1. Prof. Uzair Salman Object Oriented Programming Using JAVA Superior Group of Collage Jauharabad 1 | P a g e Object Oriented Programming Using JAVA Handouts Table of Contents Object & Classes......................................................................................................................................2 Constructor .............................................................................................................................................3 Abstraction..............................................................................................................................................3 Encapsulation..........................................................................................................................................4 Inheritance..............................................................................................................................................5 HAS-A Relationship: ............................................................................................................................6  Single Inheritance....................................................................................................................6  Multiple Inheritance................................................................................................................7  Multilevel Inheritance .............................................................................................................7  Hierarchical Inheritance ..........................................................................................................8  Hybrid inheritance...................................................................................................................8 Up-casting & Down-casting.................................................................................................................9 Up-casting: ......................................................................................................................................9 Down-casting: .................................................................................................................................9 Interfaces ..............................................................................................................................................10 Wrapper Classes, Boxing & Unboxing, Packages..................................................................................11  Wrapper Classes........................................................................................................................11  Boxing & Unboxing....................................................................................................................12  Packages....................................................................................................................................12 Exceptions.............................................................................................................................................12 Input/Output Streaming .......................................................................................................................13  Reading Text File .......................................................................................................................14  Writing to Text File....................................................................................................................15 Java Collection ......................................................................................................................................16 For-each loop........................................................................................................................................17 Some important Programs....................................................................................................................17
  • 2. Prof. Uzair Salman Object Oriented Programming Using JAVA Superior Group of Collage Jauharabad 2 | P a g e Object & Classes A class is a blueprint or template or set of instructions to build a specific type of object. Every object is built from a class. Each class should be designed and programmed to accomplish some tasks. The term ‘object’, however, refers to an actual instance of a class. Every object must belong to a class. Objects are created and eventually destroyed – so they only live in the program for a limited time. Or Object - Objects have states and behaviors. Example: A CAR has states - color, model, speed as well as behaviors –accelerate, break. An object is an instance of a class. Class - A class can be defined as a template/blue print that describes the behaviors/states that object of its type support. Following Example illustrate class and object declaration: public class student { String name; //Data Members int age; //Data Members public void setData(String n, int a) //Member Functions { name = n; age = a; } public void getData() //Member Functions { System.out.println("Name s :"+name); System.out.println("age is :"+age); } public static void main (String[] arrgs) // Main function { student obj=new student(); // Object Creation obj.setData("abc", 10); // Method Calling using object obj.getData(); // Method Calling using object } }
  • 3. Prof. Uzair Salman Object Oriented Programming Using JAVA Superior Group of Collage Jauharabad 3 | P a g e Constructor Constructor is a function in any class that is used to initialize data variables. Every class has a constructor. If we do not explicitly write a constructor for a class the Java compiler builds a default constructor for that class. Each time a new object is created, at least one constructor will be invoked. The main rule of constructors is that they should have the same name as the class and have no return type. A class can have more than one constructor. Example: Abstraction Abstraction is a process of hiding the implementation details from the user, only the functionality will be provided to the user. An abstract class is one that cannot be instantiated. All their functionality of the class still exists, and its fields, methods, and constructors are all accessed in the same manner. You just cannot create an instance of the abstract class. In Java Abstraction is achieved using Abstract classes, and Interfaces. Example: public class student { String name; int age; public student() //constructor { name="abc"; age=0; } public void show() { System.out.println("Name s :"+name); System.out.println("age is :"+age); } public static void main (String[] arrgs) { student obj=new student();// constructor automatically calls obj.show(); } }
  • 4. Prof. Uzair Salman Object Oriented Programming Using JAVA Superior Group of Collage Jauharabad 4 | P a g e Encapsulation Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as single unit. In encapsulation the variables of a class will be hidden from other classes, No outside class can access private data member (variable) of other class. However if we setup public getter and setter methods to update and read the private data fields then the outside class can access those private data fields via public methods. This way data can only be accessed by public methods thus making the private fields and their implementation hidden for outside classes. That’s why encapsulation is known as data hiding. Example: public abstract class student { // making class abstract using abstract keyword String name; int age; public void setData(String n, int a) { name= n; age= a; } public void getData() { System.out.println("Name s :"+name); System.out.println("age is :"+age); } public static void main (String[] arrgs) { student obj=new student(); /* Following is not allowed and raise error */ obj.show(); } }
  • 5. Prof. Uzair Salman Object Oriented Programming Using JAVA Superior Group of Collage Jauharabad 5 | P a g e Inheritance Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With the use of inheritance the information is made manageable in a hierarchical order. In other words, the derived class inherits the states and behaviors from the base class. The derived class is also called subclass and the base class is also known as super-class. The derived class can add its own additional variables and methods. These additional variable and methods differentiates the derived class from the base class. When we talk about inheritance, the most commonly used keyword would be extends and implements. The superclass and subclass have “is-a” relationship between them. IS-A Relationship: IS-A is a way of saying: This object is a type of that object. Let us see how the extends keyword is used to achieve inheritance. public class student { private String name; //Private Data Members private int age; //private Data Members public student() //constructor { name="abc"; age=0; } public void setData(String n, int a) //Member Functions { name = n; age = a; } public void getData() //Member Functions { System.out.println("Name s :"+name); System.out.println("age is :"+age); } public static void main (String[] arrgs) // Main function { student obj=new student(); // Object Declaration obj.setData("abc", 10); // Method Calling using object obj.getData(); // Method Calling using object }
  • 6. Prof. Uzair Salman Object Oriented Programming Using JAVA Superior Group of Collage Jauharabad 6 | P a g e Now, if we consider the IS-A relationship, we can say:  Mammal IS-A Animal  Reptile IS-A Animal  Dog IS-A Mammal  Hence: Dog IS-A Animal as well HAS-A Relationship: Composition (HAS-A) simply mean use of instance variables that are references to other objects. For example: Honda has Engine, or House has Bathroom. Types of inheritance in Java: Below are various types of inheritance in Java.  Single Inheritance Single inheritance is damn easy to understand. When a class extends another one class only then we call it a single inheritance. The below flow diagram shows that class B extends only one class which is A. Here A is a parent class of B and B would be a child class of A. public class Animal{ } public class Mammal extends Animal{ } public class Reptile extends Animal{ } public class Dog extends Mammal{ } CAR Engine IS-A HAS-AHonda
  • 7. Prof. Uzair Salman Object Oriented Programming Using JAVA Superior Group of Collage Jauharabad 7 | P a g e Example:  Multiple Inheritance Multiple Inheritance” refers to the concept of one class extending (Or inherits) more than one base class. Multiple Inheritance is very rarely used in software projects. Using multiple inheritance often leads to problems in the hierarchy. Most of the new OOP languages like Small Talk, Java, C# do not support Multiple inheritance. Multiple Inheritance is supported in C++.  Multilevel Inheritance Multilevel inheritance refers to a mechanism in OOP where one can inherit from a derived class, thereby making this derived class the base class for the new class. As you can see in below flow diagram C is subclass or child class of B and B is a child class of A. Example: public class A { public void methodA() { System.out.println("Base class method"); } } public class B extends A { public void methodB() { System.out.println("Child class method"); } public static void main(String args[]) { B obj = new B(); obj.methodA(); //calling super class method obj.methodB(); //calling local method } }
  • 8. Prof. Uzair Salman Object Oriented Programming Using JAVA Superior Group of Collage Jauharabad 8 | P a g e  Hierarchical Inheritance In such kind of inheritance one class is inherited by many sub classes. In below example class B,C and D inherits the same class A.  Hybrid inheritance Hybrid inheritance is a combination of Single and Multiple inheritance. A hybrid inheritance can be achieved in the java in a same way as multiple inheritance can be!! Using interfaces. By using interfaces you can have multiple as well as hybrid inheritance in Java. class A { public void methodA() { System.out.println("Class A method"); } } class B extends A { public void methodB() { System.out.println("class B method"); } } class C extends B { public void methodC() { System.out.println("class C method"); } public static void main(String arrgs[]) { C obj = new C(); obj.methodA(); //calling grand parent class method obj.methodB(); //calling parent class method obj.methodC(); //calling local method } }
  • 9. Prof. Uzair Salman Object Oriented Programming Using JAVA Superior Group of Collage Jauharabad 9 | P a g e Up-casting & Down-casting Casting in java means converting from type to type. When it comes to the talking about up-casting and down-casting concepts we are talking about converting the objects references types between the child type classes and parent type class. Suppose that we have three classes (A, B, C). Class B inherit from class A. Class C inherit from class B. As follows Up-casting: The up casting is casting from the child class to base class. The up casting in java is implicit which means that you don't have to put the braces (type) as an indication for casting. Below is an example of up casting where we create a new instance from class C and pass it to a reference of type A. Then we call the function display. Down-casting: The up casting is casting from the base class to child class. The down-casting in java is explicit which means that you have to put the braces (type) as an indication for casting. Below is an example of down-casting class A { void display(){} } class B implements A { public void display() { System.out.println("Am in class B"); } } class C extends B { public void display() { System.out.println("Am in class C"); } } public static void main (String[] arrgs) // Main function { A obj=new C(); // up-casting from subclass to super class obj.display(); // Method Calling of class C }
  • 10. Prof. Uzair Salman Object Oriented Programming Using JAVA Superior Group of Collage Jauharabad 10 | P a g e Interfaces Interface looks like class but it is not a class. An interface can have methods and variables just like the class but the methods declared in interface are by default abstract (only method signature, no body). Also, the variables declared in an interface are public, static & final by default. We cannot instantiate an interface. Also an interface does not have any constructor. Since methods in interfaces are abstract and do not have body, they have to be implemented by the class before you can access them. The class that implements interface must implement all the methods of that interface. Also, java programming language does not support multiple inheritances, using interfaces we can achieve this as a class can implement more than one interfaces. Key Points:  We can’t instantiate an interface in java.  Interface provides complete abstraction as none of its methods can have body.  Implements keyword is used by classes to implement an interface.  Any interface can extend any other interface but cannot implement it. Class implements interface and interface extends interface.  A class can implements any number of interfaces.  An interface is written in a file with a .java extension, with the name of the interface matching the name of the file.  The interface keyword is used to declare an interface. Example: public static void main (String[] arrgs) // Main function { A obj=new C(); // upcasting from subclass to super class obj.display(); // Method Calling of class C B objB=(B) obj; //Downcasting of reference to subclass reference objB.display(); //method calling of class C }
  • 11. Prof. Uzair Salman Object Oriented Programming Using JAVA Superior Group of Collage Jauharabad 11 | P a g e Wrapper Classes, Boxing & Unboxing, Packages  Wrapper Classes Each of Java's eight primitive data types (int, byte, shot, long, float, double, Boolean, char) has a class dedicated to it. These are known as wrapper classes, because they "wrap" the primitive data type into an object of that class. So there is an Integer class that holds an int variable, there is a Double class that holds a double variable, and so on. The wrapper classes are part of the java.lang package, which is imported by default into all Java programs. The following two statements illustrate the difference between a primitive data type and an object of a wrapper class: int x = 25; Integer y = new Integer(33); interface vehicle { /* All of the methods are abstract by default */ public void accelerate(); public void breaking(); } class CAR implements vehicle { public void accelerate() { System.out.println("Car is accelerating"); } public void breaking() { System.out.println("Break applied"); } public static void main(String[] arrgs) { CAR obj=new CAR(); //object of Class CAR obj.accelerate(); obj.breaking(); } }
  • 12. Prof. Uzair Salman Object Oriented Programming Using JAVA Superior Group of Collage Jauharabad 12 | P a g e The first statement declares an int variable named x and initializes it with the value 25. The second statement instantiates an Integer object. The object is initialized with the value 33 and a reference to the object is assigned to the object variable y.  Boxing & Unboxing o Conversion of a primitive type to the corresponding reference type is called boxing, such as an int to a java.lang.Integer. o Conversion of the reference type to the corresponding primitive type is called unboxing, such as Byte to byte.  Packages Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc. A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations) providing access protection and name space management. Some of the existing packages in Java are:: o java.lang - bundles the fundamental classes o java.io - classes for input , output functions are bundled in this package Programmers can define their own packages to bundle group of Classes/interfaces, etc. Exceptions An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program terminates abnormally, therefore these exceptions are to be handled. An exception can occur for many different reasons, below given are some scenarios where exception occurs. o A user has entered invalid data. o A file that needs to be opened cannot be found.
  • 13. Prof. Uzair Salman Object Oriented Programming Using JAVA Superior Group of Collage Jauharabad 13 | P a g e A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. The syntax for using try/catch looks like the following: try{ //Do something } catch(Exception ex) { //Catch exception hare using exception argument ex } The code which is prone to exceptions is placed in the try block, when an exception occurs, that exception occurred is handled by catch block associated with it. Example: public class ExceptionSample { public static void main (String[] arrgs) // Main function { int no1, no2; //Data variables no1=5; //Contain some value no2=0; //contain some value try // Try block { System.out.println(no1/no2); //attempt to divide number by 0 } catch (Exception ex) // Catch block receive exception { /* Display exception message */ System.out.println("Error with defination: "+ex.getMessage()); } } } Input/Output Streaming The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays. Streams support many different kinds of data, including simple bytes, primitive data types, localized characters, and objects. Some
  • 14. Prof. Uzair Salman Object Oriented Programming Using JAVA Superior Group of Collage Jauharabad 14 | P a g e streams simply pass on data; others manipulate and transform the data in useful ways. 1: Reading information into program using StreamReader 2: Writing information from program using StreamWriter You can read files using these classes: • FileReader for text files in your system's default encoding (for example, files containing Western European characters on a Western European computer). • FileInputStream for binary files and text files that contain 'weird' characters FileReader (for text files) should usually be wrapped in a BufferedFileReader. This saves up data so you can deal with it a line at a time or whatever instead of character by character. If you want to write files, basically all the same stuff applies, except you'll deal with classes named FileWriter with BufferedFileWriter for text files, or FileOutputStream for binary files.  Reading Text File If you want to read an ordinary text file in your system's default encoding, use FileReader and wrap it in a BufferedReader. In the following program, we read a file called "myFile.txt" and output the file line by line on the console. import java.io.*;
  • 15. Prof. Uzair Salman Object Oriented Programming Using JAVA Superior Group of Collage Jauharabad 15 | P a g e public class fileHandling { String textFile; String line; public void ReadTextFile(String FileName) { textFile = FileName; try { FileReader Reader = new FileReader(textFile); BufferedReader bufferedReader = new BufferedReader(Reader); while((line = bufferedReader.readLine()) != null) { System.out.println(line); } bufferedReader.close(); // close files. } catch(Exception ex) { System.out.println("Error Reading File"); } } public static void main (String[] arrgs) { fileHandling obj=new fileHandling(); obj.ReadTextFile("c:MyFile.txt"); } }  Writing to Text File To write a text file in Java, use FileWriter instead of FileReader, and BufferedOutputWriter instead of BufferedOutputReader. Here's an example program that creates a file called 'temp.txt' and writes some lines of text to it. import java.io.*; public class fileHandling { String textFile; public void WriteFile(String File) { textFile = File; try { FileWriter Writer = new FileWriter(textFile); BufferedWriter bufferedWriter =new BufferedWriter(Writer); bufferedWriter.write("Hello there,"); bufferedWriter.newLine(); bufferedWriter.write("We are writing"); bufferedWriter.close(); // Always close files. }
  • 16. Prof. Uzair Salman Object Oriented Programming Using JAVA Superior Group of Collage Jauharabad 16 | P a g e catch(Exception ex) { System.out.println("Error writing to file"); } } public static void main (String[] arrgs) { fileHandling obj=new fileHandling(); obj.WriteFile("c:MyFile.txt"); } } Java Collection Collections in java is a framework that provides an architecture to store and manipulate the group of objects. All the operations that you perform on a data such as searching, sorting, insertion, manipulation, deletion etc. can be performed by Java Collections. Java Collection simply means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
  • 17. Prof. Uzair Salman Object Oriented Programming Using JAVA Superior Group of Collage Jauharabad 17 | P a g e For-each loop Anew way of iteration was introduced in Java 5 and offers a more convenient way of iterating over arrays and collections. It is an extension to the classic for loop and it is widely known as “enhanced for” or “for-each”. The main difference between the classic for loop and the new loop is the fact that it hides the iteration variable. As a result, usage of the for-each loop leads to a more readable code with one less variable to consider each time we want to create a loop thus the possibility of ending up with a logic error is smaller. We can use it over both arrays and collections. Example: public static void main (String[] arrgs) { ArrayList arr=new ArrayList(); arr.add("A"); arr.add("B"); arr.add("C"); arr.add("D"); arr.add("E"); //Using foreach over collection for (Object s : arr) { System.out.println(s); } Some important Programs  Write a program that has three fields hours, minute, second. To initialize these fields it has constructor getter and setter methods, and a print time method to display time. Also override toString method in this class. public class TimeClass{ private int hour; private int minute; private int second; public TimeClass() { hour = minute = second = 0; }
  • 18. Prof. Uzair Salman Object Oriented Programming Using JAVA Superior Group of Collage Jauharabad 18 | P a g e public void setter(int h, int m, int s) { if ( ( h >= 0 && h < 24 ) && ( m >= 0 && m < 60 ) && ( s >= 0 && s < 60 ) ) { hour = h; minute = m; second = s; } } public int getHour() { return hour; } public int getMinute() { return minute; } public int getSecond() { return second; } public String toString() { return String.format( "%d:%02d:%02d %s", ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ), minute, second, ( hour < 12 ? "AM" : "PM" ) ); } // end method toString public static void main(String[] arrgs) { TimeClass obj=new TimeClass(); obj.setter(12, 36, 25); // set time to 12:36:25 System.out.println(obj.toString()); // output: 12:36:25 PM } }  Write a java program that has two classes point and circle. Circle class extends point class. Demonstration up casting by using circle class. class point { public void display() { System.out.println("method of class point"); } } class Circle extends point { public void display() { System.out.println("method of class circle"); } public static void main (String[] arrgs) {
  • 19. Prof. Uzair Salman Object Oriented Programming Using JAVA Superior Group of Collage Jauharabad 19 | P a g e point obj=new Circle(); // up-casting from subclass to super class obj.display(); // Method Calling of class circle } }  Use java swing library to create a simple four function arithmetic calculator import java.awt.event.*; import javax.swing.*; public class LoanCalc extends JFrame{ private JButton btnCalc; private JTextField number1; private JTextField number2; private JTextField op; private JTextField result; private JLabel lable1; private JLabel lable2; private JLabel lable3; private JLabel lable4; LoanCalc() { setTitle("Basic Calculator"); setBounds(200,200,400,500); btnCalc=new JButton("Calculate"); number1=new JTextField(); number2=new JTextField(); op=new JTextField(); result=new JTextField(); lable1=new JLabel("First Number"); lable2=new JLabel("Second Number"); lable3=new JLabel("Operation"); lable4=new JLabel("Result"); setLayout(null); number1.setBounds(120, 100, 200, 50); number2.setBounds(120, 150, 200, 50); op.setBounds(120, 200, 200, 50); result.setBounds(120, 350, 200, 50); lable1.setBounds(20,100, 100,50); lable2.setBounds(20, 150, 100, 50); lable3.setBounds(20, 200, 100, 50); lable4.setBounds(20, 350, 100, 50);
  • 20. Prof. Uzair Salman Object Oriented Programming Using JAVA Superior Group of Collage Jauharabad 20 | P a g e btnCalc.setBounds(150, 280, 100, 50); btnCalc.addActionListener(new listner()); btnCalc.setActionCommand("Calculate"); add(number1); add(number2); add(op); add(result); add(btnCalc); add(lable1); add(lable2); add(lable3); add(lable4); } public class listner implements ActionListener { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub String btn=e.getActionCommand(); int no1,no2, ans=0; String opration; if(btn=="Calculate") { no1= Integer.parseInt(number1.getText()); no2= Integer.parseInt(number1.getText()); opration= op.getText(); switch (opration) { case "+": ans=no1+no2; break; case "-": ans=no1-no2; break; case "*": ans=no1*no2; break; case "/": if(no2>0) ans=no1/no2; else ans=0; break; default: ans=0;
  • 21. Prof. Uzair Salman Object Oriented Programming Using JAVA Superior Group of Collage Jauharabad 21 | P a g e break; } result.setText(Integer.toString(ans)); } } } }