2. Interfaces
What Is an Interface?
In general, an interface is a device or a system that
unrelated entities use to interact. According to this
definition, a remote control is an interface between
you and a television set, the English language is an
interface between two people, An interface is a point
where two systems meet and interact.
3. Interfaces are available in many languages such as PHP,
Java, and C#. Interfaces were first introduced in PHP
5. An interface cannot contain properties, only constants
and methods. All methods must be public and not
contain any code inside.
4. LIBRARIES
Graphics and user interfaces
Many modern software systems are interactive, interacting with their users
through graphics and other pleasant interface techniques. This is one of the
areas where the object oriented model has proved most impressive and helpful.
Developers should be able to rely on graphical libraries to build interactive
applications quickly and effectively.
Note : Reusable classes should be available for developing applications which
provide their users with pleasant graphical user interface.
5. Why do we use interface ?
It is used to achieve total abstraction(Means all the methods in interface are
declared with empty body and are public and all fields are public static
and final by default.).
Since java does not support multiple inheritance in case of class, but by using
interface it can achieve multiple inheritance .
It is also used to achieve loose coupling.
Interfaces are used to implement abstraction. So the question arises why use
interfaces when we have abstract classes?
The reason is, abstract classes may contain non-final variables, whereas
variables in interface are final, public and static.
6. Difference between abstract class and interface
Abstract class and interface both are used to achieve abstraction where we can
declare the abstract methods. Abstract class and interface both can't be
instantiated.
But there are many differences between abstract class and interface that are given
below.
7. Abstract class Interface
1) Abstract class can have abstract and
non-abstract methods.
Interface can have only abstract methods. Since
Java 8, it can have default and static methods also.
2) Abstract class doesn't support multiple
inheritance.
Interface supports multiple inheritance
3) Abstract class can have final, non-final,
static and non-static variables.
Interface has only static and final variables.
4) Abstract class can provide the
implementation of interface.
Interface can't provide the implementation of
abstract class.
5) The abstract keyword is used to declare
abstract class.
The interface keyword is used to declare interface
6) A Java abstract class can have class
members like private, protected, etc..
Members of a Java interface are public by default.
7) An abstract class can be extended using
keyword "extends".
An interface can be implemented using keyword
"implements"
9)Example:
public abstract class Shape{
public abstract void draw();
}
Example:
public interface Drawable{
void draw();
}
8. From a programming perspective, an interface sits
between software components. Consider that a method
header (method name, parameter list, and so on)
interface sits between external code that calls the
method and the code within the method that will be
executed as a result of the call. Here's an example of java
interface:
9. How to declare an interface?
An interface is declared by using the interface keyword. It provides total abstraction;
means all the methods in an interface are declared with the empty body, and all the
fields are public, static and final by default. A class that implements an interface must
implement all the methods declared in the interface.
Syntax:
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}
To implement interface use implements keyword
10. Like a class, an interface can have methods and variables, but the methods
declared in an interface are by default abstract (only method signature, no
body).
The relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface
extends another interface, but a class implements an interface.
11. Example of an Interface in Java
This is how a class implements an interface. It has to provide the body of all the methods that are declared in
interface or in other words you can say that class has to implement all the methods of interface.
In this example, the Printable interface has only one method, and its implementation is provided in the A6 class.
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
Output:
Hello
12. Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends
multiple interfaces, it is known as multiple inheritance.
14. What is the use of interface in Java?
As mentioned above they are used for full abstraction. Since
methods in interfaces 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 allow you to extend more than one class, However
you can implement more than one interfaces in your class.
15. Advantages of interface in java:
Advantages of using interfaces are as follows:
Without bothering about the implementation part, we
can achieve the security of implementation
In java, multiple inheritance is not allowed, however you
can use interface to make use of it as you can implement
more than one interface.
16. Important points about interface or summary of interface:
1) We can’t instantiate an interface in java. That means we cannot create the object of
an interface
2)A class can implement more than one interface.
3) implements keyword is used by classes to implement an interface.
4) To declare an interface, use interface keyword
5)An interface can extends another interface or interfaces (more than one interface) .
6)A class that implements interface must implements all the methods in interface.
7)All the methods are public and abstract. And all the fields are public, static, and final.
8) While providing implementation in class of any method of an interface, it needs to be
mentioned as public and Interface cannot be declared as private, protected .
9)It is used to achieve multiple inheritance.
From Java 9 onwards, interfaces can contain following also
Static methods
Private methods
18. Errors
Errors are the problems or the faults that occur in the program, which makes the behavior of the
program abnormal.
Even experienced developers can also make these faults.
Programming errors are also known as the bugs or faults, and the process of removing these
bugs is known as debugging.
19. There are different kinds of errors:
Syntax errors
-True syntax error
-Semantic errors
Logical errors
Runtime errors
20. Exceptions
An exception is an event that occurs during the execution of a program that
disrupts the normal flow of instructions.
Exceptions provide a way to transfer control from one part of a program to
another. C++ exception handling is built upon three keywords: try, catch, and
throw
21. Exception Handling:
The error handling mechanism of c++ is generally referred to as exception
handling.
Exceptions are an elegant mechanism for handling errors You can't ignore
exceptions if you don't handle them, your program will crash.
Generally , exceptions are classified into synchronous and asynchronous
exceptions..
22. Synchronous exception
The exceptions which occur during the program execution, due to some fault in the input data
or technique that is not suitable to handle the current class of data. With in a program is known
as synchronous exception.
Example:
errors such as out of range, overflow, underflow and so on.
23. Asynchronous exceptions
The exceptions caused by events or faults unrelated to the program and beyond the control of program
are asynchronous exceptions.
For example
errors such as keyboard interrupts, hardware malfunctions, disk failure and so on.
24. exception handling model:
throw − A program throws an exception
when a problem
shows up. This is done using a throw
keyword.
catch − A program catches an exception
with an exception handler at the place in a
program where you want to handle the
problem. The catch keyword indicates
the catching of an exception.
try − A try block identifies a block of code
for which particular exceptions will be
25. Example
void main()
{
int a, b;
Cout <<”enter two numbers:”;
Cin >>a>>b;
try
{
if (b= =0)
throw b;
else
Cout <a/b;
}
catch(int x)
{
Cout <<”2nd operand can’t be 0”;
}
}
26. Access Modifers
Access modifiers are object-oriented programming that is used to set the
accessibility of classes, constructors, methods, and other members of Java.
Using the access modifiers we can set the scope or accessibility of these classes,
methods, constructors, and other members.
27. Four Types of Access Modifiers
Example: we have created two classes A and Simple. A class contains private data member and private
method. We are accessing these private members from outside the class, so there is a compile-time
error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
} }
Private: We can access the private modifier only within
the same class and not from outside the class.
28. Role of Private Constructor
EXAMPLE:
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
If you make any class constructor private, you cannot
create the instance of that class from outside the class.
29. Default: We can access the default modifier only within the same package and not from
outside the package. And also, if we do not specify any access modifier it will automatically
consider it as default.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
} }
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the
package.
Example: we have created two packages pack and mypack. We are
accessing the A class from outside its package, since A class is not public,
so it cannot be accessed from outside the package.
30. Protected: We can access the protected modifier within the same package and also from outside the
package with the help of the child class. If we do not make the child class, we cannot access it from
outside the package. So inheritance is a must for accessing it from outside the package.
Eg: we have created the two packages pack and mypack. The A class of pack package is public, so can be
accessed from outside the package. But msg method of this package is declared as protected, so it can be
accessed from outside the class only through inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output : Hello
31. Public: We can access the public modifier from anywhere. We can access public modifiers from within
the class as well as from outside the class and also within the package and from outside the package.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output: Hello
32. Understanding Java Access Modifiers
Access Modifier within class within package outside package by
subclass only
outside package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Let's understand the access modifiers in Java by a simple
table
33. User Defined Exceptions
What are user defined exception?
User Defined Exception or custom exception
is creating your own exception class and
throws that exception using ‘throw’ keyword
34. Advantages
UserDefined exceptions helps throwing an error
page depending on the business logic.
Eg. Suppose that i want to add a user to the
system but at the same time somebody has
already added the same user and in such senario i
want to show a specif error page to the user
36. Type Parametric Polymorphism
There are two major types of polymorphisms in Object Oriented Programming (OOPS)
languages.
They are Static Binding (Compile time Polymorphism)
Dynamic Binding (Runtime Polymorphism).
Method overriding would be the example of Dynamic Polymorphism and Method Overloading
would be the example of Static Polymorphism.
We can perform polymorphism in java by method overloading and method overriding.
37. Compile Time Polymorphism
Whenever an object is bound with their functionality at the compile-time, this is known
as the compile-time polymorphism.
Basically it takes place when the program is getting compile, So this is called compile-
time polymorphism or static or early binding.
Compile-time polymorphism is achieved through method overloading.
38. Which method to call is decided by compiler.
In compile time polymorphism object is same
but parameters are different.
39. Runtime polymorphism
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an
overridden method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a superclass.
We also call Dynamic binding as Late Binding because binding takes place during the actual
execution of the program.
40. Which method to call is decided by JVM in run time.
In run time polymorphism object is same and
parameters are also same.
41. Collections
What are Collections?
The Collection in Java is a framework that provides an architecture to
store and manipulate the group of objects. Java Collections can achieve
all the operations that you perform on a data such as searching, sorting,
insertion, manipulation, and deletion. Java Collection means a single unit
of objects.
The Collection interface (java.util.Collection) and Map interface
(java.util.Map) are the two main “root” interfaces of Java collection classes.
42. Why do we need collections?
• Resize the array?
• Insert an element in between?
• Delete an elements in Array?
• Apply certain operations to change this array
43. Advantages
1. Consistent API: The API has a basic set of interface like Collection, Set, List, or
Map.
2. Reduces programming effort: A programmer doesn’t have to worry about the
design of the Collection.
3. Increases program speed and quality: Increases performance by providing
high-performance implementations of useful data structures.
44. Methods of the Collection Interface
add(Object): This method is used to add an object to the collection.
addAll(Collection c): This method adds all the elements in the given collection to
this collection.
clear(): This method removes all of the elements from this collection.
contains(Object o): This method returns true if the collection contains the
specified element.
isEmpty(): This method returns true if this collection contains no elements.
47. Packages
What are Packages?
Package in Java is a mechanism to encapsulate a group of classes, sub
packages and interfaces. Packages are used for Preventing naming
conflicts. For example there can be two classes with name Employee in
two packages, college. ... Employee and college.
48. How packages work?
Package names and directory structure are closely related.
For example if a package name is college.staff.cse, then there are three
directories, college, staff and cse such that cse is present in staff and staff
is present college. Also, the directory college is accessible through
Classpath variable, i.e., path of parent directory of college is present in
Classpath. The idea is to make sure that classes are easy to locate.
49. How to use packages?
Adding a class to a Package : We can add more classes to a created package
by using package name at the top of the program and saving it in the package
directory. We need a new java file to define a public class, otherwise we can
add the new class to an existing .java file and recompile it.
Subpackages: Packages that are inside another package are the subpackages.
These are not imported by default, they have to imported explicitly. Also,
members of a subpackage have no access privileges, i.e., they are considered as
different package for protected and default access specifiers.
Example :
50. How to use packages?
Accessing classes inside a package
Following statement is used to import Vector class from util package which is
contained inside java.
51. How to use packages?
Following statement imports all the classes from util package.
52. Types of packages
Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some
of the commonly used built-in packages are:
1) java.lang: Contains language support classes(e.g classed which defines
primitive data types, math operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked
List, Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user
interfaces (like button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.
53. Types of packages
User-defined packages
These are the packages that are defined by the user. First we create a directory
myPackage (name should be same as the name of the package). Then create the
MyClass inside the directory with the first statement being the package names.
Example :
54. Advantages
Programmers can define their own packages to bundle a group of
classes/interfaces, etc.
It is a good practice to group related classes implemented so that a programmer
can easily determine that the classes, interfaces, enumerations, and annotations
are related.
Since the package creates a new namespace there won't be any name conflicts
with names in other packages.
Using packages, it is easier to provide access control
It is also easier to locate the related classes.