You are on page 1of 91

OOPS Concept:

1. Data hiding
2. Abstraction
3. Encapsulation
4. Tightly encapsulated class
5. IS-A relationship
6. Has-A relationship
7. Method signature
8. Overloading
9. Overriding

10. Static control flow


11. Instance/ non-static control flow
12. Constructors
13. Coupling
14. Cohesion
15. Type-casting

Data Hiding:
1. Outside person can’t access our internal data directly or our internal
data should not go out directly. This is OOP feature is nothing but
Data hiding.
2. After validation or identification outside person can access our
internal data.

Example:

1. After providing proper username and password, we can able to access our
G-mail inbox information.
2. Even though we are valid customer of the bank, we can able to access
our account information and we can’t access other’s account
information.
3. By declaring data member (variable only) as private we can achieve data
hiding.

package pack6;

public class Account {

private double balance;

public double getBalance() {

return balance; //validation


}

1. The main advantage of data hiding is security.

Note: It is highly recommended to declare data member (variable) as private.

Abstraction:
1. Hiding internal implementation and just highlight the set of services
what are offering is the concept of abstraction.

Example: Through Bank ATM GUI screen, bank people are highlighting the set of
service what they are offering without highlighting internal implementation.

Withdraw Deposit

Check Balance Mini Statements

Bank ATM GUI Screen


The main advantages of abstraction are:

1. We can achieve security because we are not highlighting our internal


implementation.
2. Without effecting outside person, we can able to perform any type of
changes any internal system and hence enhancement will become easy.
3. It improves maintainability of the application.
4. It improves easiness to use our system.
5. By using interfaces and abstract classes we can implement abstraction.

Encapsulation:
1. The process of binding data and corresponding methods into a single
unit is nothing but encapsulation.

Example:

Class students {

Data member + methods (behavior) Medicine for cold

Capsule

2. If any component follows data hiding and abstraction. Such type of


components is said to be encapsulated components.

Encapsulation = Data hiding + Abstraction

package pack6;

public class Account {

private double balance;

public double getBalance() { //Balance enquiry


//validation
return balance;
}
public void setBalance() { //Update Balance
//validation
this.balance = balance;
}

The main advantages of the encapsulation are:

1. We can achieve security.


2. Enhancement will become easy.
3. It improves maintainability of the application.

Note:

The main advantage of encapsulation is, we can achieve security but the main
disadvantage of the encapsulation is, it increases length of the code and
slows down execution.

Tightly encapsulated class:


1. A class is said to be tightly encapsulated, if and only if each and
every variable declared as private.
2. Whether class contains corresponding getter and setter methods or not
and whether these methods are declared as public or not. These things
we are not required to check.

package pack6;

public class Account {

private double balance;

public double getBalance() {


//validation
return balance;
}

}
Which of the following classes are tightly encapsulated?
 package pack1;

public class A{
private int x = 10;
private String name = "Lalit";
}

 package pack1;

public class B extends A {

int y = 20;
}

 package pack1;

public class C extends B {


private int z = 30;
}

 package pack1;

public class C extends A {


private int z = 30;
}
IS-A Relationship:
1. It is also known as inheritance.
2. The main of advantage of IS-A Relationship is code reusability.
3. By using extends keyword we can implement IS-A Relationship.

Example:

Case1:

package pack1;

public class A{

public void m1() {


System.out.println("Parent");
}
}

package pack1;

public class B extends A {

public void m2() {


System.out.println("Child");
}
}

package pack1;

public class C {
public static void main(String[] args) {
A a = new A();
a.m1();
a.m2();----------------------------------Error
}
}

Compile time error: The method m2() is undefined for the type A at
pack1.C.main/ cannot find symbol: method m2(), location: class A
Case1:

package pack1;

public class A{

public void m1() {


System.out.println("Parent");
}
}

package pack1;

public class B extends A {

public void m2() {


System.out.println("Child");
}
}

package pack1;

public class C {
public static void main(String[] args) {
B b = new B();
b.m1();--------------------------------------Parent
b.m2();--------------------------------------Child
}
}

Case1:

package pack1;

public class A{

public void m1() {


System.out.println("Parent");
}
}
package pack1;

public class B extends A {

public void m2() {


System.out.println("Child");
}
}

package pack1;

public class C {
public static void main(String[] args) {
A a = new B();
a.m1();
a.m2();--------------------------------Error
}
}

Compile time error: The method m2() is undefined for the type A at
pack1.C.main/ cannot find symbol: method m2(), location: class A

Case4: B a = new A();-------Error

Compile time error: cannot convert from A to B at pack1.C.main/


incompatible types, found: A, required: B

Conclusion:
1. Whatever methods parent has by default available to the child and
hence on the child reference we can call both parent and child
class methods.
2. Whatever methods child has by default not available to the parent
class and hence on the parent reference we can’t call child
specific methods.
3. Parent reference can be used to hold child object but using that
reference we can’t call child specific methods. But we can call
methods present in parent class.
4. Parent reference can be used to hold child object but child
reference can’t be used to hold parent object.
Note:
1. The most common methods which are applicable for any type child,
we have to define in parent class.
2. The specific which are applicable for a particular child, we have
to define in child class.

 Total java API is implemented based on inheritance concept.

 The most common methods which are applicable for any java
object are defined in Object Class and hence every class in
java either child class of the object class either directly or
indirectly, so that object class methods by default available
to every class java without re-writing. Due to this object
class access is root for all java classes.

 Throwable class defines the most common methods which are


required for every exception and error classes. Hence this
access as root for java exception hierarchy.

Object class(11 methods)

String class StringBuffer class Throwable class

Exception class Error class

RunTimeErrorException class IOException class OutOfMemory


 ArithmeticException
 NullPointException
Multiple inheritance:
1. A java class can’t extend more than one class at a time. Hence
java won’t provide support for multiple inheritance in classes.

Note:

 If our class doesn’t extend any other class then only our
class is direct child class of object class.

Class A {

Child Class( class A)------> Object class

 If our class extends any other class then our class is


indirect child class of object.

Class A extends B {

Class A-----> Class B-----> Object Class---Multilevel


inheritance

2. Either directly or indirectly, java won’t provide support for


inheritance with respect to classes.

Q: Why java won’t provide support for multiples inheritance?


Ans: There may be a chance of ambiguity problem. Hence java
won’t provide support multiples inheritance.

P1 class------m1() method.
P2 class------m1() method.

P3 class extends P1,P2 {

Compile time error: Ambiguity problem

3. But interface can extend any number of interfaces


simultaneously. Hence java provides support for multiples
inheritance with respect to interface.
4. Even though multiple methods declarations are available but
implementation is unique and hence there is no chance of
ambiguity problem in interfaces.

package pack1;

interface A{

public void m1();


}

package pack1;

interface B {

public void m1();


}

package pack1;

public class C implements A,B{

@Override
public void m1() {
// TODO Auto-generated method stub

Note:

Strictly speaking through we won’t get any inheritance.

Cyclic inheritance:
Cyclic inheritance is not allowed in java, off course it is not required.

Example1:

Class A extends A {

}
Example2:

Class A extends B {

Class B extends A {

Compile time error: cycling inheritance is involving


HAS-A Relationship:
1. HAS-A relationship is also known as composition or aggregation.
2. There is no specific keyword to implement HAS-A relation but most of
the times we are depending on new keyword.
3. The main advantage of HAS-A relationship is reusability of the code.

Example:

Class Engine {

Engine specific functionality

Class Car {

Engine e = new Engine();-------HAS-A relationship

Difference between composition and aggregation:

Composition Aggregation

1. Without exiting container 1. Without exiting container


object, if there is no object, if there is a chance
chance of exiting contained exiting contained object
objects then container and then container and contained
contained objects are objects are weakly
strongly associated and this associated and this weak
strong association is association is nothing but
nothing but composition. aggregation.

Example: Example:

University consists of several Department consist of several


departments. Without exiting professors. Without exiting
university, there is no chance of department, there may be a chance
exiting department. Hence of exiting professor objects.
university and departments are Hence department and professor
strongly associated and this objects are weakly associated and
strong association is nothing but this weak association is nothing
composition. but aggregation.
Civil department Professor1
Mech. department Professor2
Comp. department Professor3
Electric department Professor4

University Department

Contained objects
Container object Contained object Container object

Note:

 In composition objects are strongly associated whereas in


aggregation objects are weakly associated.
 In composition container object holds directly contained
objects, whereas in aggregation container object holds
just references of contained objects.

IS-A relationship v/s HAS-A relationship:


1. If we want total functionality of a class automatically then we should
go for IS-A relationship.

Example:

Person class (100 methods) Student class(Person’s class 100 methods

+ Student’s class methods)

2. If we want part of the functionality then we should go for HAS-A


relationship.

Test class (100 methods) Student Class (Person’s class 10 methods


+ Student’s class methods)
Method signature:
1. In java method signature consists of method name followed by argument
types.

Example:

Public static int m1 (int x, float y);

2. Return type is not part of method signature in java.


3. Compiler will use method signature to resolve method calls.

package pack1;

public class Test {

public void m1(int i) {


System.out.println(i);
}

public void m2(String s) {


System.out.println(s);
}
public static void main(String[] args) {
Test t = new Test();
t.m1(10);
t.m2("Lalit");
}

4. Within a class two methods with the same signature are not allowed,
even return types are different.

package pack1;

public class Test {

public void m1(int i) {


System.out.println(i);
}
public int m1(int s) {
return s;
}
public static void main(String[] args) {
Test t = new Test();
}

Compile time error: m1(int) is already defined in Test class.


Overloading:
1. Two methods are said to be overloaded if and only if both methods
having same name but different argument types.

package pack1;

public class Test {

public void m1(int i) {


System.out.println(i);
}

public String m1(String s) {


return s;
}
public static void main(String[] args) {
Test t = new Test();
}

2. In C language method overloading concept is not available. Hence we


can’t declare multiple methods with same name but different argument
types. If there is change in argument types, compulsory we should go
for new method name which increases complexity of programming.

3. But in java we can declare multiple methods with the same but different
argument types. Such types of methods are called overloaded methods.

4. Having overloaded concept in java reduces complexity of programming.

5. In overloading, method resolution always takes care by compiler based


on reference type. Hence overloading is also considered as compile time
polymorphism or static polymorphism or early binding.

package pack1;

public class Test {

public void m1(int i) {


System.out.println(i);
}

public String m1(String s) {


return s;
}
public static void main(String[] args) {
Test t = new Test();
t.m1(10);
t.m1("Lalit");
}

Case1: Automatic promotion in overloading:

While resolving overloaded methods, if exact matched method is not available


then we won’t get any compile time error immediately.

First it will promote argument to the next level and checked whether matched
method is available or not.

If matched method is available then it will be considered.

If the matched method is not available then compiler promotes arguments once
again to the next level. This process will be continued until all possible
promotions.

Still if the matched method is not available then we will get compile time
error. The following are all possible promotions in overloading.

 Byteshortintlongfloatdouble

 Charintlongfloatdouble

This process is called Automatic promotion in overloading.

package pack1;

public class Test {

public void m1(int i) {


System.out.println(i);
}

public void m1(float f) {


System.out.println(f);
}
public String m1(String s) {
return s;
}
public static void main(String[] args) {
Test t = new Test();
t.m1(10);
String s = t.m1("Lalit");
System.out.println(s);
t.m1('a');
t.m1(10.5f);
t.m1(10l);
t.m1(10.5);-------------Error only in double
}

package pack1;

public class Test {

public void m1(int i) {


System.out.println(i);
System.out.println("int arg");
}

public void m1(float f) {


System.out.println(f);
System.out.println("float arg");
}

public static void main(String[] args) {


Test t = new Test();
t.m1(10);
t.m1('a');
t.m1(10.5f);
t.m1(10l);

}
Case2:

While resolving overloaded methods compiler will always gives a


presidential for child class type argument then compared with parent
class argument.

String class (child)---------> Object class (parent)


package pack1;

public class Test {

public void m1(String s) {


System.out.println(s);
System.out.println("string-version");
}

public void m1(Object o) {


System.out.println(o);
System.out.println("object-version");
}

public static void main(String[] args) {


Test t = new Test();
t.m1(new Object());
t.m1("Lalit");
t.m1(null);

Case3:
Object String
StringBuffer

package pack1;

public class Test {

public void m1(String s) {


System.out.println(s);
System.out.println("string-version");
}

public void m1(StringBuffer sb) {


System.out.println(sb);
System.out.println("StringBuffer-version");
}

public static void main(String[] args) {


Test t = new Test();
t.m1(new StringBuffer("Bizlain"));
t.m1("Lalit");
t.m1(null);---------------------------Error

}
Compile time error: reference to m1( ) is ambiguous

package pack1;

public class Test {

public void m1(String s) {


System.out.println(s);
System.out.println("string-version");
}

public void m1(StringBuffer sb) {


System.out.println(sb);
System.out.println("StringBuffer-version");
}

public static void main(String[] args) {


Test t = new Test();
t.m1(new StringBuffer("Bizlain"));
t.m1("Lalit");

}
}

Case3:

package pack1;

public class Test {

public void m1(int i, float f) {


System.out.println(i);
System.out.println(f);
System.out.println("int-float-version");
}

public void m1(float f, int i) {


System.out.println(f);
System.out.println(i);
System.out.println("float-int-version");
}

public static void main(String[] args) {


Test t = new Test();
t.m1(10, 10.5f);
t.m1(10.5f, 10);
t.m1(10, 10);---------Error: reference to m1( ) is ambiguous
t.m1(10.5f, 10.5f);---Error: cannot find symbol
m1(float,float) in class Test

}
}

package pack1;

public class Test {

public void m1(int i, float f) {


System.out.println(i);
System.out.println(f);
System.out.println("int-float-version");
}

public void m1(float f, int i) {


System.out.println(f);
System.out.println(i);
System.out.println("float-int-version");
}

public static void main(String[] args) {


Test t = new Test();
t.m1(10, 10.5f);
t.m1(10.5f, 10);

}
}
Case5:

In general var-arg method will get least priority i.e if no other


method matched then only var-arg method will get the chance. It is
exactly same default case inside switch.

package pack1;

public class Test {

public void m1(int i) {


System.out.println(i);
System.out.println("General-method");
}

public void m1(int... i) {


System.out.println(i);
System.out.println("var-arg-method");
}

public static void main(String[] args) {


Test t = new Test();
t.m1();
t.m1(10,20);
t.m1(10);

}
}

Case4:

In overloading method resolution always takes care by compiler based on


reference type.

package pack1;

public class Animal{

public void m1(Animal a) {


System.out.println("Animal-version");
}

}
package pack1;

public class Monkey extends Animal {


public void m1(Monkey m) {
System.out.println("Monkey-version");
}

package pack1;

public class Test {

public static void main(String[] args) {


Animal a = new Animal();
a.m1(a);-------------------- Animal-version

Monkey m = new Monkey();


m.m1(m);--------------------- Monkey-version

Animal a1 = new Monkey();


a1.m1(a1);------------------- Animal-version

}
}
Overriding:
1. Whatever methods parent has by default available to the child
through inheritance. If child class not satisfied with parent
class implementation then child is allowed to redefine that
method based on its requirement. This process is called
overriding.
2. The parent class method which is overridden is called overridden
method and child class method which is overriding is called
overriding method.

package pack6;

public class Parent {

public void property() {


System.out.println("land,gold,cash");
}

public void marriage() {


System.out.println("Lakshmi");
}

package pack6;

public class Child extends Parent {

public void marriage() {


System.out.println("sita");
}
public static void main(String[] args) {
Child c = new Child();
c.marriage();---------------sita

}
}

3. In overriding method resolution always takes care by JVM based on


run-time object and hence overriding is also considered as run-
time polymorphism or dynamic polymorphism or late binding.
package pack6;

public class Parent {

public void property() {


System.out.println("land,gold,cash");
}

public void marriage() {


System.out.println("Lakshmi");
}

package pack6;

public class Child extends Parent {

public void marriage() {


System.out.println("sita");
}
public static void main(String[] args) {

Parent p = new Parent();


p.marriage();---------------------Lakshmi
p.property();---------------------land,gold,cash

Child c = new Child();


c.marriage();-------------------------sita
c.property();-------------------------land,gold,cash

Parent p1 = new Child();


p1.property();------------------------land,gold,cash
p1.marriage();------------------------sita
}
}

Rules for overriding:


 In overriding methods names and argument types must be matched
i.e method signature must be same.
 In overriding return type must be same but this rule is
applicable until 1.4 version only. From 1.5 versions onwards we
can take co-variant return types.
 According to this child class method return type need not be same
as parent method return type. Its child type also allowed.

package pack6;

public class Parent {

public Object m1() {


return 2; // here can be any data type value

package pack6;

public class Child extends Parent {

public String m1() {


return "Lalit";
}

public static void main(String[] args) {


Child c = new Child();
String s = c.m1();
System.out.println(s);---------------------- Lalit

Object o1 = c.m1();
System.out.println(o1);--------------------- Lalit

Parent p = new Parent();


Object o = p.m1();
System.out.println(o);---------------------- 2
}
}
 Co-variant return type applicable only for object types but not
primitive types.

Parent class return type Child class return type

1. Object 1. Object, String,


StringBuffer
2. Number 2. Number, Interger,
Float, Double, Long
3. int 3. int
4. double 4. double
5. float 5. float
6. short 6. short
7. long 7. long
8. char 8. char

But String to Object is not allowed and int to double is not allowed.

 Parent class private method not available to the child and hence
overriding concept not applicable for private methods.

 Based on our requirements exactly same private method in child


class as in parent class. It is valid but not overriding.

package pack6;

public class Parent {

private void m1(String x) {


System.out.println(x);
System.out.println("Lalit");
}
}

package pack6;

public class Child extends Parent {

private void m1(int y) {


System.out.println(y);
System.out.println("Bizlain");
}

public static void main(String[] args) {


Child c = new Child();
c.m1(10);

}
}

 We can’t override parent class final method in child classes. If


we are trying to override we will get compile time error.

package pack6;

public class Parent {

public final void m1() {

}
}

package pack6;

public class Child extends Parent {

public void m1() {-------------------Error

Compile time error: m1( ) in Child cannot override m1( ) in Parent:


overridden method is final.

 Abstract Parent class abstract methods we should override in


child class to provide implementation.

package pack6;

public abstract class Parent {

public abstract void m1();


}}

package pack6;
public class Child extends Parent {

@Override
public void m1() {

 We can override non-abstract method as abstract.

package pack6;

public class Parent {

public void m1() {

}
}

package pack6;

public abstract class Child extends Parent {

@Override
public abstract void m1();

package pack6;

public class Child1 extends Child {

@Override
public void m1() {
// TODO Auto-generated method stub

The main advantage of this approach is, we can stop the availability
of parent method implementation to the next level child classes.
 In overriding the following modifiers won’t keep any restriction:

Parent class Child class

 Synchronize non-synchronize
 Native non-native
 Strictfp non-strictfp
 Non-final final
 Abstract non-abstract

But final to non-final is acceptable.

 While overriding we can’t reduce scope of access modifiers but we


increase the scope.

 If we reduce the scope of modifiers:

package pack6;

public class Parent {

public void m1() {

}
}

package pack6;

public abstract class Child extends Parent {

@Override
abstract void m1();

Compile time error: m1( ) in Child cannot override m1( ) in Parent:


attempting to assign weaker access privileges: was public

 If we increase scope of access modifiers:


package pack6;

public class Parent {

void m1() {

}
}

package pack6;

public class Child extends Parent {

@Override
public void m1() {

Most acceptable scope of modifiers:

Private < default < protected < public.

Parent class Child class

 Public public
 Protected protected, public
 Default default, protected, public
 Private Overriding concept not allowed

 If child class methods throw any checked exception, compulsory


parent class method should throw the same checked exception or
its parent. Otherwise will get compile time error but there are
no restrictions for unchecked exceptions.

Example1:
package pack6;

import java.io.IOException;

public class Parent {

public void m1() throws IOException {

package pack6;

import java.io.*;

public class Child extends Parent {

@Override
public void m1() throws EOFException,InterruptedException {--Error

public static void main(String[] args) {

Compile time error: m1( ) in Child cannot override m1() in Parent:


overridden method doesn’t throws java.lang.InterruptedException

package pack6;

import java.io.IOException;

public class Parent {

public void m1() throws IOException, InterruptedException {

}
package pack6;
import java.io.*;

public class Child extends Parent {

@Override
public void m1() throws EOFException, InterruptedException {

public static void main(String[] args) {

Exapmple2:

package pack6;

public class Parent {

public void m1() throws Exception {

package pack6;

public class Child extends Parent {

@Override
public void m1() {

}
public static void main(String[] args) {

Example3:
package pack6;

public class Parent {

public void m1() {

package pack6;

public class Child extends Parent {

@Override
public void m1() throws Exception {-----Error

}
public static void main(String[] args) {

Compile time error:

package pack6;

public class Parent {

public void m1() throws Exception {

package pack6;

public class Child extends Parent {

@Override
public void m1() throws Exception {

}
public static void main(String[] args) {

Example4:

package pack6;

public class Parent {

public void m1() throws Exception {

package pack6;

import java.io.IOException;

public class Child extends Parent {

@Override
public void m1() throws IOException {

}
public static void main(String[] args) {

Example5:

package pack6;

import java.io.IOException;

public class Parent {


public void m1() throws IOException {

package pack6;

public class Child extends Parent {

@Override
public void m1() throws Exception {

}
public static void main(String[] args) {

package pack6;

import java.io.IOException;

public class Parent {

public void m1() throws IOException, Exception {

package pack6;

public class Child extends Parent {

@Override
public void m1() throws Exception {

}
public static void main(String[] args) {

Example6:

package pack6;

import java.io.IOException;

public class Parent {

public void m1() throws IOException {

package pack6;

import java.io.EOFException;
import java.io.FileNotFoundException;

public class Child extends Parent {

@Override
public void m1() throws FileNotFoundException,EOFException {

}
public static void main(String[] args) {

Exaple7:
package pack6;

import java.io.IOException;

public class Parent {

public void m1() throws IOException {

package pack6;

public class Child extends Parent {

@Override
public void m1() throws
ArithmeticException,NullPointerException,ClassCastException {

}
public static void main(String[] args) {

Overriding with respect to static methods:


1. We can’t override a static method as non-static, otherwise we
will get compile time error.

package pack6;

public class Parent {

public static void m1() {

package pack6;

public class Child extends Parent {

@Override
public void m1() {--------Error

}
public static void main(String[] args) {

Compile time error: m1() in Child cannot override m1() in Parent:


overridden methods in static

2. Similarly we can’t override a non-static method as static.

package pack6;

public class Parent {

public void m1() {

}
package pack6;

public class Child extends Parent {

@Override
public static void m1() {-----Error

}
public static void main(String[] args) {

Compile time error: m1() in Child cannot override m1() in Parent:


overriding methods in static

3. If both parent and child class methods are static then we


won’t get any compile time error. It seems overriding
concept applicable for static methods but it is not
overriding. It is method hiding.

package pack6;

public class Parent {

public static void m1() {

}
}

package pack6;

public class Child extends Parent {

public static void m1() {---No overrding annotation is allowed in


method hiding

}
public static void main(String[] args) {

}
Method hiding:
All rules of method hiding are exactly same as overriding
except the following differences.

Method hiding Method overriding


 Both parent and child  Both parent and child
class methods should be class methods should be
static. non-static.
 Compiler is responsible  JVM is always
for method resolution responsible for method
based on reference resolution based on
type. run-time object.
 It is also known as  It is also known as run
compile time time polymorphism or
polymorphism / static dynamic polymorphism or
polymorphism / early late binding.
binding/

Example of method hiding:

package pack6;

public class Parent {

public static void m1() {


System.out.println("Parent");
}

package pack6;

public class Child extends Parent {

public static void m1() {


System.out.println("Child");
}
public static void main(String[] args) {
Parent p = new Parent();
p.m1();-----------------------Parent

Child c = new Child();


c.m1();-------------------Child
Parent p1 = new Child();
p1.m1();---------------------Parent
}

package pack6;

public class Child extends Parent {

public static void m1() {


System.out.println("Child");
}
public static void main(String[] args) {
Parent.m1();-----------------------Parent
Child.m1();------------------------Child
}

Example of method hiding:

package pack6;

public class Parent {

public void m1() {


System.out.println("Parent");
}

package pack6;
public class Child extends Parent {

@Override
public void m1() {
System.out.println("Child");
}

public static void main(String[] args) {


Parent p = new Parent();
p.m1();---------------------Child

Child c = new Child();


c.m1();----------------------Child

Parent p1 = new Child();


p1.m1();----------------------Child
}

Method overriding with respect to var-argument:


1. We can override var-arg method with another var-arg method only.
If we are trying to override with normal method then it will
become overloading but not overriding.

Var-arg method with normal method: it will be overloading.

package pack6;

public class Parent {

public void m1(int...x) {


System.out.println("Parent");
}

package pack6;

public class Child extends Parent {

public void m1(int x) {


System.out.println("Child");
}

public static void main(String[] args) {


Parent p = new Parent();
p.m1(10);------------------------------- Parent

Child c = new Child();


c.m1(10); );------------------------------- Child

Parent p1 = new Child();


p1.m1(10); -------------------------------Parent
}

Var-arg method with var-arg method: it will be overriding.

package pack6;

public class Parent {


public void m1(int...x) {
System.out.println("Parent");
}

package pack6;

public class Child extends Parent {

@Override
public void m1(int... x) {
System.out.println("Child");
}

public static void main(String[] args) {


Parent p = new Parent();
p.m1(10); -------------------------------Parent

Child c = new Child();


c.m1(10);------------------------------- Child

Parent p1 = new Child();


p1.m1(10);------------------------------- Child

In the above if we replace child with var-arg method then it will


become overriding.

Overriding with respect to variables:


1. Variable resolution always takes care by compiler based on
reference type irrespective of whether the variable is
static or non-static (overriding concept applicable only for
methods but not for variables).

package pack6;

public class Parent {


int x = 888;

package pack6;

public class Child extends Parent {


int x = 999;

package pack6;

public class Test {


public static void main(String[] args) {
Parent p = new Parent();
System.out.println(p.x);

Child c = new Child();


System.out.println(c.x);

Parent p1 = new Child();


System.out.println(p1.x);
}

Differences between overloading and overriding:


Property Overloading Overriding
1. Methods names  Must be same  Must be same

2. Argument types  Must be different (At  Must be same


least order) ( including order)
3. Method  Must be different  Must be same
signature

4. Return type  No restriction  Must be same until


1.4 version. From 1.5
version onwards co-
variant types are
allowed.
5. Private,  Can be overloaded  Cannot be overridden
static, final
method
6. Access  No restriction  We can’t reduce scope
modifiers of access modifier
but we can increase
the scope
7. Throws clause  No restriction  If child class method
throws any checked
exception. Compulsory
parent class method
should throw same
exception or its
parent but no
restriction for
unchecked exception.
8. Method  Always takes care by  Always takes care by
resolution compiler based on JVM based on run-time
reference type object.
9. It is also  Compile time polymorphism  Run time polymorphism
known as or static polymorphism or or dynamic
early binding polymorphism or late
binding.

Note:

In overloading we have to check only method names (must be same) and


argument types (must be different).
We are not required to check remaining like return types, access
modifiers etc.

But in overriding everything we have to check like method name,


argument types, return type, access modifiers, throws clause etc.
Q: consider the following in parent class.

Public void m1 (int x) throws IOException { }

In the child class which of the following methods we can take?

 Public void m1 (int i) { } overriding


 Public static void m1 (long l) { } overloading
 Public static void m1 (int i) { } overriding
 Public void m1 (int i) throws Exception { } overriding
 Public static abstract void m1 (double d); illegal combination of

Modifier

Polymorphism:
1. One name but multiple forms are the concept of polymorphism.
Example1:

Method name is the same but we can apply for different types of arguments.
This concept is called overloading.

Abs(int), abs(long), abs(float)

Example2:

Method signature is same but in parent class one type of implementation and
in the child class another type of implementation. This concept is called
overriding.

package pack6;

public class Parent {

public void m1() {


System.out.println("lalit");
}

package pack6;

public class Child extends Parent {

@Override
public void m1() {
System.out.println("Bizlain");
}
public static void main(String[] args) {

Example3:

Usage of parent reference to hold child object is the concept of


polymorphism.

ArrayList

LinkedList

Collection (I) List (I) vector Stack

 List l = new ArrayList():


 List l = new Linkedlist():
 List l = new Vector():
 List l = new Stack():

 Parent class can be used to hold child class object but by using
that reference we can call only the methods available in parent
class and we can’t child specific methods.

But by using child reference we can call both parent and child class methods.

 If we don’t know exact run time type of object then we should go


for parent reference.
Example:

The first element present in the ArrayList can be any type. It may be student
object or customer object or string object or stringBuffer object. Hence the
return type of get method is object which can hold any object.

Object o = l.get(0);
Child c = new Child(); Parent p = new child();

Eg: ArrayList a = new ArrayList(); Eg: List l = new ArrayList();

 We can use this approach if we  We can use this approach if we


know exact run time type of don’t know exact run time type
object. of object.
 By using child reference we can  By using parent reference we
call both the parent class and can call only methods available
child class methods (This is in parent class and we can’t
the advantage of this call child specific methods
approach). (This is the disadvantage of
this approach).

 We can use child reference to  We can use parent reference to


hold only particular child hold any child class
class object (This is the object(This is the advantage of
disadvantage of this approach). this approach).

Three pillars of OOPs concept:

OOPs Encapsulation (Security)


Inheritance (Reusability)
Polymorphism (Flexibility)

Static polymorphism Run time polymorphism


Compile time polymorphism Dynamic polymorphism
Early binding Late binding

Method Overloading Method hiding Method overriding

Coupling:
1. The degree of dependency between the components is called
coupling.
2. If dependency is more then it is considered as tightly coupling
and if dependency is less then it is considered as loosely
coupling.

Example:

package pack4;

public class D {
public static int m1() {
return 10;
}
}

package pack4;

public class C {
static int k = D.m1();
}

package pack4;

public class B {
static int j = C.k;
}

package pack4;

public class A {
static int i = B.j;
}

The above components are said to be tightly couple to each other


because dependency between the components is more.
Tightly coupling is not a good programming practice because it has
several serious disadvantages:

1. Without effecting remaining components, we can’t modify any


component and hence enhancement will become difficult.
2. It suppresses reusability.
3. It reduces maintainability of the application.
4. Hence we have to maintain dependency between the components as
less as possible i.e loosely coupling is a good programming
practice.

Cohesion:
1. For every component a clear well defined functionality is define then
that component is said to be follow high-cohesion.
Example:

Low-cohesion:

Total servlet

Login page display

Validation

Index page

Reply page

Compose page

Error page

High-cohesion:

Login page.jsp validServlet index.jsp reply.jsp

Error.jsp compose.jsp

High-cohesion is always a good programming practice because it has several


advantages:

1. Without effecting remaining component we can modify any component.


Hence enhancement will become easy.
2. It promotes reusability of the code (wherever validation is required we
can reuse the same validate servlet without re-writing).
3. It improves maintainability of the application.

Object type Casting:


1. We can use parent reference to hold child object.
Example:

Object 0 = new String (“Lalit”);

2. We can use interface reference to hold implemented class object.


Example:

Runnable r = new Thread();

Reference variable name reference variable name

A a = (C) d;

Class/interface name class/interface name

Mantra1 (compile time checking 1):

The type of ‘d’ and ‘C’ must have some relation either child to parent or
parent to child or same type otherwise we will get compile time error saying
inconvertible, found: d, required: C.

Example:

Object o = new String(“lalit”);


StringBuffer sb = (StringBuffer) o;------valid

String s = new String(“lalit”);


StringBuffer sb = (StringBuffer) s;------invalid

Compile time error: inconvertible types, found: java.lang.String, required:


java.lang.StringBuffer

Mantra2 (compile time checking 2):


‘C’ must be either same or derived type of ‘A’, otherwise we will get compile
time error saying incompatible types found: C required: A.

Example:

Object o = new String(“lalit”);


StringBuffer sb = (StringBuffer) o;------valid

Object o = new String(“lalit”);


StringBuffer sb = (String) o;------invalid

Compile time error: incompatible types, found: java.lang.String, required:


java.lang.StringBuffer

Mantra3(run time checking):

Run time object type of ‘d’ must be either same or derived type of ‘C’,
otherwise we will get run time exception saying class cast exception:
java.lang.Strong cannot be cast to java.lang.StringBuffer.

Example:

Object o = new String(“lalit”);


StringBuffer sb = (StringBuffer) o;------invalid

Object o = new String(“lalit”);


Object o1 = (String) o;------valid

 Strictly speaking through type casting we are not creating any new
object.
 For the exiting object we are providing another type of reference
variable i.e we are perfoming type casting (conversion) but not object
casting.

Example:

String s = new String(“lalit”); String s


Object o = (String) s;------valid lalit
Object o
Object o = new String(“lalit”);

Integer i = new Integer(10);


Number n = (Number) i;
Object o = (Object) n;-----------valid

Number n = new Integer(10);


Object o = new Integer(10);

Integer i

Number n 10

Object o

package pack2;

public class C {
public static void main(String[] args) {
Integer i = new Integer(10);
Number n = (Number) i;
Object o = (Object) n;

System.out.println(i==n);--------true
System.out.println(n==o);--------true
System.out.println(i==o);--------true
}
}

Note:

C B A

C c = new C();

B b = (B) c;----B b = new C();

A a = (A)((B)c);-----A a = new C();

package pack6;
public class Parent {

public void m1() {


System.out.println("lalit");
}

package pack6;

public class Child extends Parent {

public void m2() {


System.out.println("bizlain");
}

public static void main(String[] args) {


Child c = new Child();
c.m1();----------------------lalit
c.m2();----------------------bizlain

((Parent)c).m1();---------lalit (Parent p = new child(); p.m1();)


((Parent)c).m2();------Error (Parent p = new child(); p.m2();)

}
}

Parent reference can be used to hold child object but by using that reference
we can’t call child specific methods and we can call only the methods
available in parent class.

Example1:

package pack6;

public class Parent {

public void m1() {


System.out.println("lalit");
}

package pack6;
public class Child extends Parent {
@Override
public void m1() {
System.out.println("bizlain");
}

package pack6;

public class Child1 extends Child {


@Override
public void m1() {
System.out.println("lalli");
}

public static void main(String[] args) {


Child1 c = new Child1();
c.m1();--------------------lalli

((Child)c).m1();----------lalli

((Parent)((Child)c)).m1();---------lalli
}
}

In this example overriding is happening, so method resolution is always


based on run time object.

Example2:

package pack6;

public class Parent {

public static void m1() {


System.out.println("lalit");
}

}
package pack6;

public class Child extends Parent {

public static void m1() {


System.out.println("bizlain");
}

package pack6;

public class Child1 extends Child {

public static void m1() {


System.out.println("lalli");
}

public static void main(String[] args) {


Child1 c = new Child1();
c.m1();-------------------lalli

((Child)c).m1();-------------bizlain

((Parent)((Child)c)).m1();--------------lalit
}
}

In this example we are using static keyword for every same signature
method. Here it is method hiding not method overriding. In method
hiding, method resolution is always based on reference type.

Example3:

package pack6;

public class Parent {


int x = 999;

package pack6;
public class Child extends Parent {

int x = 888;
}

package pack6;

public class Child1 extends Child {

int x = 777;

public static void main(String[] args) {


Child1 c = new Child1();
System.out.println(c.x);--------------777

System.out.println(((Child)c).x);---------888

System.out.println(((Parent)((Child)c)).x);--------999
}
}

In the case of instance variable, variable resolution is always based on


reference type.
Static control flow:
1. Whenever we are executing a java class, the following sequence of steps
will be executed as the part of static control flow.

 Identification of static members from top to bottom [1 to 6].


 Execution of static variable assignment and static block from top to
bottom [7-12].
 Execution of main method [13-15].

Example:

package pack5;

public class Base {

1 static int i = 10; 7

2 static {

m1(); 8

System.out.println("First static block"); 10


}

3 public static void main(String[] args) {

m1(); 13

System.out.println("Main method"); 15
}

4 public static void m1() {

System.out.println(j); 9 14
}

5 static {

System.out.println("Second static block"); 11


}

6 static int j = 20; 12

}
I = 0; [read indirect and write only at step 1st]
J = 0; [read indirect and write only at step 6th]
I = 10; [read and write at step 7th]
J = 20; [read and write at step 12th]

Output:

0
First static block
Second static block
20
Main method

2. Inside static if we are trying to read variable that read


operation is called direct read.

3. If we are calling a method and within that method if we are


trying to read a variable that read operation is called indirect
read.

Example:

package pack5;

public class Base {

static int i = 10;

static {

m1();

System.out.println(i);------direct read

public static void main(String[] args) {


m1();

System.out.println("main");
}

public static void m1() {


System.out.println(j);-----indirect read
}

static int j = 20;


}

Output:

0
10
20
Main

4. If a variable is just identified by the JVM and original value


not yet assigned then the variable is said to be in read
indirectly and write only state (RIWO).

5. If a variable is in read indirectly and write only state then we


can’t perform direct read but we can perform indirect read.

6. If we are trying to read directly then we will get compile time


error saying: illegal forward reference.

package pack5;

public class Base {

static int i = 10;

static {

System.out.println(i);
}
}

Error: NoSuchMethodError: Main (error by java 1.6)

package pack5;
public class Base {

static {

System.out.println(i);
}

static int i = 10;

Error: illegal forward reference (error by java 1.6)

package pack5;

public class Base {

static {
m1();
}

public static void m1() {


System.out.println(i);
}

static int i = 10;

Error: NoSuchMethodError: Main (error by java 1.6)


Static block:
1. Static block will be executed at the time of class loading. Hence
at the time of class loading if we want to perform any activity,
we have to define that inside static block.

Example1:

At the time class loading the corresponding native library should be


loaded. Hence we have to define this activity inside static block.

package pack5;

public class Base {

static {

System.loadLibrary("native library part");

}
}

Example2:

After loading every database driver class, we have to register driver


class with driver manager. But inside database driver class there is a
static block to perform this activity and we are not responsible to
register explicitly.

package pack5;

public class DbDriver {

static {

register this driver with driver manager

}
}

Note:

Within a class we can declare any number of static blocks but all
these static will be executed from top to bottom.
Q; Without writing main method is it possible to print some statements
to the consol?

Yes, by using static block.

package pack5;

public class Test {

static {

System.out.println("Hello i can print...");


System.exit(0);

}
} java 1.6

package pack5;

public class Test {

static int x = m1();

public static int m1() {

System.out.println("Hello i can print...");


System.exit(0);
return 10;

}
}

To be continued
Constructors:
1. Once we creates an object, compulsory we should perform initialization
then only the object is in a position to respond properly.
2. Whenever we are creating an object some piece of the code will be
executed automatically to perform initialization. This piece is nothing
but constructor. Hence the main purpose of constructor is to perform
initialization of an object.

Example: if we want to create 100 Student object with their name and roll
number.

package pack5;

public class Student {

String name;
int rollNo;

Student (String name, int rollNo) {


this.name = name;
System.out.println(this.name);

this.rollNo = rollNo;
System.out.println(this.rollNo);
}

public static void main(String[] args) {


Student s = new Student("lalit", 101);------lalit, 101

Student s1 = new Student("Amit", 102);-------Amit, 102

Student s2 = new Student("Rishab", 103);------Rishab, 103


}
}

We can initialize the object at the time of declaration and in the


instance block but every property will load in every created object
and every object property will be same. It is not a good way to
initialize any object.
package pack5;

public class Student {

String student1 = "lalit";


int rollNo1 = 101;

String student2 = "Amit";


int rollNo2 = 102;

String student3 = "Rishab";


int rollNo3 = 103;

public static void main(String[] args) {


Student s1 = new Student();
System.out.println(s1.student1);
System.out.println(s1.rollNo1);
System.out.println(s1.student2);
System.out.println(s1.rollNo2);
System.out.println(s1.student3);
System.out.println(s1.rollNo3);

Student s2 = new Student();


System.out.println(s2.student1);
System.out.println(s2.rollNo1);
System.out.println(s2.student2);
System.out.println(s2.rollNo2);
System.out.println(s2.student3);
System.out.println(s2.rollNo3);

Student s3 = new Student();


System.out.println(s3.student1);
System.out.println(s3.rollNo1);
System.out.println(s3.student2);
System.out.println(s3.rollNo2);
System.out.println(s3.student3);
System.out.println(s3.rollNo3);
}
}
The main purpose of constructor is to perform initialization of an object but
not to create object.

Difference between constructor and instance block:


1. The main purpose of constructor is to perform initialization of an
object.
But other than initialization if we want to perform any activity for
every object creation then we should go for instance block (like
updating one entry in the database for every object creation is
incrementing count value for object creation etc.

2. Both constructor and instance block have their own different purposes
and replacing one concept with another concept may not work always.
3. Both constructor and instance block will be executed for every object
creation but instance block first followed by constructor.

4. Demo program to print number of objects to create for a class.

package pack5;

public class Test {

static int count = 10;


{
count++;
}

Test(){

Test(int x){

Test(double d){

public static void main(String[] args) {


Test t1 = new Test();
Test t2 = new Test(10);
Test t3 = new Test(10.5);
System.out.println("the numeber of objects created" + " " +

count);------13
}

Rules of writing constructors:


1. Name of the class and the name of constructor must be matched.
2. Return type concept not applicable for constructor, even void also.
3. By mistake if we are trying to declare return type for the constructor
then we won’t get any compile time error because compiler treats it as
a method. Hence it legal (but stupid to have a method whose name is
exactly same as class name).

package pack5;

public class Test {

Test(){
System.out.println("constructor");
}

void Test() {
System.out.println("method but not constructor");
}

public static void main(String[] args) {


Test t1 = new Test();-----------------constructor
t1.Test();---------------------method but not constructor

4. The only applicable modifiers for constructors are public, private,


protected and default. If we are trying to use any other modifier, we
will get compile time error.
package pack5;

public class Test {

static Test(){--------------------------Error
System.out.println("constructor");
}

public static void main(String[] args) {


Test t1 = new Test();
t1.Test();--------------------------Error

Compile time error: modifier static is not allowed here

Default constructor:
1. Compiler is responsible to generate default constructor (but not JVM).

2. If we are not writing any constructor then only compiler will generate
default constructor i.e if we are writing at least one constructor then
compiler won’t generate default constructor. Hence every class in java
can contain constructor, it may be default constructor generated by
compiler or customized constructor explicitly provided by programmer
but not both simultaneously.

Prototype of default constructor:


 It is always no-arg constructor.
 The access modifier of default constructor is exactly same as class
(This rule is applicable only for public and default).
 It contains only one line (“super();”). It is a no argument call to
super class constructor.

Programmer’s code: Compiler’s code:

when programmer doesn’t know about Compiler add automatically a default


constructor or doesn’t create any constructor to the class
constructor in class
1. package pack5; 1. package pack5;

class Test { class Test {

Test(){
} super();
}
}

2. package pack5; 2. package pack5;

public class Test { public class Test {

Test(){ public Test(){


super(); super();
} }
} }

3. package pack5; 3. package pack5;

public class Test { public class Test {

void Test() { public Test() {


super();
} }
} void Test() {

}
}

Programmer’s code: Compiler’s code:

when programmer know about Compiler add automatically a default


constructor but doesn’t create fully constructor to the class
package pack5; package pack5;
class Test { class Test {

Test(){ Test(){
super();
} }

} }

package pack5; package pack5;

class Test { class Test {

Test(int i){ Test(int i){


super();
} }

} }

package pack5; package pack5;

class Test { class Test {

Test(){ Test(){
this(10); this(10);
} }

Test(){ Test(){
super();
} }

} }

 The first line inside every constructor should be either super() or


this() and if we are not writing anything then compiler will always
place super().

Case1:

We can take super() or this() only in first line of constructor. If we are


trying to take anywhere else we will get compile time error.

package pack5;
class Test {

Test(){
System.out.println("constructor");
super();---------------------------------Error
}

Compile time error: call to super() must be 1st statement in


constructor.

Case2:

Within the constructor we can either super() or this() but not both
simultaneously.

package pack5;

class Test {

Test(){
super();
this();---------------------------------Error
}

}
Compile time error: call to this() must be 1st statement in
constructor.

Case3:

We can use super() or this() only inside in constructor but not inside
method. If we are trying to use outside of constructor we will get compile
time error.

We can call a constructor directly from another constructor only.


package pack5;

class Test {

public void Test(){---------------------------------Error


super();---------------------------------------Error
System.out.println("Hello");
}

Compile time error: call to super() must be 1st statement in


constructor.

Super(), this() Super, this


 These are constructor calls to  These are keywords to refer
call super (parent) class and super class and current class
current class constructor. instance member.
 We can use only in constructors  We can use anywhere except
as 1st line. static are including main
method.
 We can use these only once in  We can use these any number of
constructor. times.

Overloaded constructor:
1. Within a class we can declare multiple constructors and all these,
constructor having same name but different type of argument. Hence all
these, constructor are considered as overloaded constructors. Hence
overloading concept applicable for constructors.
package pack5;

class Test {

Test() {
this(10);
System.out.println("no-arg");
}

Test(int i){
this(10.5);
System.out.println(i);
}

Test(double d){
System.out.println(d);
}

public static void main(String[] args) {


Test t1 = new Test();-----------------10.5, 10, no-arg

System.out.println();

Test t2 = new Test(20);----------------10.5, 20

System.out.println();

Test t3 = new Test(20.5);-----------20.5

System.out.println();

Test t4 = new Test(30l);----------20.5 (automatic promotion)


}

2. For constructors inheritance and overriding concepts are not applicable


but overloading concept is applicable.

package pack6;

public class Child extends Parent {


Child (){
super(10);
System.out.println("child constructor");
}

public static void main(String[] args) {


Child c = new Child();
}
}

Output:

parent constructor
child constructor

3. Every class in java including abstract class can contain constructor


but interface cannot contain constructor because interface doesn’t
contain instance variables.

package pack5;

class Test {

Test() {

package pack5;

abstract class Test {

Test() {

}
}

package pack5;

interface Test {

Test() {-------------------Error

Case1:

Recursive method call is run time exception saying stack overflow error.

But in our program if there is a chance of recursive constructor invocation


then the code won’t compile and we will get compile time error.

In recursive method call case when we don’t call any method in main method:

package pack5;

public class Test {

public static void m1() {


m2();
}

public static void m2() {


m1();
}

public static void main(String[] args) {


System.out.println("Hello");----------Hello
}

}
In recursive method call case when we call any method in main method:

package pack5;

public class Test {

public static void m1() {


m2();
}

public static void m2() {


m1();
}

public static void main(String[] args) {

m1();------------Run time error but Stack overflow exception

System.out.println("Hello");
}

Stack overflow Exception

Infinite time
M2() method
M1() method
M2() method
M1() method
M2() method
M1() method
Main method

In recursive constructor invocation case when we don’t create any object in


main method:

package pack5;

public class Test {

Test(){
this(10);-----------compile time error
}

Test(int i){
this();-----------compile time error
}

public static void main(String[] args) {


System.out.println("Hello");-------------Hello
}

In recursive constructor invocation case when we create any object in main


method:

package pack5;

public class Test {

Test(){
this(10);
}

Test(int i){
this();
}

public static void main(String[] args) {


Test t = new Test();
System.out.println("Hello");
}

Compile time error: Recursive constructor invocation Test(int)


Recursive constructor invocation Test()

Case2:

Example1:

package pack6;

public class Parent {


Parent(){
super();-->

Default parent constructor created automatically by compiler in parent


class and here super constructor with no argument call parent’s parent
(object class) constructor. That means object constructor should be
with no arguments

package pack6;

public class Child extends Parent {

Child(){
super();
}
}

Default child constructor created automatically by compiler in child


class and here super constructor with no argument call child’s parent
(parent class) constructor. That means parent constructor should be
with no arguments.

Example2:

package pack6;

public class Parent {

Parent(){
super();

Default parent constructor is not created by compiler. It is created


by programmer but in default parent constructor super() constructor
with no argument automatically created by compiler. Here super()
constructor with no argument call parent’s parent (object class)
constructor. That means object constructor should be with no
arguments.

package pack6;

public class Child extends Parent {

Child(){

super();
}
}

Default child constructor is not created by compiler. It is created by


programmer but in default child constructor super() constructor with
no argument automatically created by compiler. Here super()
constructor with no argument call child’s parent (parent class)
constructor. That means parent constructor should be with no
arguments.

Example3:

package pack6;

public class Parent {

Parent(int i){
super();
}

Parent constructor with int type argument is created by programmer but


in parent constructor with int type argument super() constructor with
no argument automatically created by compiler. Here super()
constructor with no argument call parent’s parent (object class)
constructor. That means object constructor should be with no
arguments.

package pack6;

public class Child extends Parent {

Child(){
super();
}
}

Default child constructor created automatically by compiler in child


class and here super constructor with no argument call child’s parent
(parent class) constructor. That means parent constructor should be
with no arguments. But in this program parent construct has argument
type so super() constructor should be same argument type value as
parent constructor, otherwise we will get compile time error saying
cannot find symbol, symbol: constructor Parent(), location: class
Parent.

Note:

 If parent class contains any argument constructor then while


writing child classes we have to take special care with respect
to constructors.

 Whenever we are writing any argument constructor it is highly


recommended to write no arg constructor also.
package pack6;

public class Parent {

Parent(){
super();
}

Parent(int i){
super();
}

Here both constructor created by programmer.

package pack6;

public class Child extends Parent {

Child(){
super();
}
}

Default child constructor created automatically by compiler in child


class and here super constructor with no argument call child’s parent
(parent class) constructor. That means parent constructor should be
with no arguments.

Case3:

Example1:

package pack6;

import java.io.IOException;
public class Parent {

Parent() throws IOException{

super();-----created by compiler by default


}

package pack6;

public class Child extends Parent {

Child(){ Default constructor created by compiler


super();-------------Error
}
}

Compile time error: unreported exception java.IO.IOException in


default constructor

Example2:

package pack6;

import java.io.IOException;

public class Parent {

Parent() throws IOException{

super();-----created by compiler by default


}

package pack6;

public class Child extends Parent {

Child(){
try {
super();---------------Error
} catch (Exception e) {
// TODO: handle exception
}

}
}

Here we are trying to handle exception by try-catch block in default


constructor which is created by programmer. But we are getting compile
time error because after constructor 1 st line can only super() or
this(), but here 1st line/statement after constructor is try.

So we can solve this problem by handling the exception only by caller


constructor. It is only solution in the cases of constructor.

package pack6;

import java.io.IOException;

public class Parent {

Parent() throws IOException{


super();
}

package pack6;

import java.io.IOException;

public class Child extends Parent {

Child() throws IOException{


super();
}
}

OR
package pack6;

public class Child extends Parent {


Child() throws Exception{
super();
}
}

OR
package pack6;

public class Child extends Parent {

Child() throws Throwable{


super();
}
}

Note:

If parent class constructor throws any checked exception, compulsory


child class constructor should throw the same checked exception or its
parent, otherwise the code won’t compile.

Which of the following statement is valid?

a) The main purpose of constructor is to create an object. (false)

Answer:
The main purpose of constructor is to perform initialization of an
object.
b) The main purpose of constructor is to perform initialization of an
object. (true)

c) The name of the constructor need not be same as class name. (false)

Answer:
The name of the constructor need be same as class name

d) Return type concept applicable for constructors but only void. (false)

Answer:
Return type concept not applicable for constructors, even void
also.

e) We can apply any modifier for constructor. (false)

Answer:
We can apply only public, private, protected modifier.

f) Default constructor generated by JVM. (false)

Answer:
Default constructor generated by compiler.

g) Compiler is responsible to generate default constructor. (true)

h) Compiler will always generate default constructor. (false)

Answer:
Compiler will not always generate default constructor
(When programmers are create default constructor).

i) If we are writing no-arg constructor then compiler will generate


default constructor. (false)

Answer:
If we are writing no-arg constructor then compiler will not
generate default constructor

j) Every no argument constructor is always default constructor. (false)

Answer:
Every no argument constructor is always default constructor.
(When programmer create no argument constructor then it is not a
default constructor).
k) Default constructor is always no-arg constructor. (true)

l) The 1st line inside every constructor should be either super() or


this(). If we are not writing anything then compiler will generates
this(). (false)

Answer:
The 1st line inside every constructor should be either super()
or this(). If we are not writing anything then compiler will
generate super().

m) For constructor both overloading and overriding concepts are


applicable. (false)

Answer:
For constructor both overloading and overriding concepts are not
applicable.

n) For constructor inheritance concept is applicable but not overriding.


(false)

Answer:
For constructor inheritance concept is not applicable.

o) Only concrete classes can contain constructor but abstract classes


cannot. (false)

Answer:
Concrete classes and abstract classes both can contain
constructors.

p) Interface can contain constructors. (false)

Answer:
Interface cannot contain constructors.

q) Recursive constructor invocation is a run time exception. (false)

Answer:
Recursive constructor invocation is a compile time exception.

r) If parent class constructor throws some checked exception then


compulsory child class constructor should throw the same checked
exception or its child. (false).
Answer:
If parent class constructor throws some checked exception then
compulsory child class constructor should throw the same checked
exception or its parent.

You might also like