Object Oriented Programming (OOPS)

1.Data Hiding

1.Our internal data should not go out directly that is outside person can’t access
our internal data directly.
2.By using private modifier we can implement data hiding.

Example:
class Account {
private double balance;

After providing proper username and password only , we can access our Account
information.

The main advantage of data hiding is security.
Note: recommended modifier for data members is private.

2.Abstraction

1.Hide internal implementation and just highlight the set of services, is called
abstraction.

2.By using abstract classes and interfaces we can implement abstraction.

Example :

By using ATM GUI screen bank people are highlighting the set of services what they
are offering without highlighting internal implementation.

The main advantages of Abstraction are:

  1. We can achieve security as we are not highlighting our internal
    implementation.(i.e., outside person doesn’t aware our internal implementation.)
    Enhancement will become very easy because without effecting end user we can
    able to perform any type of changes in our internal system.

It provides more flexibility to the end user to use system very easily.

It improves maintainability of the application.

It improves modularity of the application.

It improves easyness to use our system.

By using interfaces (GUI screens) we can implement abstraction

3.Encapsulation

1.Binding of data and corresponding methods into a single unit is called
Encapsulation .

2.If any java class follows data hiding and abstraction such type of class is said to
be encapsulated class.

3.Encapsulation=Data hiding + Abstraction
Example:

class Account

welcome to VBR Bank {
private double balance;
getBalance > public double getBalance()
{
//validate user
return balance;
Public void setBalance(double balance)
setBalance //validate user
this.balance=balance;
GUI }

Every data member should be declared as private and for every member we have to
maintain getter & Setter methods.

The main advantages of encapsulation are :

We can achieve security.

Enhancement will become very easy.

It improves maintainability and modularity of the application.
It provides flexibility to the user to use system very easily.

The main disadvantage of encapsulation is it increases length of the code and slows
down execution.

3.Tightly encapsulated class :

A class is said to be tightly encapsulated if and only if every variable of that class
declared as private whether the variable has getter and setter methods are not , and

whether these methods declared as public or not, these checkings are not required to
perform.

Example:
class Account {
private double balance;
public double getBalance () {
return balance;

}
}

Which of the following classes are tightly encapsulated?
class A

{
private int x=10; (valid)
}

class B extends A

{
int y=20; (invalid)
}

class C extends A

{
private int z=30; (valid)
}

Which of the following classes are tightly encapsulated?
class A {

int x=10; //not
}
class B extends A {

private int y=20; //not
}
class C extends B {

private int z=30; //not
}

Note: if the parent class is not tightly encapsulated then no child class is tightly
encapsulated.

IS-A Relationship(inheritance) :

  1. Also known as inheritance.
  2. By using “extends” keywords we can implement IS-A relationship.
  3. The main advantage of IS-A relationship is reusability.

Example:
class Parent {
public void methodOne(){ }
}
class Child extends Parent {
public void methodTwo() { }
}

class Test
{
public static void main(String[] args)
{
Parent p=new Parent(); C.E: cannot find symbol
p.methodOne(); symbol : method methodTwo()
p.methodTwo(); location: class Parent
Child c=new Child();
c.methodOne();
c.methodTwo();
Parent p1=new Child();
p1.methodOne(); C.E: incompatible types
p1.methodTwo(); found : Parent
Child cl=new Parent();—— 7 required: Child
}

Conclusion :

  1. Whatever the parent has by default available to the child but whatever the child
    has by default not available to the parent. Hence on the child reference we can
    call both parent and child class methods. But on the parent reference we can call
    only methods available in the parent class and we can’t call child specific
    methods.
  2. Parent class reference can be used to hold child class object but by using that
    reference we can call only methods available in parent class and child specific
    methods we can’t call.
  3. Child class reference cannot be used to hold parent class object.

Example:

The common methods which are required for housing loan, vehicle loan, personal loan
and education loan we can define into a separate class in parent class loan. So that
automatically these methods are available to every child loan class.

Example:
class Loan {

//common methods which are required for any type of loan.
}
class HousingLoan extends Loan {
//Housing loan specific methods.
}
class EducationLoan extends Loan {
//Education Loan specific methods.

}

e For all java classes the most commonly required functionality is define inside
object class hence object class acts as a root for all java classes.

¢ For all java exceptions and errors the most common required functionality
defines inside Throwable class hence Throwable class acts as a root for exception
hierarchy.

Diagram:
Object

SUring-..sesseceresesesrenseesseeneeses Number Throwable

Byte short Integer Long Float Double

Exception Error

Multiple inheritance :
Having more than one Parent class at the same level is called multiple inheritance.

Example:

Parent1 Parent2

Child

Any class can extends only one class at a time and can’t extends more than one class
simultaneously hence java won’t provide support for multiple inheritance.

Example:

class A{}

class B{} (invalid)
class C extends A,B

But an interface can extends any no. Of interfaces at a time hence java provides support
for multiple inheritance through interfaces.

Example:

interface A{}
interface B{}
interface C extends A,B{}

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

Example:

class A{} Object

If our class extends any other class then our class is not direct child class of object, It is
indirect child class of object , which forms multilevel inheritance.

Example 1:
class B{} Object
class A extends B{} I\

I Multilevel inheritance

(valid)

Example 2:

Object B

\/

(invalid)
Why java won’t provide support for multiple inheritance?

There may be a chance of raising ambiguity problems.

Example:
Parentl——> methodOne() Parent2 > methodOne()

c.methodOne(); ———> Ambiguity problem.

Why ambiguity problem won’t be there in interfaces?

Interfaces having dummy declarations and they won’t have implementations hence no
ambiguity problem.

Example:
interface inter1 interface inter2
{ {
public void methodOne(); public void methodOne();
} t

eae

interface inter3 extends inter1,inter2{}

{

class Test implements inter3

public void methodOne()
{

System.out.printIn(“This is methodOne()”);

Cyclic inheritance :

Cyclic inheritance is not allowed in java.

Example 1:

B
class A extends B{} |(invalid)
class B extends A{} /C.E:cyclic inheritance involving A

A

Example 2:

class A extends A{} GES cyclic inheritance involving A

HAS-A relationship is also known as composition (or) aggregation.

  1. There is no specific keyword to implement HAS-A relationship but mostly we
    can use new operator.
  2. The main advantage of HAS-A relationship is reusability.

=

Example:
class Engine
{
/fengine specific functionality
}
class Car

{

Engine e=new Engine() ;

ne i
ne i
ne i

e class Car HAS-A engine reference.
e The main dis-advantage of HAS-A relationship increases dependency between
the components and creates maintains problems.

Composition vs Aggregation:

Composition:

Without existing container object if there is no chance of existing contained objects then
the relationship between container object and contained object is called composition
which is a strong association.

Example:

University consists of several departments whenever university object destroys
automatically all the department objects will be destroyed that is without existing
university object there is no chance of existing dependent object hence these are

strongly associated and this relationship is called composition.

Example:

department1 department2
Contained Object

department3 department4 Container Object

Aggregation :

Without existing container object if there is a chance of existing contained objects such
type of relationship is called aggregation. In aggregation objects have weak association.

Example:

Within a department there may be a chance of several professors will work whenever
we are closing department still there may be a chance of existing professor object
without existing department object the relationship between department and professor
is called aggregation where the objects having weak association.

Example:
(pi) Contained object
| Container object
Department
Note :

In composition container , contained objects are strongly associated, and but container
object holds contained objects directly

But in Aggregation container and contained objects are weakly associated and
container object just now holds the reference of contained objects.

Method signature:

In java, method signature consists of name of the method followed by argument types.

Example:

public void methodOne(int i,float f);

methodOne(int,float);

e In java return type is not part of the method signature.
e Compiler will use method signature while resolving method calls,

class Test {
public void ml(double d) { }
public void m2(int i) { }
public static void main(String ar[]) {
Test t=new Test();
t.m1(10.5);
t.m2(10);
t.m3(10.5); //CE
}
}
CE : cannot find symbol
symbol : method m3 (double)
location : class Test

Within the same class we can’t take 2 methods with the same signature otherwise we
will get compile time error.

Example:

public void methodOne() { }

public int methodOne () {
return 10;

}

Output:

Compile time error

methodOne() is already defined in Test

Polymorphism:

Same name with different forms is the concept of polymorphism.
Example 1: We can use same abs() method for int type, long type, float type etc.
Example:

  1. abs(int)
  2. abs(long)
  3. abs(float)

Example 2:
We can use the parent reference to hold any child objects.

We can use the same List reference to hold ArrayList object, LinkedList object, Vector
object, or Stack object.

Example:

List =new Array ListQ;
List new LinkedListQ;
List =new VectorQ;
List new StackQ;

Diagram:

Polymorphism

Compiletime/static/earlybinding Runtime/dynamic/latebinding

overloading method hiding overriding

Diagram: 3 Pillars of OOPS

Reusability

Flexibility
Polymorphism

1) Inheritance talks about reusability.
2) Polymorphism talks about flexibility.
3) Encapsulation talks about security.

Security

Encapsulation

Beautiful definition of polymorphism:

A boy starts love with the word friendship, but girl ends love with the same word
friendship, word is the same but with different attitudes. This concept is nothing but

polymorphism.

Overloading :

  1. Two methods are said to be overload if and only if both having the same name
    but different argument types.
  2. In ‘C’ language we can’t take 2 methods with the same name and different types.
    If there is a change in argument type compulsory we should go for new method
    name.

Example :

abs() ————for int type
labs() ————for long type

fabs() ———for float type

etc

  1. Lack of overloading in “C” increases complexity of the programming.
    4, But in java we can take multiple methods with the same name and different
    argument types.

Example:
abs(int)
abs(long)
abs(float)

  1. Having the same name and different argument types is called method
    overloading.
  2. All these methods are considered as overloaded methods.
  3. Having overloading concept in java reduces complexity of the programming.
  4. Example:
  5. class Test {
  6. public void methodOne() {
  7. System. out.println(“no-arg method”) ;
  8. }
  9. public void methodOne (int i) {
  10. System.out.println(“int-arg method”); //overloaded methods
  11. }
  12. public void methodOne(double d) {
  13. System. out.printin(“double-arg method”) ;
  14. }
  15. public static void main(String[] args) {
  16. Test t=new.Test();
  17. t.methodOne().;//no-arg method
  18. t.methodOne(10).;//int-arg method
  19. t.methodOne (10.5) ;//double-arg method
  20. }
  21. }
  22. Conclusion ; In overloading compiler is responsible to perform method
    resolution(decision) based on the reference type(but not based on run time
    object). Hence overloading is also considered as compile time polymorphism(or)
    static polymorphism (or)early biding.

Case 1: Automatic promotion in overloading.

¢ In overloading if compiler is unable to find the method with exact match we
won’t get any compile time error immediately.

e 1st compiler promotes the argument to the next level and checks whether the
matched method is available or not if it is available then that method will be
considered if it is not available then compiler promotes the argument 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. This
process is called automatic promotion in overloading.

The following are various possible automatic promotions in overloading.

Diagram :

byte——> sho MN

int —> long ——> float ——»>double
char

Example:

class Test

{
public void methodOne (int i)
{

System. out.printin(“int-arg method”) ;
}

public void methodOne (float f) //foverloaded methods
{

System. out.printlin(“float-arg method”) ;

}

public static void main(String[] args)

{
Test t=new Test();
//t.methodOne(‘a’) ;//int-arg method
//t.methodOne (101) ;//float-arg method
t.methodOne (10.5) ;//C.E:cannot find symbol

}

Case 2:
class Test
{
public void methodOne (String s)
{
System. out.printlin (“String version”) ;

}
public void methodOne (Object 0) //Both methods are said to

//be

overloaded methods.

{

System. out.printlin (“Object version”) ;

}

public static void main(String[] args)

{
Test t=new Test();
t.methodOne (“arun”) ;//String version
t.methodOne (new Object()) ;//Object version
t.methodOne (null) ;//String version

Note:

While resolving overloaded methods exact match will always get high priority,

While resolving overloaded methods child class will get the more priority than parent
class

Case 3:
class Test{
public void methodOne (String s) {
System. out.printlin (“String version”) ;
}
public void methodOne (StringBuffer s) {
System. out.printlin (“StringBuffer version” ) ;
}
public static void main(String[].. args) {
Test t=new Test();
t.methodOne (“arun”) ;//String version
t.methodOne (new StringBuffer (“sai”));//StringBuffer version
t.methodOne (null) ;//CE : reference to m1() is ambiquous
}
}

Output:

Object

String StringBuffer

Case 4:
class Test {
public void methodOne(int i,float f) {
System. out.printlin(“int-float method”) ;
}
public void methodOne (float f,int i) {
System. out.printlin(“float-int method”) ;
}
public static void main(String[] args) {
Test t=new Test();
t.methodOne(10,10.5f£) ;//int-float method
t.methodOne(10.5£,10) ;//float-int method
t.methodOne (10,10); //C.E:
//CE:reference to methodOne is ambiguous,
//poth method methodOne(int,float) in Test

//and method methodOne(float,int) in Test match
t.methodOne(10.5£,10.5f£) ;//C.E:
cannot find symbol
symbol : methodOne(float, float)
location : class Test

}

Case 5:
class Test{
public void methodOne (int i) {

System. out.println(“general method”) ;
}
public void methodOne(int…i) {
System. out.printlin(“var-arg method”) ;
}
public static void main(String[] args) {
Test t=new Test();
t.methodOne() ;//var-arg method
t.methodOne (10,20) ;//var-arg method
t.methodOne (10) ;//general method

In general var-arg method will get less priority that is if no other method matched then
only var-arg method will get chance for execution it is almost same as default case inside
switch.

Case 6:
class Animal{ }
class Monkey extends Animal {}
class Test{
public void methodOne (Animal a) {
System. out.println (“Animal version”) ;
}
public void methodOne (Monkey m) {
System. out.printin (“Monkey version”) ;
}
public static void main(String[] args) {
Test t=new Test();
Animal a=new Animal () ;
t.methodOne (a) ;//Animal version
Monkey m=new Monkey () ;
t.methodOne (m) ;//Monkey version
Animal al=new Monkey () ;
t.methodOne (al) ;//Animal version

In overloading method resolution is always based on reference type and runtime object
won’t play any role in overloading.

  1. Whatever the Parent has by default available to the Child through inheritance, if
    the Child is not satisfied with Parent class method implementation then Child is

allow to redefine that Parent class method in Child class in its own way this
process is called overriding.

The Parent class method which is overridden is called overridden method.
The Child class method which is overriding is called overriding method.

Example 1:

class Parent {
public void property () {
System. out.println (“cashtland+gold”) ;
}

public void marry () {
System.out.printin(“subbalakshmi”); //overridden
method
}
}
class Child extends Parent{ //overriding

public void marry () {
System. out. printl1n(“3sha/4me/9tara/anushka’ ) ;
//overriding method
}
}

class Test {
public static void main(String[] args) {
Parent p=new Parent();
p-marry() ;//subbalakshmi (parent method)
Child c=new Child();
c.marry() ;//Trisha/nayanatara/anushka (child method)
Parent pl=new Child();
pl.marry() ;//Trisha/nayanatara/anushka (child method)
}
}

In overriding method resolution is always takes care by JVM based on runtime
object hence overriding is also considered as runtime polymorphism or dynamic
polymorphism or late binding.

The process of overriding method resolution is also known as dynamic method
dispatch.

Note: In overriding runtime object will play the role and reference type is dummy.

Rules for overriding :

  1. In overriding method names and arguments must be same. That is method
    signature must be same.
  2. Until 1.4 version the return types must be same but from 1.5 version onwards co-
    variant return types are allowed.
  3. According to this Child class method return type need not be same as Parent
    class method return type its Child types also allowed.
  4. Example:
  5. class Parent {
  6. public Object methodOne () {
  7. return null;
  8. }
  9. }
  10. class Child extends Parent {
  11. public String methodOne() {
  12. return null;
  13. }
  14. }
  15. C:> javac -source 1.4 Parent.java //error
    It is valid in “1.5” but invalid in “1.4”.

Diagram:
Parent method : Object Number String double
return type
Child method: String Integer Object int

return type Sf JS Xx Xx

Co-variant return type concept is applicable only for object types but not for
primitives.

Private methods are not visible in the Child classes hence overriding concept is not applicable for
private methods. Based on own requirement we can declare the same Parent class private method
in child class also. It is valid but not overriding.

Example:

class Parent

{

private void methodOne()

t}

it is valid but not overriding.

class Child extends Parent

{

private void methodOne()

t

Parent class final methods we can’t override in the Child class.

  1. Example:
  2. class Parent {
  3. public final void methodOne() {}
  4. }
  5. class Child extends Parent{
  6. public void methodOne() {}
  7. }
  8. Output:
  1. Compile time error:
  2. methodOne() in Child cannot override methodOne ()
  3. in Parent; overridden method is final

Parent class non final methods we can override as final in child class. We can
override native methods in the child classes.

  1. We should override Parent class abstract methods in Child classes to provide

implementation.

  1. Example:
  2. abstract class Parent {
  3. public abstract void methodOne() ;
  4. }
  5. class Child extends Parent {
  6. public void methodOne() { }
  7. }
    Diagram:
    abstract

overriding is possible.

  1. We can override a non-abstract method as abstract
    this approach is helpful to stop availability of Parent method implementation to
    the next level child classes.
  2. Example:
  3. class Parent {
  1. public void methodOne () { }
  2. }
  3. abstract class Child extends Parent {
  4. public abstract void methodOne() ;
  5. }

Synchronized, strictfp, modifiers won’t keep any restrictions on overriding.

Diagram:

final nonfinal native abstract «Synchronized strietf

noninal final nonnative nonastract nonSyncronzed.nonstrt

44, While overriding we can’t reduce the scope of access modifier.

  1. Example:
  2. class Parent {

Al. public void methodOne() { }

  1. }
  2. class Child extends Parent {
  3. protected void methodOne( ) { }
  4. }
  5. Output:
  6. Compile time error :
  7. methodOne() in Child cannot override methodOne() in Parent;
  8. attempting to assign weaker access privileges; was public

Diagram:

public protected © defaults private

public protected/public <default»/protected/public overriding concent

vov V is not applicable
X

[private < default < protected < public|

Checked Vs Un-checked Exceptions :

e The exceptions which are checked by the compiler for smooth execution of the
program at runtime are called checked exceptions.
e The exceptions which are not checked by the compiler are called un-checked

exceptions.
¢ RuntimeException and its child classes, Error and its child classes are unchecked

except these the remaining are checked exceptions.

Exception Error
L serenneee LinkageError

RuntimeException lOException SQLException ServietException |. AssertionError

VirtualMachinegrror

EOFException

ArithmeticException

NullPointerException ree oune ception VerifyError
IndexOutOfBoundsException nkerrupre xception
ArrayIndexOutOfBoundsException OutOfMemoryError StackOverflowError

StringlndexOutOfBoundsException
IllegalArgumentException

|___umberFormatexception
ClassCastException

IllegalStateException

Rule: While overriding if the child class method throws any checked exception
compulsory the parent class method should throw the same checked exception or its
parent otherwise we will get compile time error.

But there are no restrictions for un-checked exceptions.

Example:
class Parent {

public void methodOne() {}
}
class Child extends Parent{
public void methodOne()throws Exception {}

}

Output:

Compile time error :

methodOne() in Child cannot override methodOne() in Parent;
overridden method does not throw java.lang.Exception

Examples :

@) Parent: public void methodOne()throws Exception ;
Child: public void methodOne() valid

@ Parent: public void methodOne() invalid
Child : public void methodOne()throws Exception
G) Parent: public void methodOne()throws Exception

Child: public void methodOne()throws Exception valid

(4) Parent: public void methodOne()throws IOException ; ;
Child: public void methodOne()throws Exception jinvata

6 Parent: public void methodOne()throws IOException valid
Child: public void methodOne()throws EOFException,FileNotFoundException

©) Parent: public void methodOne()throws IOException

invalid

Child : public void methodOne(}throws EOFException,InterruptedException |

3) Parent: public void methodOne()throws IOException | valid
Child: public void methodOne()throws EOFException,ArithmeticException

Parent: public void methodOne()
Child: public void methodOne()throws | valid
ArithmeticException,NullPointerException,ClassCastException, RuntimeException

Overriding with respect to static methods:
Case 1:

We can’t override a static method as non static.

Example:
class Parent

{
public static void methodOne() {}
//here static methodOne() method is a class level

}

class Child extends Parent

{

public void methodOne() {}

//here methodOne() method is a object level hence
// we can’t override methodOne() method

}

output :;
CE: methodOne in Child can’t override methodOne() in Parent ;
overriden method is static

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

Case 3:

class Parent

{
public static void methodOne() {}

}
class Child extends Parent {
public static void methodOne() {}

}

It is valid. It seems to be overriding concept is applicable for static methods but it is not
overriding it is method hiding.

METHOD HIDING :

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

Overriding Method hiding

  1. Both Parent and Child class methods 1. Both Parent and Child class methods
    should be non static. should be static.
  2. Method resolution is always takes care |2. Method resolution is always takes care by
    by JVM based on runtime object. compiler based on reference type.
  1. Overriding is also considered as 3. Method hiding is also considered as
    runtime polymorphism (or) dynamic compile time polymorphism (or) static
    polymorphism (or) late binding. polymorphism (or) early biding.
    Example:

class Parent {
public static void methodOne() {
System.out.println(“parent class”);
}

}
class Child extends Parent{
public static void methodOne() {
System.out.println(“child class”) ;
}
}
class Test{
public static void main(String[] args) {
Parent p=new Parent ();
p-methodOne();//parent class
Child c=new Child();
c.methodOne();//child class
Parent pl=new Child();
pl.methodOne();//parent class

Note: If both Parent and Child class methods are non static then it will become
overriding and method resolution is based on runtime object. In this case the output is

Parent class
Child class
Child class

Overriding with respect to Var-arg methods:

A var-arg method should be overridden with var-arg method only. If we are trying to
override with normal method then it will become overloading but not overriding.

Example:
class Parent. {
public void methodOne (int… i){

System.out.println(“parent class”) ;

}

}

class Child extends Parent { //overloading but not overriding.
public void methodOne(int i) {
System.out.println(“child class”) ;

}

}

class Test {

public static void main(String[] args) {
Parent p=new Parent();

p-methodOne(10) ;//parent class

Child c=new Child() ;

c.methodOne(10) ;//child class

Parent pl=new Child();
pl.methodOne (10) ;//parent class

In the above program if we replace child class method with var arg then it will become
overriding. In this case the output is

Parent class
Child class
Child class

Overriding with respect to variables:

Overriding concept is not applicable for variables.
Variable resolution is always takes care by compiler based on reference type.

Example:
class Parent
{
int x=888;
}
class Child extends Parent
{
int x=999;
}
class Test
{
public static void main(String[] args)
{
Parent p=new Parent ();
System. out.println(p.x) ;//888
Child c=new Child();
System.out.println(c.x) ;//999
Parent pl=new Child();
System. out.println(p1.x) ;//888

Note: In the above program Parent and Child class variables, whether both are static or
non static whether one is static and the other one is non static there is no change in the
answer.

Differences between overloading and overriding ?

Property
1) Method
names

2) Argument
type

3) Method
signature
4) Return
types

5) private,
static, final
methods

6) Access
modifiers

7) Throws
clause

8) Method
resolution

9) Also
known as

Note:

Overloading
Must be same.

Must be different(at
least order)

Must be different.

No restrictions.

Can be overloaded.

No restrictions.

No restrictions.

Is always takes care
by compiler based on
referenced type.

Compile time
polymorphism (or)
static(or)early
binding.

Overriding

Must be same.
Must be same including order.

Must be same.

Must be same until 1.4v but from 1.5v onwards
we can take co-variant return types also.

Can not be overridden.

Weakering/reducing is not allowed.

If child class method throws any checked
exception compulsory parent class method should
throw the same checked exceptions or its parent
but no restrictions for un-checked exceptions.

Is always takes care by JVM based on runtime
object.

Runtime polymorphism (or) dynamic (or) late
binding.

  1. In overloading we have to check only method names (must be same) and
    arguments (must be different) the remaining things like return type extra not
    required to check.

2, But In overriding we should compulsory check everything like method names,
arguments, return types, throws keyword, modifiers etc.

Consider the method in parent class
Parent: public void methodOne(int ijthrows IOException

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

public void methodOne(int i)//valid(overriding)

private void methodOne(throws Exception//valid(overloading)
public native void method One(int i);//valid(overriding)

public static void methodOne(double d)//valid(overloading)

  1. public static void method One(int i)
    Compile time error :

methodOne(int) in Child cannot override methodOne(int) in Parent; overriding
method is static

  1. public static abstract void methodOne(float f)
    Compile time error :
  2. illegal combination of modifiers: abstract and static
  3. Child is not abstract and does not override abstract method
    methodOne(float) in Child

What is the difference between ArrayList =new ArrayListQ & List /=new ArrayList() ?

ArrayList al=new ArrayListQ); List =new ArrayListQ;
[Child c=new ChildQ3;] [Parent p=new ChildQ;]
If we know runtime object type

exactly then we have to used this
approach

If we don’t know exact Runtime object type then
we have to used this approach

By using parent reference we can call only method
available in parent class and child specific method
we can’t call.

By using child reference we can call
both parent & child calss methods.

e Wecan use ArrayList reference to hold ArrayList object where as we can use
List reference to hold any list implemented class object (ArrayList, LinkedList,
Vector, Stack)

e By using ArrayList reference we can call both List and ArrayList methods but
by using List reference we can call only List interface specific methods and we
can’t call ArrayList specific methods.

IIQ : In how many ways we can create an object ? (or) In
how many ways get an object in java ?

By using new Operator :
Test t = new Test();

By using newInstance() :(Reflection Mechanism)

Test t=(Test)Class.forName (“Test”) .newInstance () ;

By using Clone(Q :

Test tl = new Test();

Test t2 = (Test)t1l.Clone();

By using Factory methods :

. Runtime r = Runtime.getRuntime() ;

  1. DateFormat df = DateFormat.getInstance() ;
  2. By using Deserialization :
  3. FileInputStream fis = new FileInputStream(“abc.ser”) ;
  4. ObjectInputStream ois = new ObjectInputStream (fis) ;
  5. Test t = (Test)ois.readObject();

Constructors :

  1. Object creation is not enough compulsory we should perform initialization then
    only the object is in a position to provide the response properly.
  2. Whenever we are creating an object some piece of the code will be executed
    automatically to perform initialization of an object this piece of the code is
    nothing but constructor.
  3. Hence the main objective of constructor is to perform initialization of an object.

Example:
class. Student
{
String name;
int rollno;
Student (String name,int rollno) //Constructor
{
this .name=name ;
this.rollno=rollno;
}
public static void main(String[] args)
{
Student sl=new Student (“vijayabhaskar” ,101) ;
Student s2=new Student (“bhaskar” ,102) ;

Diagram:

name=bhaskar
rollno=102

name=vijayabhaskar
rollno=101

Constructor Vs instance block:

  1. Both instance block and constructor will be executed automatically for every

object creation but instance block 1st followed by constructor.

The main objective of constructor is to perform initialization of an object.

  1. Other than initialization if we want to perform any activity for every object
    creation we have to define that activity inside instance block.
  2. Both concepts having different purposes hence replacing one concept with
    another concept is not possible.
  3. Constructor can take arguments but instance block can’t take any arguments
    hence we can’t replace constructor concept with instance block.
  4. Similarly we can’t replace instance block purpose with constructor.

Demo program to track no of objects created for a class:
class Test
{
static int count=0;
{
count++; //instance block
}
Test ()
{}
Test(int i)
{}
public static void main(String[] args)
{
Test tl=new Test();
Test t2=new Test(10);
Test t3=new Test();
System. out.println (count) ;//3

Rules to write constructors:

=

Name of the constructor and name of the class must be same.

Return type concept is not applicable for constructor even void also by mistake if
we are declaring the return type for the constructor we won’t get any compile
time error and runtime error compiler simply treats it as a method.

Example:

class Test

{

void Test () //it is not a constructor and it is a method

{}
}

9, It is legal (but stupid) to have a method whose name is exactly same as class
name.

  1. The only applicable modifiers for the constructors are public, default, private,
    protected.
  2. If we are using any other modifier we will get compile time error.

Example:
class Test

{
static Test()

{}

}
Output:
Modifier static not allowed here

Default constructor:

  1. For every class in java including abstract classes. also constructor concept is

applicable.

  1. If we are not writing at least one constructor then compiler will generate default
    constructor.
  2. If we are writing at least one constructor then compiler won’t generate any
    default constructor. Hence every class contains either compiler generated
    constructor (or) programmer written constructor but not both simultaneously.

Prototype of default constructor:

=

It is always no argument constructor.

  1. The access modifier of the default constructor is same as class modifier. (This
    rule is applicable only for public and default).
  2. Default constructor contains only one line. super(Q; it is a no argument call to

super class constructor.

Programmers code

class Test { }

public class Test { }

class Test

{
void Test(){}

}

class Test

Test(int i)
{}

class Test
Test ()

super ();

class Test

Test(int i)
{
this();

Compiler generated code

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

public class Test {
public Test ()
{
super ();
}
}

class Test
{
Test ()
{
super ();

}
void Test()

{}
}

class Test
{
Test (int i)
{
super ();
}
}

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

class Test
{
Test(int i)
{
this ();

super ();

super() vs this():

The 1st line inside every constructor should be either super( or thisQ if we are not
writing anything compiler will always generate super().

Case 1; We have to take super( (or) this() only in the 1st line of constructor. If we are
taking anywhere else we will get compile time error.
Example:
class Test
{
Test ()
{
System. out.println (“constructor”) ;
super ();

}

Output:

Compile time error.

Call to super must be first statement in constructor

Case 2: We can use either super( (or) thisQ) but not both simultaneously.
Example:
class Test
{
Test ()
{
super ();
this ();

}

Output:

Compile time error.

Call to this must be first statement in constructor

Case 3: We can use super() (or) this) only inside constructor. If we are using anywhere
else we will get compile time error.

Example:

class Test

{

public void methodOne ()

{

super ();

}
}
Output:
Compile time error.
Call to super must be first statement in constructor

That is we can call a constructor directly from another constructor only.

1.we should use only in 1st line

  1. only one but not both
  2. only inside constructor

calling another constructor of same class.
calling super class constructor.

Example:

super(0, this super, this

These are constructors calls. These are keywords

We can use these to invoke super class & — |We can use refers parent class and current
current constructors directly class instance members.

We should use only inside constructors as {We can use anywhere (i.e., instance area)
first line, if we are using outside of except static area , other wise we will get
constructor we will get compile time error. |compile time error .

Example:

class Test
{

public static void main(String[] args)

{

System. out.printiln (super. hashCode ());

}
}
Output:
Compile time error.
Non-static variable super cannot be referenced from a static context.

Overloaded constructors :

A class can contain more than one constructor and all these constructors having the
same name but different arguments and hence these constructors are considered as
overloaded constructors.

Example:
class Test {
Test (double d) {
System.out.println(“double-argument constructor” ) ;

}
Test(int i) {
this(10.5);
System. out.println(“int-argument constructor” ) ;

}
Test() {

this (10);
System.out.println(“no-argument constructor”) ;
}
public static void main(String[] args) {
Test tl=new Test(); //no-argument constructor/int-argument

//constructor/double-argument constructor
Test t2=new Test(10) ;

//int-argument constructor/double-argument constructor
Test t3=new Test(10.5) ;//double-argument constructor

Parent class constructor by default won’t available to the Child. Hence
Inheritance concept is not applicable for constructors and hence overriding
concept also not applicable to the constructors. But constructors can be
overloaded.

We can take constructor in any java class including abstract class also but we
can’t take constructor inside interface.

Example:

class Test | abstract class Test | interface Test1

{ { {
Test() Test() Test1()
{} {} {}

} } }

valid valid invalid

We can’t create object for abstract class but abstract class can contain constructor what
is the need ?

Abstract class constructor will be executed for every child class object creation to
perform initialization of child class object only.

Which of the following statement is true ?

  1. Whenever we are creating child class object then automatically parent class
    object will be created.(false)
  2. Whenever we are creating child class object then parent class constructor will be
    executed.(true)

Example:
abstract class Parent
{
Parent ()
{
System. out. printlin(this.hashCode () ) ;
//11394033//here this means child class object
}
}
class .Child.extends Parent
{
Child()
{
System. out.println(this.hashCode() ) ;//11394033
}
}
class Test
{
public static void main(String[] args)
{
Child c=new Child();
System. out.println(c.hashCode()) ;//11394033

}

Case 1: recursive method call is always runtime exception where as recursive
constructor invocation is a compile time error.

Nested call:

e Calling a function inside another function is called nested call.
¢ Innested call there is a calling function which calls another function(called
function).

Example:
public static void methodOne ()

{
methodTwo ();

}
public static void methodTwo ()

{
methodOne () ;

}
Recursive call:

e Calling a function within same function is called recursive call.
e In recursive call called and calling function is same.

Example:
public void methodOne ()

{
methodOne () ;

}

Example:
class Test class Test
{
public static void methodOne() Test(int i)
{
methodTwol(); { this();
} ‘
public static void methodTwo() rest)
{ {
methodOne(); this(10):
} |
public static void main(String[] args) public static void main(String|[] args)
{ {
methodOne(); System.out.printin(“hello”);
System.out.printin(“hello”); }
} } C.E:recursive constructor invocation
} R.E:StackOverflowError

Note: Compiler is responsible for the following checkings.

  1. Compiler will check whether the programmer wrote any constructor or not. If
    he didn’t write at least one constructor then compiler will generate default
    constructor.
  2. If the programmer wrote any constructor then compiler will check whether he
    wrote super( or this() in the 1st line or not. If his not writing any of these
    compiler will always write (generate) super(.
  3. Compiler will check is there any chance of recursive constructor invocation. If
    there is a possibility then compiler will raise compile time error.

Case 2:
class Parent class Parent
class Parent { {
{ Parent() Parent(int i)
class Child extends Parent| —{} {}
{t valid } I E:\scjp>javac Child.java
class Child extends Parent] class Child extends Parent | Child.java:10: cannot find symbol
{} { symbol ; constructor Parent()
Child() location: class Parent
{ super();
super();
}
} output: /
compile time error

e Ifthe Parent class contains any argument constructors while writing Child
classes we should takes special care with respect to constructors.

e Whenever we are writing any argument constructor it is highly recommended to
write no argument constructor also.

Case 3:

class Parent

{

Parent () throws. java.io.IOException

{}
}
class Child extends Parent
{}
Output:

Compile time error

Unreported exception Java.io.IOException in default constructor.
Example:

class Parent

{

Parent()throws java.io. IOException

{}
}

class Child extends Parent

{
Child() throws Exception

{

super ();

}

If Parent class constructor throws some checked exception compulsory Child class
constructor should throw the same checked exception (or) its Parent.

Singleton classes :

For any java class if we are allow to create only one object such type of class is said to be
singleton class.

Example

1) Runtime class

2) ActionServlet

3) ServiceLocator
4) BusinessDelegate

Runtime r1l=Runtime.getRuntime () ;

//getRuntime() method is a factory method
Runtime r2=Runtime.getRuntime () ;
Runtime r3=Runtime.getRuntime () ;

System. out.printin(r1l==r2) ;//true
System. out.printin(r1==r3) ;//true

Diagram:

ri
r2

r3

Advantage of Singleton class :

If the requirement is same then instead of creating a separate object for every person
we will create only one object and we can share that object for every required person we
can achieve this by using singleton classes. That is the main advantages of singleton
classes are Performance will be improved and memory utilization will be improved.

Creation of our own singleton classes:

We can create our own singleton classes for this we have to use private constructor,
static variable and factory method.

Example:
class Test
{
private static Test t=null;
private Test()
{}
public static Test getTest()
//getTest() method is a factory method
{
if (t==nul1l1)
{
t=new Test();

}

return t;
}
}

class Client

{
public static void main(String[] args)
{
System. out.println(Test.getTest() .hashCode()) ;//1671711
System.out.printin(Test.getTest() .hashCode()) ;//1671711
System. out.println(Test.getTest() .hashCode()) ;//1671711
System. out.println(Test.getTest() .hashCode()) ;//1671711

Diagram:

t1
t2

t3

Note:

We can create any xxxton classes like(double ton,trible ton…etc)

Example:

class Test

{
private static Test tl=null;
private static Test t2=null;

private Test()
{}
public static Test getTest()
//getTest() method is a factory method
{
if (t1l—nul1l1)
{
tl=new Test();
return t1;
}
else if (t2==null1)
{
t2=new Test();
return t2;

else

if (Math.random()<0.5) //Math.random() limit : 0<=x<1
return t1;

else
return t2;

}
}
class Client
{
public static void main(String[] args)
{
System. out.println(Test.getTest() .hashCode()) ;//1671711
System. out.println(Test.getTest() .hashCode()) ;//11394033
System. out.println(Test.getTest() .hashCode()) ;//11394033
System. out.printin(Test.getTest() .hashCode()) ;//1671711

IIQ : We are not allowed to create child class but class is not final , How it is Possible ?

By declaring every constructor has private.
class Parent {
private Parent() {

}
We can’t create child class for this class

Note : When ever we are creating child class object automatically parent class
constructor will be executed but parent object won’t be created.

class Parent {

Parent() {
System. out.println(this.hashCode()); //123
}

}

class Child extends Parent {

Child() {

System. out.println(this.hashCode()) ;//123
}

}

class Test {

public static void main(String ar[]) {

Child c=new Child();
System. out.println(c.hashCode()) ;//123

Which of the following is true ?

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

We can declare return type for the constructor but it should be void. (false)

We can use any modifier for the constructor. (false)

Compiler will always generate default constructor. (false)

The modifier of the default constructor is always default. (false)

The 1st line inside every constructor should be super always. (false)

The 1st line inside every constructor should be either super or this and if we are

not writing anything compiler will always place this().(false)

  1. Overloading concept is not applicable for constructor. (false)

9, Inheritance and overriding concepts are applicable for constructors. (false)

  1. Concrete class can contain constructor but abstract class cannot. (false)
  2. Interface can contain constructor. (false)
  3. Recursive constructor call is always runtime exception. (false)
  4. If Parent class constructor throws some un-checked exception compulsory Child
    class constructor should throw the same un-checked exception or it’s Parent.
    (false)

14, Without using private constructor we can create singleton class. (false)

  1. None of the above.(true)

NAME YD

Factory method:

By using class name if we are calling a method and that method returns the same class
object such type of method is called factory method.

Example:
Runtime r=Runtime.getRuntime() ;//getRuntime is a factory method.
DateFormat df=DateFormat.getInstance ();

If object creation required under some constraints then we can implement by using
factory method.

Static control flow :

Example:

class Base
{
Qstatic intCi=10;)——@
Q)static
{

methodOne();

System.out.printin(“first static block”); |__ (49)

8 public static void main(String[] args)

{
methodOne(); @
System.out.printin(“main method”);}; —— “>

I
@ public static void methodOne()

{
System.out.printin(j); ——@), 4)
t
6) static
{

System.out.printin(“second static block”);

I
© static int (=20) ——_@

Analysis:

i=O[RIWO]

j=0[RIWO]

i=10[R&W]

j=20[R&W]

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

2.execution of static variable assignments and static blocks from top to bottom|[7 to 12]

3.execution of main method[13 to 15]

Output:
E:\scjp>javac Base.java
E:\scjp>java Base

0

First static block
Second static block

Leave a Reply

Your email address will not be published. Required fields are marked *