Академический Документы
Профессиональный Документы
Культура Документы
Uzair Salman
Packages .................................................................................................................................... 12
Exceptions ............................................................................................................................................. 12
Input/Output Streaming ....................................................................................................................... 13
1|Page
//Data Members
//Data Members
// Main function
// Object Creation
// Method Calling using object
// Method Calling using object
2|Page
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:
public class student {
String name;
int age;
public student()
{
name="abc";
age=0;
}
//constructor
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:
3|Page
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. Thats why encapsulation is known
as data hiding.
Example:
4|Page
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)
{
student obj=new student();
obj.setData("abc", 10);
obj.getData();
}
// Main function
// Object Declaration
// Method Calling using object
// Method Calling using object
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.
5|Page
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.
IS-A
CAR
Honda
HAS-A
Engine
6|Page
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
}
}
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:
Superior Group of Collage Jauharabad
7|Page
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
}
}
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.
8|Page
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.
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
}
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
9|Page
// Main function
// upcasting from subclass to
// Method Calling of class C
//Downcasting of reference to
//method calling of class C
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 cant 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:
10 | P a g e
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();
}
}
11 | 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.
their
own
packages
to
bundle
group
of
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.
Superior Group of Collage Jauharabad
12 | P a g e
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)
{
int no1, no2;
no1=5;
no2=0;
try
{
// Main function
//Data variables
//Contain some value
//contain some value
// Try block
System.out.println(no1/no2);
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
Superior Group of Collage Jauharabad
13 | P a g e
streams simply pass on data; others manipulate and transform the data in
useful ways.
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.*;
14 | P a g e
15 | 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).
16 | 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);
}
17 | P a g e
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)
{
18 | P a g e
obj.display();
class
}
}
JButton btnCalc;
JTextField number1;
JTextField number2;
JTextField op;
JTextField result;
JLabel lable1;
JLabel lable2;
JLabel lable3;
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
lable2=new
lable3=new
lable4=new
JLabel("First Number");
JLabel("Second Number");
JLabel("Operation");
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);
19 | P a g e
20 | P a g e
}
}
}
}
21 | P a g e