Declaration and Access ModifiersAgenda
Java source file structure:
![]() Case 1: If there is no public class then we can use any name for java source file there are no restrictions. 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:
![]()
Import statement:
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. Case 1: Types of Import Statements:There are 2 types of import statements. 1) Explicit class import2) Implicit class import. Explicit class import:Example: Import java.util.ArrayList
Implicit class import:Example: import java.util.*;
Which of the following import statements are meaningful ? ![]() Case 3: consider the following code.
Example: Date d=new Date(); 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.
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 "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". Difference between C language #include and java language import ?
1.5 versions new features :
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. Without static import: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 With static import:import static java.lang.Math.sqrt; import static java.lang.Math.*; class Test { public static void main(String args[]){ System.out.println(sqrt(4)); System.out.println(max(10,20)); System.out.println(random()); }} Output: D:\Java>javac Test.java D:\Java>java Test 2.0 20 0.4302853847363891 Explain about System.out.println statement ?Example 1 and Example 2:![]() ![]() Example 3: import static java.lang.System.out; class Test { public static void main(String args[]){ out.println("hello"); out.println("hi"); }} Output: D:\Java>javac Test.java D:\Java>java Test hello hiExample 4: import static java.lang.Integer.*; import static java.lang.Byte.*; class Test { public static void main(String args[]){ System.out.println(MAX_VALUE); }} Output: Compile time error. D:\Java>javac Test.java Test.java:6: reference to MAX_VALUE is ambiguous, both variable MAX_VALUE in java.lang.Integer and variable MAX_VALUE in java.lang.Byte match System.out.println(MAX_VALUE); 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.
![]()
![]() Diagram: ![]() Usage of static import reduces readability and creates confusion hence if there is no specific requirement never recommended to use static import. What is the difference between general import and static import ?
Package statement:It is an encapsulation mechanism to group related classes and interfaces into a single module. The main objectives of packages are:
![]() How to compile package Program: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:![]()
![]()
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 How to execute package Program:D:\Java>java com.durgajobs.itjobs.HydJobsAt the time of execution compulsory we should provide fully qualified name. 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; Java source file structure:![]() All the following are valid java Programs. ![]() Note: An empty source file is a valid java Program. Class ModifiersWhenever we are writing our own classes compulsory we have to provide some information about our class to the jvm. Like
We can specify this information by using the corresponding modifiers. The only applicable modifiers for Top Level classes are:
If we are using any other modifier we will get compile time error. Example:private class Test { public static void main(String args[]){ int i=0; for(int j=0;j<3;j++) { i=i+j; } System.out.println(i); }} OUTPUT: Compile time error. D:\Java>javac Test.java Test.java:1: modifier private not allowed here private class Test But For the inner classes the following modifiers are allowed. Diagram:![]() What is the difference between access specifier and access modifier ?
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.javaProgram2: 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 is the modifier applicable for classes, methods and variables. Final Methods:
Program 1: class Parent { public void property(){ System.out.println("cash+gold+land"); } public final void marriage(){ System.out.println("subbalakshmi"); }}Program 2: class child extends Parent { public void marriage(){ 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:final class parent { static int x=10; static { x=999; }} The main advantage of final keyword is we can achieve security. 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. ![]() Child classes are responsible to provide implementation for parent class abstract methods. Example:Program: ![]()
The following are the various illegal combinations for methods.Diagram:![]() All the 6 combinations are illegal. 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(); What is the difference between abstract class and abstract method ?
Example1: HttpServlet class is abstract but it doesn't contain any abstract method. 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(); public abstract void methodTwo(); } class child extends Parent { public void methodOne(){} } Output: Compile time error. D:\Java>javac Parent.java Parent.java:6: child is not abstract and does not override abstract method methodTwo() in Parent class child extends Parent If we declare class child as abstract then the code compiles fine but child of child is responsible to provide implementation for methodTwo(). What is the difference between final and abstract ?
![]() Note: Usage of abstract methods, abstract classes and interfaces is always good Programming practice. Strictfp:
![]() 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. What is the difference between abstract and strictfp ?
![]() 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.javaProgram 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 { public static void main(String args[]){ A a=new A(); a.methodOne(); }} Output: D:\Java>javac -d . A.java D:\Java>javac -d . B.java D:\Java>java pack1.B methodOne is executedExample 2: 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:
Protected members:
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 executedExample 2: ![]() Compression of private, default, protected and public:
Recommended modifier for variables is private where as recommended modifier for methods is public. Final variables:Final instance variables:
![]() 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. Program 1: class Test { int i; } Output: D:\Java>javac Test.java D:\Java>Program 2: class Test { final int i; } Output: Compile time error. D:\Java>javac Test.java Test.java:1: variable i might not have been initialized class TestRule: For the final instance variables we should perform initialization before constructor completion. That is the following are various possible places for this. 1) At the time of declaration:Example:class Test { final int i=10; } Output: D:\Java>javac Test.java D:\Java> 2) Inside instance block: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; Final static variables:
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. 1) At the time of declaration:Example:class Test { final static int i=10; } Output: D:\Java>javac Test.java D:\Java> 2) Inside static block: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; Final local variables:
class Test { public static void main(String args[]){ int i; System.out.println("hello"); }} Output: D:\Java>javac Test.java D:\Java>java Test HelloExample: 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:
![]()
Static modifier:
![]() Output: D:\Java>javac Test.java D:\Java>java Test 888.....20
1) Int x=10; 2) Static int x=10; 3) Public void methodOne(){ System.out.println(x); } 4) Public static void methodOne(){ System.out.println(x); }
Which are the following declarations are allow within the same class simultaneously ? 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 . ![]() 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: ![]()
Native modifier:
The main objectives of native keyword are:
To use native keyword:Pseudo code:![]()
Synchronized:
Transient modifier:
Volatile modifier:
Summary of modifier:
Note :
Interfaces:
Def1: Any service requirement specification (srs) is called an interface. ![]() 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. 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. Declaration and implementation of 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.
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(); } ![]() class SubServiceProvider extends ServiceProvider { } Output: Compile time error. D:\Java>javac SubServiceProvider.java SubServiceProvider.java:1: SubServiceProvider is not abstract and does not override abstract method methodTwo() in Interf class SubServiceProvider extends ServiceProvider Extends vs implements:A class can extends only one class at a time. Example:class One{ public void methodOne(){ } } class Two extends One{ } A class can implements any no. Of interfaces at a time. 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(){ } } An interface can extend any no. Of interfaces at a time. Example:interface One{ void methodOne(); } interface Two{ void methodTwo(); } interface Three extends One,Two { }Which of the following is true?
Consider the expression X extends Y for which of the possibility of X and Y this expression is true?
X extends Y, Z ? X extends Y implements Z ?
X implements Y, Z ? 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();
public: To make this method available for every implementation class.
As every interface method is always public and abstract we can't use the following modifiers for interface methods. Inside interface which method declarations are valid?
Interface variables:
interface interf { int x=10; }
public: To make it available for every implementation class. Hence inside interface the following declarations are equal. 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;
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 ?
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 Interface naming conflicts:Method naming conflicts: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.javaCase 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.javaCase 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.
Is a java class can implement any no. Of interfaces simultaneously ? Variable naming conflicts: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.
By implementing SingleThreadModel interface Servlet can process only one client request at a time so that we can get "Thread Safety".
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 ?
Why JVM is providing the required ability in marker interfaces ?
Is it possible to create our own marker interface ? Adapter class:
interface X{ void m1(); void m2(); void m3(); void m4(); //. //. //. //. void m5(); }Example 2: class Test implements X{ public void m3(){ System.out.println("m3() method is called"); } public void m1(){} public void m2(){} public void m4(){} public void m5(){} }
abstract class AdapterX implements X{ public void m1(){} public void m2(){} public void m3(){} public void m4(){} //. //. //. public void m1000(){} }Example 2: public class Test extend AdapterX{{ public void m3(){ }}Example: ![]() Generic Servlet simply acts as an adapter class for Servlet interface. 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?
|
interface | Abstract 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. |
Every method present inside interface is always public and abstract whether we are declaring or not. | Every method present inside abstract class need not be public and abstract. |
We can't declare interface methods with the modifiers private, protected, final, static, synchronized, native, strictfp. | There are no restrictions on abstract class method modifiers. |
Every interface variable is always public static final whether we are declaring or not. | Every abstract class variable need not be public static final. |
Every interface variable is always public static final we can't declare with the following modifiers. Private, protected, transient, volatile. | There are no restrictions on abstract class variable modifiers. |
For the interface variables compulsory we should perform initialization at the time of declaration otherwise we will get compile time error. | It is not require to perform initialization for abstract class variables at the time of declaration. |
Inside interface we can't take static and instance blocks. | Inside abstract class we can take both static and instance blocks. |
Inside interface we can't take constructor. | Inside abstract class we can take constructor. |
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.