Java (Chap-2)
Java (Chap-2)
1 public class MyClass { 1 class MyClass { 1 private class MyClass { 1 protected class MyClass {
2 // Body of the class 2 // Body of the class 2 // Body of the class 2 // Body of the class
3 } 3 } 3 } 3 }
Components of class declaration
1) Access-control modifiers
2) Non-access control modifiers
a) abstract
i) Used to create abstract classes
(a)Defines general structure/skeleton at the top in class hierarchy
(b)Hence, many definitions of data and methods can be skipped
(c)Thus, no objects can be created
(d)May contain one or more declarations of an abstract methods.
(e)Must be sub-classed/extended and then the child class can be instantiated.
(f)Can have abstract methods:
1) If extended, definition of every abstract method be provided
2) If extended by another abstract class, the definition is not required though can
exist.
3) abstract methods can not be private
Note:
1. Constructors can be private, default, protected or public.
Components of method declaration
1) Access-control modifiers
2) Non-access control modifiers
a) static
i) Can ONLY access other static methods or static variables of the same class
1) Hence, it is called Class Method.
ii) Can not access instance variables and non-static methods of the same class directly or
using this.
iii) Can not use this or super keyword.
iv) Can be accessed by other static and non-static methods of the same class directly or using
class name.
v) Can be accessed by static and non-static methods of other classes using class name or
object.
b) final
i) Creates a method that can not be over-ridden in sub-class.
ii) final methods are efficient (inline call) – compiler’s discretion.
iii) private methods are by default final.
c) native
i) Allows code written in non-Java language to be used in Java program.
ii) Use javah to compile java source that contains native method to produce c++ header file.
iii) Use javah –stubs to create c++ source template.
iv) Compile the c++ source to shared library and load in java program
I. System.loadLibrary(“LibraryName”);
Components of method declaration
1) Access-control modifiers
2) Non-access control modifiers
a) static
b) final
c) native
d) synchronized
i) A synchronized method blocks if same or other synchronized method of the class is
being executed by any object of the same class.
ii) “Limits the concurrent execution to one method by multiple objects of same class”
iii) static synchronized method blocks on the class while as non-static synchronized
method blocks on the object.
e) abstract
i) abstract method can only be defined in an abstract class.
ii) However, abstract class declaration is enough to declare a class as abstract.
iii)Any combination of non-access modifiers can be used to declare a method except
abstract.
Note:
1. Constructors can not be static or final or native or synchronized or abstract or any
combination of these.
Components of method declaration
1 public class MyClass{
2 static int foo1() {}
3 final int foo2(){}
4 native int foo3(){}
5 synchronized int foo4(){}
6 abstract int foo5();
7
8 static final native synchronized int bar1(){}
9 static final native int bar2(){}
10 static final synchronized int bar3(){}
11 static native synchronized int bar4(){}
12 static synchronized int bar5(){}
13
14 private static final native synchronized int foobar1(){}
15 private static final native int foobar2(){}
16 private static final synchronized int foobar3(){}
17 private static native synchronized int foobar4(){}
18 private static synchronized int foobar5(){}
19 };
Components of method declaration
<Access-control modifiers> [Non-access modifiers] <return-type> <methodName> ([Parameter1]
[,Parameter2])
{// Body of the method}
1) Access-control modifiers
2) Non-access control modifiers
3) Return type
a) Primitive – int, char, boolean, etc.
b) Derived - arrays
c) Object
d) void
4) Parameters
a) Comma separated list of variables with their types 1 public class MyClass1 {
b) No default values 2 public int foo(int a, int… b) {
3 int sum = 0, count = b.length;
c) Type can be
4 for (int i = 0; i < count; i+/))
a) Primitive, which is passed by value 5 sum = sum + p[i];
b) Derived and Object, which are passed by reference 6 return sum;
d) Can be final – value assigned by caller can not be changed.7 }
e) Automatic type-conversion in method-overloading 8 }
a) If the actual parameter type (say int) does not match the
formal parameter type (say float), the actual parameter
is automatically converted
b) Widening conversion
f) Variable number of parameters of same type
a) Should be last parameter
b) (<type> <parameter>, <type>… <parameter>)
Method overloading & variable hiding
1) Method overloading
1) 2 or more methods of same class having
1) same name, and
2) different number of parameters, or
3) same number of parameters but different types, or both 2) and 3).
2) Modifiers and return-type have no role to play in overloading methods.
2) Variable hiding
a) When instance or class variable has same name as that of local variable or parameter, the
instance or class variable is kept hidden by local variable or parameter.
b) To access instance variable in method, use this keyword.
c) To access class variable in method, use super keyword.
1) Inheritance fundamentals
1 public class MyClass { 1 class MyClass {
2) Java inheritance principle 2 public int a; 2 public int a;
3)Visibility criteria 3 int b; 3 int b;
a) Class 4 protected int c; 4 protected int c;
b) Member 5 private int d; 5 private int d;
4)Keyword 6 }; 6 };
7 7
a) extends
8 // same package class 8 // same package class
9 class MyClass1 extends MyClass { 9 class MyClass1 extends MyClass {
10 //public int a; 10 //public int a;
11 //int b; 11 //int b;
12 //protected int c; 12 //protected int c;
13 }; 13 };
14 14
15 // another package class 15 // another package class can not extend
16 class MyClass2 extends MyClass {
17 //public int a;
18 //protected int c;
19 };
Shadowing & Overriding
1) Inheritance fundamentals
1 public class MyClass {
2) Java inheritance principle 2 public int a;
3)Visibility criteria 3 };
a) Class 4
b) Member 5 // same package class
6 class MyClass1 extends MyClass {
4)Keyword
7 int a;
a) extends 8 void foo() {
5)Shadowing 9 a = 10;
a) Instance or class variables of sub-class can have 10 this.a = 10;
same name as that of inherited variables. 11 super.a = 10;
b) Any direct reference/access to such a name results 12 }
13 };
in access to instance/class variable of sub-class.
a) a=10;
b) this.a=10;
c) To access shadowed variables,
a) super.a=10;
Shadowing & Overriding
1) Inheritance fundamentals
2) Java inheritance principle
3)Visibility criteria
a) Class
b) Member 1 public class MyClass {
4)Keyword 2 void foo() {}
3 void foo(int i) {}
a) extends
4 };
5)Shadowing 5
6) Overriding 6 // same package class
a) Methods of sub-class can have same name and signature as 7 class MyClass1 extends MyClass {
that of inherited methods. 8 void foo() {}
9 public void foo(int i) {}
b) Any direct call to such a name results in access to method of
10 void bar() {
sub-class. 11 foo();
a) foo(); 12 this.foo();
b) this.foo(); 13 super.foo();
c) To access overridden methods, 14 }
a) super.foo(); 15 };
d) Overloaded methods are also overridden.
e) Return-type must match for overridden and overriding
methods.
f) Overriding methods can not be more restrictive than
overridden methods.
a) private -> default -> protected -> public
this & super
this super
1) To refer to current instance of the class 1) To refer to instance of the super class
2) Used in constructor chaining to call overloaded 2) Used in constructor chaining to call overloaded
constructor of the same class from the current constructor of the base class from the current
constructor. constructor.
1) this(1,2,3); 1) super(1,2,3);
3)Used to access instance/class variable hidden by 3)Used to access inherited instance/class variable
the local variable of a method. shadowed by the sub-class variable.
1) this.x=10; 1) super.x=10;
4)Used to call inherited method that is overridden by
the sub-class method.
1) super.foo();
Interfaces
<Modifiers> interface <InterfaceName> [extends <InterfaceName> [,<InterfaceName>]]
{
// Declaration of variables and methods
}
1) Interface basics
1) Interfaces can NOT be instantiated like abstract classes.
1) Pure abstract classes
2) The only applicable access-modifier for interface is either default or public
1) In case of public, source file should be named as that of interface name
3) The only applicable non-access modifier for interface is abstract
1) Interfaces are implicitly abstract
4) Method declarations are implicitly public
1) The only access-modifier applicable is public
2) The class that implements the interface, should provide definition for the
method with public visibility.
5) Variable declarations are implicitly public, final and static
1) Hence, only primitive data types are allowed.
2) Non-blank finals can be initialized by expressions.
6) Interfaces can extend many other interfaces
1) Multiple inheritance
7) A class can implement any number of interfaces and extend one class at the same
time.
Interfaces
<Modifiers> class <ClassName> implements <InterfaceName1> [,<InterfaceName2>]]
{
// Definition of methods declared in the interfaces
}
1) Interface basics
2) Interface implementation
1) An implementing class must provide definition for every method declaration provided by
the interfaces it implements.
2) Two or more interfaces implemented by a class and having multiple method declarations
of same signature need only one definition.
1) Same method declaration signature implies same name, number of parameters, types
of the parameters, and return type.
2) Definition can also be provided by the base-class of the implementing class.
3) Two or more interfaces implemented by a class and having multiple static finals of same
signature can cause ambiguity.
1) Same static final signature implies same name and type.
2) Full-qualification of static finals is needed to resolved the ambiguity in the class
1) Interface1.x=10;
2) Interface2.x=10;
4) Interfaces allow objects of the implementing class to be upcasted to any of its interfaces.
1) Extending a class allows its object to be upcasted to one of its base-classes.
1 interface A {
Interfaces
2 void funcA(); 1 interface A {
3 } 2 int a = 10;
4 interface B extends A { 3 }
5 void funcB(); 4 interface B extends A {
6 } 5 int a = 20;
7 class C implements B { 6 }
8 public void funcA() { 7 class C implements A, B {
9 System.out.println("This is funcA"); 8 void foo() {
10 } 9 System.out.println("A.a: " + A.a);
11 public void funcB() { 10 System.out.println("B.a: " + B.a);
1 interface A {
12 System.out.println("This is funcB"); 11 }
2 void funcA();
13 } 12 }
3 }
14 } 13 public class MyClass {
4 interface B extends A {
15 public class MyClass { 14 public static void main(String args[]) {
5 void funcB();
16 public static void main(String args[]) { 15 C obj = new C();
6 }
17 C obj = new C(); 16 obj.foo();
7 class C implements A, B {
18 obj.funcA(); 17 }
8 public void funcA() {
19 obj.funcB(); 18 }
9 System.out.println("This is funcA");
20 }
10 }
21 }
11 public void funcB() {
12 System.out.println("This is funcB");
13 }
14 }
15 public class MyClass {
16 public static void main(String args[]) {
17 C obj = new C();
18 obj.funcA();
19 obj.funcB();
20 }
21 }
Inner classes
1) Basics
1) A class definition can be placed within another class definition
1) The enclosing class is called Outer Class
2) The nested class is called Inner Class
2) They can be declared with the class body or code block.
3) They behave like normal classes, i.e., they can be instantiated, extended, implement
interface, and so on.
2) Access
1) They can access the members of outer class – including private members.
2) Inner classes can be private, default, protected or public.
3) Outer class can access members of inner class based on access-specifier of the inner class
4) Inner classes can be final, abstract or static.
1) Static inner classes can ONLY access members of outer class using an object
reference to outer class
2) Non-static inner classes can access members of outer class directly.
3) Anonymous inner classes
1) These are inner classes without name
2) They extend an existing class by overriding/adding a method or variable and create an
object of the new class
3) They are extensively used in event-driven programming.
1 class OuterClass {
1 class OuterClass {
2 int x = 10;
2 int x = 10;
3 private class InnerClass {
3 static class InnerClass {
4 int y = 5;
4 int y = 5;
5 }
5 }
6 }
6 }
7 public class Main {
7 public class Main {
8 public static void main(String[] args) {
8 public static void main(String[] args) {
9 OuterClass myOuter = new OuterClass();
9 OuterClass.InnerClass myInner = new OuterClass.InnerClass();
10 OuterClass.InnerClass myInner = myOuter.new InnerClass();
10 System.out.println(myInner.y);
11 System.out.println(myInner.y + myOuter.x);
11 }
12 }
12 }
13 }
2) Catch or Specify
1) Method that throws an exception must either:
1) Catch it by enclosing the statement that throws the exception in try block, and
provide the handler to catch it as catch block. OR
2) Specify that it can throw an exception by publishing a comma delimited list of
exceptions it throws in method declaration using throws so that the method that calls
this method can handle it.
Checked vs Unchecked
1) Checked Exception
1) The program anticipates the exception and can recover from it.
2) As an example, reading a file that does not exist
3) These exceptions are processed at compile time.
4) Therefore, they are subject to catch or specify
5) Examples: ClassNotFoundException, IOException
6) Java programs do not compile if checked exceptions are not either specified or handled.
1) Method should handle it, or
2) Method should specify it, and the caller should handle it.
2) Unchecked Exception
1) The program CANNOT anticipate the exception and CANNOT recover from it.
2) As an example,
3) They are of two types:
1) Error
1) External to application such as I/O device failed during reading/writing
2) Runtime Exception
1) Internal to application such as logical error like division by zero
4) These exceptions are processed at run time.
5) Therefore, they are NOT subject to catch or specify but can be specified and handled to
notify and fix bugs.
6) Examples: NullPointerException, IndexOutOfBoundsException
Checked vs Unchecked
https://www.javacodemonk.com/java-exception-class-hierarchy-92e8224e
Catching an Exception
1) try…catch…finally
1) Java uses try…catch…finally block to catch exceptions.
2) Statement that throws an exception is put in try block.
3) Associated with try block can be 1 or more catch blocks, which is followed by none or
one finally block, OR
4) Associated with try block can be NO catch block, but a mandatory finally block.
5) Associate with each catch block is a specified and unique Exception class of which type
exception object that catch block handles.
1) Therefore, two catch blocks can not specify same exception class.
1 try {
2 // block of code to monitor for errors
3 } catch (ExceptionType1 exOb) {
4 // exception handler for ExceptionType1
5 } catch (ExceptionType2 exOb) {
6 // exception handler for ExceptionType2
7 } finally {
8 // block of code to be executed after try block ends
9 }
Catching an Exception
1) try…catch…finally
2) When exception is raised
1) When an exception is raised in try block, the flow of execution is interrupted,
3) When catch blocks are present
1) The hunt for an appropriate handler begins from the first catch block associated with try
block,
2) The appropriate catch block (handler) is the one whose:
1) Exception class absolutely matches the class of the exception object, or
2) Exception class is super-class of the class of the exception object.
3) If appropriate catch block is found, then
1) A jump from the statement that threw the exception is made to that catch block,
2) The body of the catch block is executed,
3) The preceding and succeeding catch blocks are ignored and not executed,
4) The body of the finally block (if present) is executed,
5) The execution continues to the code that immediately follows the last catch block (if
finally not present) or the finally block (if present).
4) This implies that,
1) The statements in try block that follow the statement that raises exception are never
executed.
2) Only one catch block is executed for an exception.
Catching an Exception
1) try…catch…finally
2) When exception is raised
3) When catch blocks are present
1) If no appropriate catch block is found, then
1) The body of the finally block (if present) is executed,
2) The code following the finally block is not executed,
3) The hunt for appropriate handler continues in the method that called this method
until
1) a handler is found, executed and execution continues from the code that
immediately follows that handler or
2) the default handler is executed and the program terminates.
4) When no catch block is present
1) The hunt for an appropriate handler begins after the execution of finally block
1) In absence of catch block, finally is mandatory.
2) The code following the finally block is not executed,
3) The hunt for appropriate handler continues in the method that called this method until
1) a handler is found, executed and execution continues from the code that immediately
follows that handler or
2) the default handler is executed and the program terminates.
5) When no exception is raised
1) All statements of try block are executed
2) No catch block is executed
3) finally block is certainly executed
6) A return or break or continue in try block ensure that finally is executed before exiting.
Catching an Exception
1 public class MyClass {
2 public static void main(String[] args) {
3 try {
4 int data = 50 / 0; // throws exception
5 // the next statement will not execute
6 System.out.println("Will not execute!");
7 }
8 // Choosing appropriate handler
9 catch (IndexOutOfBoundsException e1) {
10 System.out.println("Not appropriate handler!");
11 } catch (ArithmeticException e2) {
12 System.out.println("Appropriate handler!");
13 } catch (IOException e3) {
14 System.out.println("Appropriate handler but not executed");
15 } finally {
16 System.out.println("Executed whether there is exception or not");
17 }
18 System.out.println("Executed!");
19 }
20 }
Catching an Exception
1 public class MyClass {
2 public static void main(String[] args) {
3 try {
4 int data = 50 / 0; // throws exception
5 // the next statement will not execute
6 System.out.println("Will not execute!");
7 }
8 // No handler
9 finally {
10 System.out.println("Executed whether there is exception or not");
11 }
12 System.out.println(“Not Executed!");
13 }
14 }
Nesting
1) Exceptions can be nested
2) This provides more fine-grained control on exception handling
3) Two possible ways of nesting exist:
1) A try-catch-finally block directly placed inside a try or catch block.
2) A try-catch-finally block in a method is called by another method from a statement in its
try-catch-finally block.
Nesting
1) A try-catch-finally block directly placed inside a try or catch block.
Maximum marks: 05