Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Unit I Java & J2EE

The document outlines a programming course focused on Java and J2EE, detailing the syllabus, course outcomes, and program outcomes. It covers fundamental concepts of Java, including object-oriented programming principles, exception handling, multithreading, and web application development using servlets and JSP. Additionally, it provides resources and examples for practical application of these concepts.

Uploaded by

white Devil
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Unit I Java & J2EE

The document outlines a programming course focused on Java and J2EE, detailing the syllabus, course outcomes, and program outcomes. It covers fundamental concepts of Java, including object-oriented programming principles, exception handling, multithreading, and web application development using servlets and JSP. Additionally, it provides resources and examples for practical application of these concepts.

Uploaded by

white Devil
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 99

Programming Using

Java & J2EE (Integrated)


20MCA22
Overview of the Course
• Syllabus
• Course Outcomes
• Program Outcomes
Syllabus
• Java
• Unit I: The Java Language, Inheritance and Interfaces
• Unit II: Exception handling and Multithreaded Programming
• J2EE
• Unit III: Servlets
• Unit IV: Java Server Pages and Controlling the Structure of generated
servlets
• Unit V: JDBC
Course Outcomes
Course Outcome (COs)
Bloom’s
At the end of the course, the student will be able to
Level
Build console applications using the basic concepts of OOP and exceptions
1. L3
handling mechanisms of core Java technology
Develop console applications using multiple threads and interface key
2. L3
features of Java.
Develop web applications using servlets to process client request, cookies
3. L3
and session tracking.
Construct powerful web applications using Java Server Pages with implicit
4. L3
variables JSP action tags, directive tags, and Java Beans
Apply JDBC API to access the different databases like MySQL, Oracle and
5. L3
DB2 from Java applications
6 Develop secure Java web applications for any enterprise business logic. L6
Program Outcomes

Sl. Program Outcome of this course (POs) PO


no No.
1 Postgraduates will demonstrate an ability to design and 3
conduct experiments, analyze and interpret data
2 Postgraduates will demonstrate an ability to design a system, 4
component or process as per needs and specifications
3 Postgraduates will demonstrate skills to use modern software 6
tools and technology to build and test applications
Books
Text Books
1 Herbert Schildt, Java The Complete Reference, Eight Edition. Tata McGraw-Hill
Edition – 2011

2 Marty Hall, Larry Brown, Core Servlets and Java Server Pages. Volume 1: Core
Technologies. Second Edition

3 Java 6 Programming Black Book, Dreamtech Press. 2012


4 Web Technologies: HTML, Javascript, XML and , PHP, Java, JSP ASP.net, Ajax Black
Book Kogent learning Solutions Inc/Wiley india 2008
Unit I: The Java Language,
Inheritance and Interfaces
• The Java language: The Java Buzz words ,Object Oriented
Programming, The Three OOP Principles, A first simple program
• Introducing Classes: class fundamentals, declaring objects,
introducing methods, constructors, The this keyword
• Inheritance: Basics of inheritance, Method Overriding, Dynamic
Method Dispatch, Using Abstract classes Interfaces, Default Interface
Methods, Use static methods in an Interface
The Java Buzz words
• Simple
• Object oriented
• Distributed
• Interpreted
• Robust
• Secure
• Architecture neutral
• Portable
• High performance
• Multithreaded
• Dynamic
Simple
• Java was designed to be easy for professional programmer to learn
and use effectively.
• It’s simple and easy to learn if you already know the basic concepts
of Object Oriented Programming.
• C++ programmer can move to JAVA with very little effort to learn.
• In Java, there is small number of clearly defined ways to accomplish
a given task
Object Oriented
• Java is true object oriented language.
• Almost “Everything is an Object” paradigm. All program code and
data reside within objects and classes.
• The object model in Java is simple and easy to extend.
• Java comes with an extensive set of classes, arranged in packages
that can be used in our programs through inheritance.
Distributed
• Java is designed for distributed environment of the Internet.
• Its used for creating applications on networks.
• Java applications can access remote objects on Internet as easily as
they can do in local system.
• Java enables multiple programmers at multiple remote locations to
collaborate and work together on a single project.
Compiled and Interpreted
• Usually a computer language is either compiled or Interpreted. Java
combines both this approach and makes it a two-stage system.
• Compiled : Java enables creation of a cross platform programs by
compiling into an intermediate representation called Java Bytecode.
• Interpreted : Bytecode is then interpreted, which generates machine
code that can be directly executed by the machine that provides a
Java Virtual machine.
Robust
• It provides many features that make the program execute reliably in
variety of environments.
• Java is a strictly typed language. It checks code both at compile time
and runtime.
• Java takes care of all memory management problems with garbage-
collection.
• Java, with the help of exception handling captures all types of
serious errors and eliminates any risk of crashing the system.
Secure
• Java provides a “firewall” between a networked application and
your computer.
• When a Java Compatible Web browser is used, downloading can be
done safely without fear of viral infection or malicious intent.
• Java achieves this protection by confining a Java program to the java
execution environment and not allowing it to access other parts of
the computer.
Architecture Neutral
• Java language and Java Virtual Machine helped in achieving the goal
of “write once; run anywhere, any time, forever.”
• Changes and upgrades in operating systems, processors and system
resources will not force any changes in Java Programs.
Portable
• Java Provides a way to download programs dynamically to all the
various types of platforms connected to the Internet.
• It helps in generating Portable executable code.
High Performance
• Java performance is high because of the use of bytecode.
• The bytecode was used, so that it was easily translated into native
machine code.
Multithreaded
• Multithreaded Programs handled multiple tasks simultaneously,
which was helpful in creating interactive, networked programs.
• Java run-time system comes with tools that support multiprocess
synchronization used to construct smoothly interactive systems.
Dynamic
• Java is capable of linking in new class libraries, methods, and
objects.
• It can also link native methods (the functions written in other
languages such as C and C++).
Object Oriented Programming
• Object means a real-world entity such as a pen, chair, table, computer,
watch, etc. Object-Oriented Programming is a methodology or paradigm to
design a program using classes and objects. It simplifies software
development and maintenance by providing some concepts:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Object
• Any entity that has state and behavior is known as an
object.
• For example, a chair, pen, table, keyboard, bike, etc. It can
be physical or logical.
• An Object can be defined as an instance of a class.
• An object contains an address and takes up some space in
memory.
• Objects can communicate without knowing the details of
each other's data or code.
• The only necessary thing is the type of message accepted
and the type of response returned by the objects.
Class
• Collection of objects is called class.
• It is a logical entity.
• A class can also be defined as a blueprint from which you can create
an individual object.
• Class doesn't consume any space.
Inheritance
• When one object acquires all the properties and behaviors of a parent
object, it is known as inheritance.
• It provides code reusability.
• It is used to achieve runtime polymorphism.
Polymorphism
• If one task is performed in different ways, it is known as
polymorphism.
• For example: to convince the customer differently, to draw
something, for example, shape, triangle, rectangle, etc.
• In Java, we use method overloading and method overriding to achieve
polymorphism.
• Another example can be to speak something; for example, a cat
speaks meow, dog barks woof, etc.
Abstraction
• Hiding internal details and showing functionality is known as
abstraction.
• For example phone call, we don't know the internal processing.
• In Java, we use abstract class and interface to achieve abstraction.
Encapsulation
• Binding (or wrapping) code and data together into a single unit are
known as encapsulation.
• For example, a capsule, it is wrapped with different medicines.
• A java class is the example of encapsulation.
• Java bean is the fully encapsulated class because all the data
members are private here.
The Three OOP Principles
• Encapsulation
• Inheritance
• Polymorphism
Encapsulation
Inheritance
Polymorphism
A First Simple Program
Compiling and executing the
Program
• Command to compile the program
C:\>javac Example.java
• To run the program
C:\>java Example
A Second Short Program
Introducing Classes
• The General Form of a Class
class classname
{
type instance-variable1;
type instance-variable2;
// ...type instance-variableN;
type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list)
{
// body of method}//
...
type methodnameN(parameter-list)
{
// body of method
}
}
A Simple Class
• Box class
class Box
{
double width;
double height;
double depth;
}
• Creating an object for the Box Class
Box mybox = new Box(); // create a Box object called mybox
• To access the members of the class from the object
mybox.width = 100;
A Complete Example
/* A program that uses the Box class.
Call this file BoxDemo.java
*/
class Box {
double width;
double height;
double depth;
}
// This class declares an object of type Box.
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
Declaring Objects
• Box mybox = new Box();
• This can be written as
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
A Closer Look at new
• The new operator dynamically allocates memory for an object.
• General Syntax
class-var= new classname( );
Assigning Object Reference
Variables
Box b1 = new Box();
Box b2 = b1;
Introducing Methods

• Methods that have a return type other than void return a value to the
calling routine using the following form of the return statement:
return value;
Adding a Method to the Box Class
Returning a Value
Important Things To Understand
About Returning Values
• The type of data returned by a method must be compatible with the return
type specified by the method.
• For example, if the return type of some method is boolean, you could not return an
integer.
• The variable receiving the value returned by a method (such as vol, in this
case) must also be compatible with the return type specified for the
method.
• The call to volume( )could have been used in the println( )statement
directly
System.out.println("Volume is " + mybox1.volume());
Adding a Method That Takes
Parameters
Constructors
• Initializes an object immediately upon creation.
• It has the same name as the class in which it resides
• Syntactically similar to a method.
• It is automatically called immediately after the object is created,
before the new operator completes.
• Constructors look a little strange because they have no return type,
not even void.
• Initialize the internal state of an object so that the code creating an
instance will have a fully initialized, usable object immediately.
Example
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxDemo6 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Calling the
Constructor/Instantiating an
object
• General Syntax
class-var = new classname( );
• Example
Box mybox1 = new Box();
Parameterized Constructors
• Default constructor initializes all object with the same data.
• Dynamic initialization is required to allow different object with its own
data.
• Parameterized Constructor can be used to initialize each object with
different data.
Example
/* Here, Box uses a parameterized constructor to
initialize the dimensions of a box.
*/
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxDemo7 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
The this Keyword
• A method will need to refer to the object that invoked it.
• Java defines the this keyword.
• this can be used inside any method to refer to the current object.
• this is always a reference to the object on which the method was invoked
• Example
// A redundant use of this.
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
class BoxDemo7 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Instance Variable Hiding
// Use this to resolve name-space collisions.
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
Overloading Methods
• Two or more methods within the same class that share the same name, as
long as their parameter declarations are different.
• The methods are said to be overloaded, and the process is referred to as
method overloading.
• When an overloaded method is invoked, Java uses the type and/or number
of arguments as its guide to determine which version of the overloaded
method to actually call.
• Overloaded methods must differ in the type and/or number of their
parameters.
• While overloaded methods may have different return types, the return type
alone is insufficient to distinguish two versions of a method.
Overloading Constructors
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
Using Objects as Parameters
// Objects may be passed to methods.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// return true if o is equal to the invoking object
boolean equals(Test o) {
if(o.a == a && o.b == b) return true;
else return false;
}
}
Main Class
class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}
A Closer Look at Argument
Passing
• Call by Value
• Primitive data like int, float, double, etc
• Call by Reference
• Objects like String, Integer, Float, user defined classes objects (Students,
Employees, Projects etc)
Returning Objects
// Returning an object. public static void main(String args[]) {
class Test { Test ob1 = new Test(2);
int a; Test ob2;
Test(int i) { ob2 = ob1.incrByTen();
a = i; System.out.println("ob1.a: " + ob1.a);
} System.out.println("ob2.a: " + ob2.a);
Test incrByTen() { ob2 = ob2.incrByTen();
Test temp = new Test(a+10); System.out.println("ob2.a after second
increase: “ + ob2.a);
return temp;
} }
}
}
class RetOb {
Recursion
// A simple example of recursion.
class Factorial {
// this is a recursive method
int fact(int n) {
int result;
if(n==1) return 1;
result = fact(n-1) * n;
return result;
}
}
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
Introducing Access Control
• Control what parts of a program can access the members of a class.
• Prevent misuse
• Java’s access specifiers are public, private, and protected.
• protected applies only when inheritance is involved.
• A member of a class is modified by the public specifier, then that
member can be accessed by any other code.
• When a member of a class is specified as private, then that member
can only be accessed by other members of its class.
• Default access is public
/* This program demonstrates the difference public static void main(String args[]) {
between public and private. Test ob = new Test();
*/ // These are OK, a and b may be accessed
directly
class Test {
ob.a = 10;
int a; // default access
ob.b = 20;
public int b; // public access
// This is not OK and will cause an error
private int c; // private access
// ob.c = 100; // Error!
// methods to access c
// You must access c through its methods
void setc(int i) { // set c's value
ob.setc(100); // OK
c = i;
System.out.println("a, b, and c: " + ob.a +
}
""+
int getc() { // get c's value
ob.b + " " + ob.getc());
return c;
}
}
}
}
class AccessTest {
Understanding static
• Static defines a class member that will be used independently of any object of that
class.
• To create such a member, precede its declaration with the keyword static.
• When a member is declared static, it can be accessed before any objects of its class
are created, and without reference to any object.
• Both methods and variables can be declared static.
• The most common example of a static member is main( ).
• main( ) is declared as static because it must be called before any objects exist.
• Instance variables declared as static are global variables.
• When objects of its class are declared, no copy of a static variable is made.
• All instances of the class share the same static variable
Methods declared as static have
several restrictions
• They can only call other static methods.
• They must only access static data.
• They cannot refer to this or super in any way.
// Demonstrate static variables, methods, and blocks.
class UseStatic {
static int a = 3;
static int b;
static void meth(int x) {
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static {
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42);
}
}
Introducing final
• A variable can be declared as final.
• Prevents its contents from being modified.
• This means that you must initialize a final variable when it is declared.
• Example
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
final int FILE_SAVEAS = 4;
final int FILE_QUIT = 5;
Inheritance
• Allows the creation of hierarchical classifications.
• Create a general class that defines traits common to a set of related
items.
• This class can then be inherited by other, more specific classes, each
adding those things that are unique to it.
• A class that is inherited is called a superclass.
• The class that does the inheriting is called a subclass.
• A subclass is a specialized version of a superclass.
• It inherits all of the instance variables and methods defined by the
superclass and adds its own, unique elements.
Inheritance Basics
• To inherit a class incorporate the definition of one class into another
by using the extends keyword.
// A simple example of inheritance.
// Create a superclass.
class A {
private int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
/* The subclass has access to all public members of its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
The general form of a class
declaration that inherits a
superclass
class subclass-name extends superclass-name {
// body of class
}
Member Access and Inheritance
• A subclass includes all of the members of its superclass, it cannot
access those members of the superclass that have been declared as
private
/* In a class hierarchy, private members remain class Access {
private to their class. public static void main(String args[]) {
This program contains an error and will not B subOb = new B();
compile. subOb.setij(10, 12);
*/ subOb.sum();
// Create a superclass. System.out.println("Total is " + subOb.total);
class A { }
int i; // public by default }
private int j; // private to A
void setij(int x, int y) {
i = x;
j = y;
}
}
// A's j is not accessible here.
class B extends A {
int total;
void sum() {
total = i + j; // ERROR, j is not accessible here
}
}
A Superclass Variable Can
Reference a Subclass Object
• A reference variable of a superclass can be assigned a reference to
any subclass derived from that superclass.
Using super
• Using super to Call Superclass Constructors
• A Second Use for super
When Constructors Are Called
• Constructors are called in order of derivation, from superclass to
subclass.
• super( ) must be the first statement executed in a subclass’
constructor, this order is the same whether or not super( ) is used.
• If super( ) is not used, then the default or parameterless constructor
of each superclass will be executed.
// Demonstrate when constructors are called.
// Create a super class.
class A {
A() {
System.out.println("Inside A's constructor.");
}
}
// Create a subclass by extending class A.
class B extends A {
B() {
System.out.println("Inside B's constructor.");
}
}
// Create another subclass by extending B.
class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}
class CallingCons {
public static void main(String args[]) {
C c = new C();
}
}
Method Overriding
• In a class hierarchy, when a method in a subclass has the same name
and type signature as a method in its superclass, then the method in
the subclass is said to override the method in the superclass.
• When an overridden method is called from within a subclass, it will
always refer to the version of that method defined by the subclass.
• The version of the method defined by the superclass will be hidden
• Method overriding occurs only when the names and the type
signatures of the two methods are identical.
• If they are not, then the two methods are simply overloaded.
// Method overriding. // display k – this overrides show() in A
class A { void show() {
int i, j; System.out.println("k: " + k);
A(int a, int b) { }
i = a; }
j = b; class Override {
} public static void main(String args[]) {
// display i and j B subOb = new B(1, 2, 3);
void show() { SubOb.show(); // this calls show() in B
System.out.println("i and j: " + i + " " + j); }
} }
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
Use super to call the superclass
methods
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() {
super.show(); // this calls A's show()
System.out.println("k: " + k);
}
}
Dynamic Method Dispatch
• Dynamic method dispatch is the mechanism by which a call to an
overridden method is resolved at run time, rather than compile time.
• Dynamic method dispatch is important because this is how Java
implements run-time polymorphism.
• Important principle: a superclass reference variable can refer to a
subclass object. Java uses this fact to resolve calls to overridden
methods at run time.
• When an overridden method is called through a superclass reference,
Java determines which version of that method to execute based upon
the type of the object being referred to at the time the call occurs
// Dynamic Method Dispatch
class A {
void callme() {
System.out.println("Inside A's callme method");
}
}
class B extends A {
// override callme()
void callme() {
System.out.println("Inside B's callme method");
}
}
class C extends A {
// override callme()
void callme() {
System.out.println("Inside C's callme method");
}
}
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}
References
Objects
r = a; // r refers to an A object
a Aa A r.callme(); // calls A's version of callme
r = b; // r refers to a B object

b B B A r

r.callme(); // calls B's version of callme

c C C
Using Abstract Classes
• Defines a superclass that declares the structure of a given abstraction
without providing a complete implementation of every method.
• Creates a superclass that only defines a generalized form that will be
shared by all of its subclasses, leaving it to each subclass to fill in the
details.
• Such a class determines the nature of the methods that the
subclasses must implement.
Abstract Method
• Are methods defined in the superclass as abstract
• Are methods be overridden by subclasses
• These methods are sometimes referred to as subclasser responsibility
because they have no implementation specified in the superclass.
• General Form:
abstract type name(parameter-list);
Abstract class cont..
• Any class that contains one or more abstract methods must also be
declared abstract.
• To declare a class abstract, you simply use the abstract keyword in front
of the class keyword at the beginning of the class declaration.
• There can be no objects of an abstract class.
• Abstract class cannot be directly instantiated with the new operator.
• An abstract class is not fully defined.
• Abstract constructors, or abstract static methods cannot be declared.
• Any subclass of an abstract class must either implement all of the
abstract methods in the superclass, or be itself declared abstract.
// A Simple demonstration of abstract.
abstract class A {
abstract void callme();

// concrete methods are still allowed in abstract classes


void callmetoo() {
System.out.println("This is a concrete method.");
}
}
class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo {
public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
}
}
Interfaces
• Fully abstract a class
• Specify what a class must do, but not how it does it.
• Syntactically similar to classes, but they lack instance variables, and their methods are
declared without any body.
• Once defined, any number of classes can implement an interface.
• One class can implement any number of interfaces.
• To implement an interface, a class must create the complete set of methods defined by
the interface.
• Each class is free to determine the details of its own implementation.
• By providing the interface keyword, Java allows o fully utilize the “one interface, multiple
methods” aspect of polymorphism.
• Designed to support dynamic method resolution at run time.
Defining an Interface
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
//...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
Interfaces cont..
• Variables can be declared inside of interface declarations.
• They are implicitly final and static, meaning they cannot be changed
by the implementing class.
• They must also be initialized.
• All methods and variables are implicitly public.
• Example
interface Callback {
void callback(int param);
}
Implementing Interfaces
• Include the implements clause in a class definition.
• Create the methods defined by the interface.
• The general form
class classname [extends superclass] [implements interface [,interface...]] {
// class-body
}
• Example
class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
}
Example
class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
void nonIfaceMeth() {
System.out.println("Classes that implement interfaces " +
"may also define other members, too.");
}
}
Default Interface Methods
• Default methods enable to add new functionality to the interfaces of
the libraries and ensure binary compatibility with code written for
older versions of those interfaces.
• Methods which are defined inside the interface and tagged with
default are known as default methods.
• These methods are non-abstract methods.
interface Sayable{
// Default method
default void say(){
System.out.println("Hello, this is default method");
}
// Abstract method
void sayMore(String msg);
}
public class DefaultMethods implements Sayable{
public void sayMore(String msg){ // implementing abstract method
System.out.println(msg);
}
public static void main(String[] args) {
DefaultMethods dm = new DefaultMethods();
dm.say(); // calling default method
dm.sayMore("Work is worship"); // calling abstract method
}
}
Use static methods in an
Interface
• This makes it easier to organize helper methods in the libraries.
• Keep static methods specific to an interface in the same interface
rather than in a separate class.
• Static methods are used to define utility methods
interface Sayable{
// default method
default void say(){
System.out.println("Hello, this is default method");
}
// Abstract method
void sayMore(String msg);
// static method
static void sayLouder(String msg){
System.out.println(msg);
}
}
public class DefaultMethods implements Sayable{
public void sayMore(String msg){ // implementing abstract method
System.out.println(msg);
}
public static void main(String[] args) {
DefaultMethods dm = new DefaultMethods();
dm.say(); // calling default method
dm.sayMore("Work is worship"); // calling abstract method
Sayable.sayLouder("Helloooo..."); // calling static method
}
}

You might also like