Module-1 Part-2
Module-1 Part-2
MODULE-1 PART-2
Java source file structure:: Java source file structure, Class Modifiers, Member modifiers, Interfaces.
A java Program can contain any no. Of classes but at most one class can be declared as public. "If there is a public
class the name of the Program and name of the public class must be matched otherwise we will get compile time
error".
If there is no public class then any name we gives for java source file.
Example:
Case 1:
If there is no public class then we can use any name for java source file there are no restrictions.
Example:
A.java
B.java
C.java
Ashok.java
case 2:
If class B declared as public then the name of the Program should be B.java otherwise we will get compile time error
saying "class B is public, should be declared in a file named B.java".
Case 3:
If both B and C classes are declared as public and name of the file is B.java then we will get compile time error
saying "class C is public, should be declared in a file named C.java".
It is highly recommended to take only one class for source file and name of the Program (file) must be same as
class name. This approach improves readability and understandability of the code.
Example:
class A
{
public static void main(String args[]){
System.out.println("A class main method is executed");
}
}
class B
{
public static void main(String args[]){
System.out.println("B class main method is executed");
}
}
class C
{
public static void main(String args[]){
System.out.println("C class main method is executed");
}
}
class D
{
}
Output:
D:\Java>java A
A class main method is executed
D:\Java>java B
B class main method is executed
D:\Java>java C
We can compile a java Program but not java class in that Program for every class one dot class file will be created.
We can run a java class but not java source file whenever we are trying to run a class the corresponding class
main method will be executed.
If the class won't contain main method then we will get runtime exception saying "NoSuchMethodError: main".
If we are trying to execute a java class and if the corresponding .class file is not available then we will get runtime
execution saying "NoClassDefFoundError: Ashok".
Import statement:
class Test{
public static void main(String args[]){
ArrayList l=new ArrayList();
}
}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:3: cannot find symbol
symbol : class ArrayList
location: class Test
We can resolve this problem by using fully qualified name "java.util.ArrayList l=new java.util.ArrayList();". But
problem with using fully qualified name every time is it increases length of the code and reduces readability.
We can resolve this problem by using import statements.
Example:
import java.util.ArrayList;
class Test{
public static void main(String args[]){
ArrayList l=new ArrayList();
}
}
Output:
D:\Java>javac Test.java
Hence whenever we are using import statement it is not require to use fully qualified names we can use short names
directly. This approach decreases length of the code and improves readability.
This type of import is highly recommended to use because it improves readability of the code.
Best suitable for Hi-Tech city where readability is important.
Case 2:
Which of the following import statements are meaningful ?
Case 3:
The code compiles fine even though we are not using import statements because we used fully qualified name.
Whenever we are using fully qualified name it is not required to use import statement. Similarly whenever we are
using import statements it is not require to use fully qualified name.
Case 4:
Example:
import java.util.*;
import java.sql.*;
class Test
{
public static void main(String args[])
{
Date d=new Date();
}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:7: reference to Date is ambiguous,
both class java.sql.Date in java.sql and class java.util.Date in java.util match
Note: Even in the List case also we may get the same ambiguity problem because it is available in
both util and awt packages.
Case 5:
While resolving class names compiler will always gives the importance in the following order.
Example:
import java.util.Date;
import java.sql.*;
class Test
{
public static void main(String args[]){
Date d=new Date();
}}
The code compiles fine and in this case util package Date will be considered.
Case 6:
Whenever we are importing a package all classes and interfaces present in that package are by default available but not
sub package classes.
Example:
To use pattern class in our Program directly which import statement is required ?
Case7:
In any java Program the following 2 packages are not require to import because these are available by default to every
java Program.
1. java.lang package
2. default package(current working directory)
Case 8:
"Import statement is totally compile time concept" if more no of imports are there then more will be the compile time
but there is "no change in execution time".
#include import
At compile time only compiler copy the At runtime JVM will execute the
code from standard library and placed in corresponding standard library and use it's
current program. result in current program.
In the case of C language #include all the header files will be loaded at the time of include statement hence it
follows static loading.
But in java import statement no ".class" will be loaded at the time of import statements in the next lines of the
code whenever we are using a particular class then only corresponding ".class" file will be loaded. Hence it
follows "dynamic loading" or "load-on -demand" or "load-on-fly".
1. For-Each
2. Var-arg
3. Queue
4. Generics
5. Auto boxing and Auto unboxing
6. Co-varient return types
7. Annotations
8. Enum
9. Static import
10. String builder
Static import:
This concept introduced in 1.5 versions. According to sun static import improves readability of the code but according to
worldwide Programming exports (like us) static imports creates confusion and reduces readability of the code. Hence if
there is no specific requirement never recommended to use a static import.
Usually we can access static members by using class name but whenever we are using static import it is not require to
use class name we can access directly.
class Test
{
public static void main(String args[]){
System.out.println(Math.sqrt(4));
System.out.println(Math.max(10,20));
System.out.println(Math.random());
}}
Output:
D:\Java>javac Test.java
D:\Java>java Test
2.0
20
0.841306154315576
Example 3:
Example 4:
Note: Two packages contain a class or interface with the same is very rare hence ambiguity problem is very rare in
normal import.
But 2 classes or interfaces can contain a method or variable with the same name is very common hence ambiguity
problem is also very common in static import.
While resolving static members compiler will give the precedence in the following order.
Example:
If we comet line one then we will get Integer class MAX_VALUE 2147483647.
If we comet lines one and two then Byte class MAX_VALUE will be considered 127.
Diagram:
Usage of static import reduces readability and creates confusion hence if there is no specific requirement never
recommended to use static import.
We can use normal imports to import classes and interfaces of a package. whenever we are using normal import
we can access class and interfaces directly by their short name it is not require to use fully qualified names.
We can use static import to import static members of a particular class. whenever we are using static import it is
not require to use class name we can access static members directly.
Package statement:
It is an encapsulation mechanism to group related classes and interfaces into a single module.
Example:
Example:
package com.durgajobs.itjobs;
class HydJobs
{
public static void main(String args[]){
System.out.println("package demo");
}
}
Javac HydJobs.java generated class file will be placed in current working directory.
Diagram:
Javac -d . HydJobs.java
-d means destination to place generated class files "." means current working directory.
Generated class file will be placed into corresponding package structure.
Diagram:
If the specified package structure is not already available then this command itself will create the required
package structure.
As the destination we can use any valid directory.
If the specified destination is not available then we will get compile time error.
Example:
D:\Java>javac -d c: HydJobs.java
Diagram:
If the specified destination is not available then we will get compile time error.
Example:
D:\Java>javac -d z: HydJobs.java
If Z: is not available then we will get compile time error.
D:\Java>java com.durgajobs.itjobs.HydJobs
Conclusion 1:
In any java Program there should be at most one package statement that is if we are taking more than one package
statement we will get compile time error.
Example:
package pack1;
package pack2;
class A
{
}
Output:
Compile time error.
D:\Java>javac A.java
A.java:2: class, interface, or enum expected
package pack2;
Conclusion 2:
In any java Program the 1st non comment statement should be package statement [if it is available] otherwise we will
get compile time error.
Example:
import java.util.*;
package pack1;
class A
{
}
Output:
Compile time error.
D:\Java>javac A.java
A.java:2: class, interface, or enum expected
package pack1;
Class Modifiers
Whenever we are writing our own classes compulsory we have to provide some information about our class to the jvm.
Like
1. Public
2. Default
3. Final
4. Abstract
5. Strictfp
If we are using any other modifier we will get compile time error.
Example:
But For the inner classes the following modifiers are allowed.
Diagram:
In old languages 'C' (or) 'C++' public, private, protected, default are considered as access specifiers and all the
remaining are considered as access modifiers.
But in java there is no such type of division all are considered as access modifiers.
Public Classes:
If a class declared as public then we can access that class from anywhere. With in the package or outside the package.
Example:
Program1:
package pack1;
public class Test
{
public void methodOne(){
System.out.println("test class methodone is executed");
}}
Compile the above Program:
D:\Java>javac -d . Test.java
Program2:
package pack2;
import pack1.Test;
class Test1
{
public static void main(String args[]){
Test t=new Test();
t.methodOne();
}}
OUTPUT:
D:\Java>javac -d . Test1.java
D:\Java>java pack2.Test1
Test class methodone is executed.
If class Test is not public then while compiling Test1 class we will get compile time error saying pack1.Test is not public in
pack1; cannot be accessed from outside package.
Default Classes:
If a class declared as the default then we can access that class only within the current package hence default access is
also known as "package level access".
Example:
Program 1:
package pack1;
class Test
{
public void methodOne(){
System.out.println("test class methodone is executed");
}}
Program 2:
package pack1;
import pack1.Test;
class Test1
{
public static void main(String args[]){
Test t=new Test();
t.methodOne();
}}
OUTPUT:
D:\Java>javac -d . Test.java
D:\Java>javac -d . Test1.java
D:\Java>java pack1.Test1
Test class methodone is executed
Final Modifier:
Final Methods:
Example:
Program 1:
class Parent
{
public void property(){
System.out.println("cash+gold+land");
}
public final void marriage(){
System.out.println("subbalakshmi");
}}
Program 2:
System.out.println("Thamanna");
}}
OUTPUT:
Compile time error.
D:\Java>javac Parent.java
D:\Java>javac child.java
child.java:3: marriage() in child cannot override marriage() in Parent;
overridden method is final
public void marriage(){
Final Class:
If a class declared as the final then we cann't creates the child class that is inheritance concept is not applicable for final
classes.
Example:
Program 1:
final class Parent
{
}
Program 2:
class child extends Parent
{
}
OUTPUT:
Compile time error.
D:\Java>javac Parent.java
D:\Java>javac child.java
child.java:1: cannot inherit from final Parent
class child extends Parent
Note: Every method present inside a final class is always final by default whether we are declaring or not. But every
variable present inside a final class need not be final.
Example:
Abstract Modifier:
Abstract is the modifier applicable only for methods and classes but not for variables.
Abstract Methods:
Even though we don't have implementation still we can declare a method with abstract modifier.
That is abstract methods have only declaration but not implementation.
Hence abstract method declaration should compulsory ends with semicolon.
Example:
Child classes are responsible to provide implementation for parent class abstract methods.
Example:
Program:
The main advantage of abstract methods is , by declaring abstract method in parent class we can provide guide
lines to the child class such that which methods they should compulsory implement.
Abstract method never talks about implementation whereas if any modifier talks about implementation then the
modifier will be enemy to abstract and that is always illegal combination for methods.
Diagram:
Abstract class:
For any java class if we are not allow to create an object such type of class we have to declare with abstract modifier that
is for abstract class instantiation is not possible.
Example:
abstract class Test
{
public static void main(String args[]){
Test t=new Test();
}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:4: Test is abstract; cannot be instantiated
Test t=new Test();
If a class contain at least on abstract method then compulsory the corresponding class should be declare with
abstract modifier. Because implementation is not complete and hence we can't create object of that class.
Even though class doesn't contain any abstract methods still we can declare the class as abstract that is an
abstract class can contain zero no of abstract methods also.
Example1: HttpServlet class is abstract but it doesn't contain any abstract method.
Example2: Every adapter class is abstract but it doesn't contain any abstract method.
Example1:
class Parent
{
public void methodOne();
}
Output:
Compile time error.
D:\Java>javac Parent.java
Parent.java:3: missing method body, or declare abstract
public void methodOne();
Example2:
class Parent
{
public abstract void methodOne(){}
}
Output:
Compile time error.
Parent.java:3: abstract methods cannot have a body
public abstract void methodOne(){}
Example3:
class Parent
{
public abstract void methodOne();
}
Output:
Compile time error.
D:\Java>javac Parent.java
Parent.java:1: Parent is not abstract and does not
override abstract method methodOne() in Parent
class Parent
If a class extends any abstract class then compulsory we should provide implementation for every abstract method of
the parent class otherwise we have to declare child class as abstract.
Example:
abstract class Parent
{
public abstract void methodOne();
If we declare class child as abstract then the code compiles fine but child of child is responsible to provide
implementation for methodTwo().
For abstract methods compulsory we should override in the child class to provide implementation. Whereas for
final methods we can't override hence abstract final combination is illegal for methods.
For abstract classes we should compulsory create child class to provide implementation whereas for final class we
can't create child class. Hence final abstract combination is illegal for classes.
Final class cannot contain abstract methods whereas abstract class can contain final method.
Example:
Note:
Usage of abstract methods, abstract classes and interfaces is always good Programming practice.
Strictfp:
strictfp is the modifier applicable for methods and classes but not for variables.
Strictfp modifier introduced in 1.2 versions.
Usually the result of floating point of arithmetic is varing from platform to platform , to overcome this problem
we should use strictfp modifier.
If a method declare as the Strictfp then all the floating point calculations in that method has to follow IEEE754
standard, So that we will get platform independent results.
Example:
If a class declares as the Strictfp then every concrete method(which has body) of that class has to follow IEEE754
standard for floating point arithmetic, so we will get platform independent results.
Strictfp method talks about implementation where as abstract method never talks about implementation hence
abstract, strictfp combination is illegal for methods.
But we can declare a class with abstract and strictfp modifier simultaneously. That is abstract strictfp combination
is legal for classes but illegal for methods.
Example:
Member modifiers:
Public members:
If a member declared as the public then we can access that member from anywhere "but the corresponding class must
be visible" hence before checking member visibility we have to check class visibility.
Example:
Program 1:
package pack1;
class A
{
public void methodOne(){
System.out.println("a class method");
}}
D:\Java>javac -d . A.java
Program 2:
package pack2;
import pack1.A;
class B
{
public static void main(String args[]){
A a=new A();
a.methodOne();
}}
Output:
Compile time error.
D:\Java>javac -d . B.java
B.java:2: pack1.A is not public in pack1;
cannot be accessed from outside package
import pack1.A;
In the above Program even though methodOne() method is public we can't access from class B because the
corresponding class A is not public that is both classes and methods are public then only we can access.
Default member:
If a member declared as the default then we can access that member only within the current package hence default
member is also known as package level access.
Example 1:
Program 1:
package pack1;
class A
{
void methodOne(){
System.out.println("methodOne is executed");
}}
Program 2:
package pack1;
import pack1.A;
class B
{
Program 1:
package pack1;
class A
{
void methodOne(){
System.out.println("methodOne is executed");
}}
Program 2:
package pack2;
import pack1.A;
class B
{
public static void main(String args[]){
A a=new A();
a.methodOne();
}}
Output:
Compile time error.
D:\Java>javac -d . A.java
D:\Java>javac -d . B.java
B.java:2: pack1.A is not public in pack1; cannot be accessed from outside package
import pack1.A;
Private members:
If a member declared as the private then we can access that member only with in the current class.
Private methods are not visible in child classes where as abstract methods should be visible in child classes to
provide implementation hence private, abstract combination is illegal for methods.
Protected members:
If a member declared as the protected then we can access that member within the current package anywhere
but outside package only in child classes.
Protected=default+kids.
We can access protected members within the current package anywhere either by child reference or by parent
reference
But from outside package we can access protected members only in child classes and should be by child
reference only that is we can't use parent reference to call protected members from outside package.
Example:
Program 1:
package pack1;
public class A
{
protected void methodOne(){
System.out.println("methodOne is executed");
}}
Program 2:
package pack1;
class B extends A
{
public static void main(String args[]){
A a=new A();
a.methodOne();
B b=new B();
b.methodOne();
A a1=new B();
a1.methodOne();
}}
Output:
D:\Java>javac -d . A.java
D:\Java>javac -d . B.java
D:\Java>java pack1.B
methodOne is executed
methodOne is executed
methodOne is executed
Example 2:
Private<default<protected<public
Recommended modifier for variables is private where as re commended modifi er for method s is public.
Final variables:
If the value of a variable is varied from object to obje ct such type of varia bles are call ed instance variables.
For every object a separate copy of inst ance variable s will be created.
DIAGRAM:
For the instance variables it is not required to perform initialization explicitly jvm will always provide default values.
Example:
class Test
{
int i;
public static void main(String args[]){
Test t=new Test();
System.out.println(t.i);
}}
Output:
D:\Java>javac Test.java
D:\Java>java Test
0
If the instance variable declared as the final compulsory we should perform initialization explicitly and JVM won't provide
any default values.
whether we are using or not otherwise we will get compile time error.
Example:
Program 1:
class Test
{
int i;
}
Output:
D:\Java>javac Test.java
D:\Java>
Program 2:
class Test
{
final int i;
}
Output:
For the final instance variables we should perform initialization before constructor completion. That is the following are
various possible places for this.
Example:
class Test
{
final int i=10;
}
Output:
D:\Java>javac Test.java
D:\Java>
Example:
class Test
{
final int i;
{
i=10;
}}
Output:
D:\Java>javac Test.java
D:\Java>
3) Inside constructor:
Example:
class Test
{
final int i;
Test()
{
i=10;
}}
Output:
D:\Java>javac Test.java
D:\Java>
If we are performing initialization anywhere else we will get compile time error.
Example:
class Test
{
final int i;
public void methodOne(){
i=10;
}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: cannot assign a value to final variable i
i=10;
If the value of a variable is not varied from object to object such type of variables is not recommended to declare
as the instance variables. We have to declare those variables at class level by using static modifier.
In the case of instance variables for every object a seperate copy will be created but in the case of static variables
a single copy will be created at class level and shared by every object of that class.
For the static variables it is not required to perform initialization explicitly jvm will always provide default values.
Example:
class Test
{
static int i;
public static void main(String args[]){
System.out.println("value of i is :"+i);
}}
Output:
D:\Java>javac Test.java
D:\Java>java Test
Value of i is: 0
If the static variable declare as final then compulsory we should perform initialization explicitly whether we are using or
not otherwise we will get compile time error.(The JVM won't provide any default values)
Example:
Rule:
For the final static variables we should perform initialization before class loading completion otherwise we will get
compile time error. That is the following are possible places.
Example:
class Test
{
final static int i=10;
}
Output:
D:\Java>javac Test.java
D:\Java>
Example:
class Test
{
final static int i;
static
{
i=10;
}}
Output:
Compile successfully.
If we are performing initialization anywhere else we will get compile time error.
Example:
class Test
{
final static int i;
public static void main(String args[]){
i=10;
}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: cannot assign a value to final variable i
i=10;
To meet temporary requirement of the Programmer sometime we can declare the variable inside a method or
block or constructor such type of variables are called local variables.
For the local variables jvm won't provide any default value compulsory we should perform initialization explicitly
before using that variable.
Example:
class Test
{
public static void main(String args[]){
int i;
System.out.println("hello");
}}
Output:
D:\Java>javac Test.java
D:\Java>java Test
Hello
Example:
class Test
{
public static void main(String args[]){
int i;
System.out.println(i);
}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: variable i might not have been initialized
System.out.println(i);
Even though local variable declared as the final before using only we should perform initialization.
Example:
class Test
{
public static void main(String args[]){
final int i;
System.out.println("hello");
}}
Output:
D:\Java>javac Test.java
D:\Java>java Test
hello
Note: The only applicable modifier for local variables is final if we are using any other modifier we will get compile time
error.
Example:
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: illegal start of expression
private int x=10;
Formal parameters:
The formal parameters of a method are simply acts as local variables of that method hence it is possible to
declare formal parameters as final.
If we declare formal parameters as final then we can't change its value within the method.
Example:
For instance and static variables JVM will provide default values but if instance and static declared as final JVM
won't provide default value compulsory we should perform initialization whether we are using or not .
For the local variables JVM won't provide any default values we have to perform explicitly before using that
variables , this rule is same whether local variable final or not.
Static modifier:
Example:
Output:
D:\Java>javac Test.java
D:\Java>java Test
888. ....20
Instance variables can be accessed only from instance area directly and we can't access from static area directly.
But static variables can be accessed from both instance and static areas directly.
1) Int x=10;
Which are the following declarations are allow within the same class simultaneously ?
a) 1 and 3
Example:
class Test
{
int x=10;
public void methodOne(){
System.out.println(x);
}}
Output:
Compile successfully.
b) 1 and 4
Example:
class Test
{
int x=10;
public static void methodOne(){
System.out.println(x);
}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: non-static variable x cannot be referenced from a static context
System.out.println(x);
c) 2 and 3
Example:
class Test
{
static int x=10;
public void methodOne(){
System.out.println(x);
}}
Output:
Compile successfully.
d) 2 and 4
Example:
class Test
{
static int x=10;
public static void methodOne(){
System.out.println(x);
}}
Output:
Compile successfully.
e) 1 and 2
Example:
class Test
{
int x=10;
static int x=10;
}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:4: x is already defined in Test
static int x=10;
f) 3 and 4
Example:
class Test{
public void methodOne(){
System.out.println(x);
}
public static void methodOne(){
System.out.println(x);
}}
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: methodOne() is already defined in Test
public static void methodOne(){
For static methods implementation should be available but for abstract methods implementation is not available hence
static abstract combination is illegal for methods.
case 1:
Overloading concept is applicable for static method including main method also.But JVM will always call String[]
args main method .
The other overloaded method we have to call explicitly then it will be executed just like a normal method call .
Example:
Output :
String() method is called
case 2:
Inheritance concept is applicable for static methods including main() method hence while executing child class, if the
child doesn't contain main() method then the parent class main method will be executed.
Example:
class Parent{
public static void main(String args[]){
System.out.println("parent main() method called");
}
}
class child extends Parent{
}
Output:
Example:
Output:
It seems to be overriding concept is applicable for static methods but it is not overriding it is method hiding.
Native modifier:
Native is a modifier applicable only for methods but not for variables and classes.
The methods which are implemented in non java are called native methods or foreign methods.
Pseudo code:
For native methods implementation is already available and we are not responsible to provide implementation
hence native method declaration should compulsory ends with semicolon.
o Public native void methodOne() --- invalid
o Public native void methodOne(); -- valid
For native methods implementation is already available where as for abstract methods implementation should
not be available child class is responsible to provide that, hence abstract native combination is illegal for
methods.
We can't declare a native method as strictfp because there is no guaranty whether the old language supports
IEEE754 standard or not. That is native strictfp combination is illegal for methods.
For native methods inheritance, overriding and overloading concepts are applicable.
The main advantage of native keyword is performence will be improves.
The main disadvantage of native keyword is usage of native keyword in java breaks platform independent
nature of java language.
Synchronized:
1. Synchronized is the modifier applicable for methods and blocks but not for variables and classes.
2. If a method or block declared with synchronized keyword then at a time only one thread is allow to execute that
method or block on the given object.
3. The main advantage of synchronized keyword is we can resolve data inconsistency problems.
4. But the main disadvantage is it increases waiting time of the threads and effects performance of the system.
Hence if there is no specific requirement never recommended to use synchronized keyword.
For syncronized methods compulsory implementation should be available , but for abstract methods implementation
won't be available , Hence abstract - syncronized combination is illegal for methods.
Transient modifier:
1. Transient is the modifier applicable only for variables but not for methods and classes.
2. At the time of serialization if we don't want to serialize the value of a particular variable to meet the security
constraints then we should declare that variable with transient modifier.
3. At the time of serialization jvm ignores the original value of the transient variable and save default value that is
transient means "not to serialize".
4. Static variables are not part of object state hence serialization concept is not applicable for static variables duo to
this declaring a static variable as transient there is no use.
5. Final variables will be participated into serialization directly by their values due to this declaring a final variable as
transient there is no impact.
Volatile modifier:
1. Volatile is the modifier applicable only for variables but not for classes and methods.
2. If the value of variable keeps on changing such type of variables we have to declare with volatile modifier.
3. If a variable declared as volatile then for every thread a separate local copy will be created by the jvm, all
intermediate modifications performed by the thread will takes place in the local copy instead of master copy.
4. Once the value got finalized before terminating the thread that final value will be updated in master copy.
5. The main advantage of volatile modifier is we can resolve data inconsistency problems, but creating and
maintaining a separate copy for every thread increases complexity of the Programming and effects performance
of the system. Hence if there is no specific requirement never recommended to use volatile modifier and it's
almost outdated.
6. Volatile means the value keep on changing where as final means the value never changes hence final volatile
combination is illegal for variables.
Summary of modifier:
Inner Outer
Modifier Methods Variables Blocks Interfaces Enum Constructors
Classes Classes
Public
Private
Protected
Default
Final
Abstract
Strictfp
Static
Synchronized
Native
Transient
Volatile
Note :
1. The modifiers which are applicable for inner classes but not for outer classes are private, protected, static.
2. The modifiers which are applicable only for methods native.
3. The modifiers which are applicable only for variables transient and volatile.
4. The modifiers which are applicable for constructor public, private, protected, default.
5. The only applicable modifier for local variables is final.
6. The modifiers which are applicable for classes but not for enums are final , abstract.
7. The modifiers which are applicable for classes but not for interface are final.
Interfaces:
Diagram:
Example2: Sun people define Servlet API to develop web applications web server vendor is responsible to provide
implementation.
Diagram:
Def2: From the client point of view an interface define the set of services what is expecting. From the service provider
point of view an interface defines the set of services what is offering. Hence an interface is considered as a contract
between client and service provider.
Example: ATM GUI screen describes the set of services what bank people offering, at the same time the same GUI screen
the set of services what customer is expecting hence this GUI screen acts as a contract between bank and customer.
Def3: Inside interface every method is always abstract whether we are declaring or not hence interface is considered as
100% pure abstract class.
Summery def: Any service requirement specification (SRS) or any contract between client and service provider or 100%
pure abstract classes is considered as an interface.
Note1:
Whenever we are implementing an interface compulsory for every method of that interface we should provide
implementation otherwise we have to declare class as abstract in that case child class is responsible to provide
implementation for remaining methods.
Note2:
Whenever we are implementing an interface method compulsory it should be declared as public otherwise we will get
compile time error.
Example:
interface Interf
{
void methodOne();
void methodTwo();
}
Extends vs implements:
Example:
class One{
public void methodOne(){
}
}
class Two extends One{
}
Example:
interface One{
public void methodOne();
}
interface Two{
public void methodTwo();
}
class Three implements One,Two{
public void methodOne(){
}
public void methodTwo(){
}
}
A class can extend a class and can implement any no. Of interfaces simultaneously.
interface One{
void methodOne();
}
class Two
{
public void methodTwo(){
}
}
class Three extends Two implements One{
public void methodOne(){
}
}
Example:
interface One{
void methodOne();
}
interface Two{
void methodTwo();
}
interface Three extends One,Two
{
}
Which of the following is true?
Ans: 6
Consider the expression X extends Y for which of the possibility of X and Y this expression is true?
Ans: 3
X extends Y, Z ?
X, Y, Z should be interfaces.
X extends Y implements Z ?
X, Y should be classes.
Z should be interface.
X implements Y, Z ?
X should be class.
Y, Z should be interfaces.
X implements Y extend Z ?
Example:
interface One{
}
class Two {
}
class Three implements One extends Two{
}
Output:
Compile time error.
D:\Java>javac Three.java
Three.java:5: '{' expected
class Three implements One extends Two{
Interface methods:
Every method present inside interface is always public and abstract whether we are declaring or not. Hence inside
interface the following method declarations are equal.
void methodOne();
public Void methodOne();
abstract Void methodOne(); Equal
public abstract Void methodOne();
As every interface method is always public and abstract we can't use the following modifiers for interface methods.
Private, protected, final, static, synchronized, native, strictfp.
Ans: 5
Interface variables:
Example:
interface interf
{
int x=10;
}
int x=10;
public int x=10;
static int x=10;
final int x=10; Equal
public static int x=10;
public final int x=10;
static final int x=10;
public static final int x=10;
As every interface variable by default public static final we can't declare with the following modifiers.
o Private
o Protected
o Transient
o Volatile
For the interface variables compulsory we should perform initialization at the time of declaration only otherwise
we will get compile time error.
Example:
interface Interf
{
int x;
}
Output:
Compile time error.
D:\Java>javac Interf.java
Interf.java:3: = expected
int x;
Which of the following declarations are valid inside interface ?
1. int x;
2. private int x=10;
3. public volatile int x=10;
4. public transient int x=10;
5. public static final int x=10;
Ans: 5
Interface variables can be access from implementation class but cannot be modified.
Example:
interface Interf
{
int x=10;
}
Example 1:
Example 2:
class Test implements Interf
{
public static void main(String args[]){
int x=20;
//here we declaring the variable x.
System.out.println(x);
}
}
Output:
D:\Java>javac Test.java
D:\Java>java Test
20
Case 1:
If two interfaces contain a method with same signature and same return type in the implementation class only one
method implementation is enough.
Example 1:
interface Left
{
public void methodOne();
}
Example 2:
interface Right
{
public void methodOne();
}
Example 3:
class Test implements Left,Right
{
public void methodOne()
{
}}
Output:
D:\Java>javac Left.java
D:\Java>javac Right.java
D:\Java>javac Test.java
Case 2:
if two interfaces contain a method with same name but different arguments in the implementation class we have to
provide implementation for both methods and these methods acts as a overloaded methods
Example 1:
interface Left
{
public void methodOne();
}
Example 2:
interface Right
{
public void methodOne(int i);
}
Example 3:
class Test implements Left,Right
{
public void methodOne()
{
}
public void methodOne(int i)
{
}}
Output:
D:\Java>javac Left.java
D:\Java>javac Right.java
D:\Java>javac Test.java
Case 3:
If two interfaces contain a method with same signature but different return types then it is not possible to implement
both interfaces simultaneously.
Example 1:
interface Left
{
public void methodOne();
}
Example 2:
interface Right
{
public int methodOne(int i);
}
We can't write any java class that implements both interfaces simultaneously.
Two interfaces can contain a variable with the same name and there may be a chance variable naming conflicts but we
can resolve variable naming conflicts by using interface names.
Example 1:
interface Left
{
int x=888;
}
Example 2:
interface Right
{
int x=999;
}
Example 3:
class Test implements Left,Right
{
public static void main(String args[]){
//System.out.println(x);
System.out.println(Left.x);
System.out.println(Right.x);
}
}
Output:
D:\Java>javac Left.java
D:\Java>javac Right.java
D:\Java>javac Test.java
D:\Java>java Test
888
999
Marker interface:
If an interface doesn't contain any methods and by implementing that interface if our objects will get some ability such
type of interfaces are called Marker interface (or) Tag interface (or) Ability interface.
Example:
Serializable
Cloneable
RandomAccess These are marked for some ability
SingleThreadModel
.
.
.
.
Example 1:
By implementing Serilaizable interface we can send that object across the network and we can save state of an object
into a file.
Example 2:
By implementing SingleThreadModel interface Servlet can process only one client request at a time so that we can get
"Thread Safety".
Example 3:
By implementing Cloneable interface our object is in a position to provide exactly duplicate cloned object.
Without having any methods in marker interface how objects will get ability ?
Internally JVM is responsible to provide required ability.
Adapter class:
Adapter class is a simple java class that implements an interface only with empty implementation for every
method.
If we implement an interface directly for each and every method compulsory we should provide implementation
whether it is required or not. This approach increases length of the code and reduces readability.
Example 1:
interface X{
void m1();
void m2();
void m3();
void m4();
//.
//.
//.
//.
void m5();
}
Example 2:
Example 1:
abstract class AdapterX implements X{
public void m1(){}
public void m2(){}
public void m3(){}
public void m4(){}
//.
//.
//.
public void m1000(){}
}
Example 2:
Example:
Note : marker interface and Adapter class are big utilities to the programmer to simplify programming.
What is the difference between interface, abstract class and concrete class?
When we should go for interface, abstract class and concrete class?
If we don't know anything about implementation just we have requirement specification then we should go for
interface.
If we are talking about implementation but not completely (partial implementation) then we should go for
abstract class.
If we are talking about implementation completely and ready to provide service then we should go for concrete
class.
Example:
Every interface variable is always public static Every abstract class variable need not be
final whether we are declaring or not. public static final.
Every interface variable is always public static There are no restrictions on abstract class
final we can't declare with the following variable modifiers.
Inside interface we can't take static and Inside abstract class we can take both
instance blocks. static and instance blocks.
We can't create object for abstract class but abstract class can contain constructor what is the need ?
abstract class constructor will be executed when ever we are creating child class object to perform initialization of child
object.
Example:
class Parent{
Parent()
{
System.out.println(this.hashCode());
}
}
class child extends Parent{
child(){
System.out.println(this.hashCode());
}
}
class Test{
public static void main(String args[]){
child c=new child();
System.out.println(c.hashCode());
}
}
Note : We can't create object for abstract class either directly or indirectly.
Every method present inside interface is abstract but in abstract class also we can take only abstract methods then
what is the need of interface concept ?
We can replace interface concept with abstract class. But it is not a good programming practice. We are misusing the roll
of abstract class. It may create performence problems also.
Why abstract class can contain constructor where as interface doesn't contain constructor ?
The main purpose of constructor is to perform initialization of an object i.e., provide values for the instance variables,
Inside interface every variable is always static and there is no chance of existing instance variables. Hence constructor is
not required for interface.
But abstract class can contains instance variable which are required for the child object to perform initialization for those
instance variables constructor is required in the case of abstract class.