1)Encapsulation = datahiding + Abstraction
2)IS A relation Ship is inheritance
3)In Inheritance Parent reference can hold child class object.But here only parent class methods will be accessible , Child class methods are not available
4)In Inheritance Child ref cannot hold parent object
5)Implementation will be only once and hence no ambiguity in case of multiple inheritance in interfaces
6)Cyclic inheritance is not allowed in java
7)Has - A is also known as Composition/Agreegation.Example is Car has a engine
No speific keyword here , we use new operator
write once and use anywhere -- reusability
8)Composition and aggregation difference
Strong association is composition example univrsity and branches(csc,eee...)
University cannot exist with out branches
Weak association is aggregation example department and professor
Professor can exist with out department
9)When to use IS - A / HAS - A
Total functionality is needed in child class then go for IS- A
Example student needs all functionality of person
Part of functionality the go for has-A
test class example
Student may or may not need all details of all test
10)In overloading same method names but different argument types.method signature should be same
11)methodsignature = name+arguments
Compiler uses method signature to resolve method calls
with in a class two methods with same signature not allowed even return types are different
12)In method overloading compiler takes care of method resolving based on the reference type
50)
Overloaded Constructors
With in a class we can declare multiple constructors and all these constructors having same name but different type of arguments hence all these constructors are considered as overloaded constructors
Hence overloading concept applicable for constructors
For constructors inheritance and overriding concepts are not applicable but overloading concept is applicable.
Every class in java including abstract class contain constructors but interface do not contain
Since constructors are mainly used for initialization and as interface do not contain instance variables there is no need of constructor
51)Case 1:
Recursive method call is a runtime exception saying stack overflow error but in our program if there is chance of recursive constructor invocation then
code wont compile and we will get compile time error
Recursive contructor invocation
If only possibility is there then comiler immediately throws error
When ever we are writing any argument constructor it is recomended to write no arg constructor.
Special care while writing child class constructor if parent has arg constructor and child has no constructor then by default compiler will provide
default constructor and it will implicity call super and it will not find no arg constructor in parent
valid compiler will provide default constructor for both the classes
55)Only Inner classes in Java can be static, not Top level class.
2)IS A relation Ship is inheritance
3)In Inheritance Parent reference can hold child class object.But here only parent class methods will be accessible , Child class methods are not available
4)In Inheritance Child ref cannot hold parent object
5)Implementation will be only once and hence no ambiguity in case of multiple inheritance in interfaces
6)Cyclic inheritance is not allowed in java
7)Has - A is also known as Composition/Agreegation.Example is Car has a engine
No speific keyword here , we use new operator
write once and use anywhere -- reusability
8)Composition and aggregation difference
Strong association is composition example univrsity and branches(csc,eee...)
University cannot exist with out branches
Weak association is aggregation example department and professor
Professor can exist with out department
9)When to use IS - A / HAS - A
Total functionality is needed in child class then go for IS- A
Example student needs all functionality of person
Part of functionality the go for has-A
test class example
Student may or may not need all details of all test
10)In overloading same method names but different argument types.method signature should be same
11)methodsignature = name+arguments
Compiler uses method signature to resolve method calls
with in a class two methods with same signature not allowed even return types are different
12)In method overloading compiler takes care of method resolving based on the reference type
13)Automatic promotion allowed in overloading
char -- byte-- short --int--long--float--double
14)m1('a')
Calling Method
public void(int i)
{
}
Yes m1('a')gets called
15)m1(Object o)
m1(String s)
Calling is
m1(null)
then m1(string s ) gets priority since it is child class
16)m(String s)
m(StringBuffer sb)
calling
m(null)
Ambuguity hence compile time error.Compile error since both string and stringbuffer are at same level
17)m1(int i ,float j)
m1(float i ,int j)
calling
m1(10,10)
Ambiguous and hence compile time(check auto promotion 13 point)
m1(10.5f,10.5f)
No matching method found
Since float cannot be reduced to int
18)m1(int x)
m1(int... x)
calling
m1()
then m1(int... x)gets called
calling
m1(10,20)
var arg gets called
calling
m1(10)
then here m1(int x)gets called even both matches , since it is old
19)Overriding
Method name and arguments should be same here
Covariant return types allowed here like parent class can have object as return type then child class can have string as return type
Covariant concept not applicable for primitives
Example if parent class return type is double then child class cannot have int
Covariant concept Applicable only to objects
parent class abstract methods we should override in child class to provide implementation
parent class non abstract method can be declared as abstract in child class
20)In overloading
Return type can be differenr for the overloaded methods when numbrer of arguments different.
with in a class two methods with same signature not allowed even return types are different
Invalid Case
public void add()
{
System.out.println("add");
}
public int add()
{
System.out.println("1");
return 1;
}
valid case
public void add()
{
System.out.println("add");
}
public int add(int i)
{
System.out.println("1");
return 1;
}
21)
Exception Rule
If child class method throws any checked exception then compulary parent class should throw checked execption or its parent exception else Compile time error
22)We cannot override class level method to object level methods(Static to non static not to be done)
Vice versa also not possible
Both parent and child class have static methods then it is method hhiding not overriding
In method hiding mehod resolution is taken based on the compiler i,e based on reference not on the run time object
Example
public class ParentExample {
public static void testOne()
{
System.out.println("I'm parent test");
}
}
public class ChildExample extends ParentExample{
public static void testOne() {
// TODO Auto-generated method stub
System.out.println("I'm Child ");
}
}
public class MainClass {
public static void main(String[] args) {
ParentExample parentObj = new ChildExample();
parentObj.testOne();
/*ChildExample chidObj = new ChildExample();
chidObj.testOne();*/
}
}
O/P
I'm parent test
For the same thing if it is not method hiding and if it is just overriding then child class method will be called
23)Var - Args Overriding
We cannot override Vararg method with the normal method
class parent{
public void m1(int...x)
{
s.o.p("parent")
}
}
class child extends parent{
public void m1(int x)
{
s.o.p("child")
}
}
calling like this
parent p1 = new child();
p.m1();//parent method is called since above scenatio is overloading not overriding.In overloading refenrece type during compiling
19)Overriding
Method name and arguments should be same here
Covariant return types allowed here like parent class can have object as return type then child class can have string as return type
Covariant concept not applicable for primitives
Example if parent class return type is double then child class cannot have int
Covariant concept Applicable only to objects
parent class abstract methods we should override in child class to provide implementation
parent class non abstract method can be declared as abstract in child class
20)In overloading
Return type can be differenr for the overloaded methods when numbrer of arguments different.
with in a class two methods with same signature not allowed even return types are different
Invalid Case
public void add()
{
System.out.println("add");
}
public int add()
{
System.out.println("1");
return 1;
}
valid case
public void add()
{
System.out.println("add");
}
public int add(int i)
{
System.out.println("1");
return 1;
}
21)
Exception Rule
If child class method throws any checked exception then compulary parent class should throw checked execption or its parent exception else Compile time error
22)We cannot override class level method to object level methods(Static to non static not to be done)
Vice versa also not possible
Both parent and child class have static methods then it is method hhiding not overriding
In method hiding mehod resolution is taken based on the compiler i,e based on reference not on the run time object
Example
public class ParentExample {
public static void testOne()
{
System.out.println("I'm parent test");
}
}
public class ChildExample extends ParentExample{
public static void testOne() {
// TODO Auto-generated method stub
System.out.println("I'm Child ");
}
}
public class MainClass {
public static void main(String[] args) {
ParentExample parentObj = new ChildExample();
parentObj.testOne();
/*ChildExample chidObj = new ChildExample();
chidObj.testOne();*/
}
}
O/P
I'm parent test
For the same thing if it is not method hiding and if it is just overriding then child class method will be called
23)Var - Args Overriding
We cannot override Vararg method with the normal method
class parent{
public void m1(int...x)
{
s.o.p("parent")
}
}
class child extends parent{
public void m1(int x)
{
s.o.p("child")
}
}
calling like this
parent p1 = new child();
p.m1();//parent method is called since above scenatio is overloading not overriding.In overloading refenrece type during compiling
24)Overriding not applicable to variables
variable resolution always takes place by compiler based on reference type
Even above concept is same with static variables
25)Difference b/w overloading and overriding
property overloading override
Meth name must be same must be same
Argument types must be diff(atleast order) must be same(incl order)
Meth sig must be diff must be same
Return type no restriction must be same until 1.4
from 1.5 covariant allowed
private static final can be overloaded cannot be over ridden
Access modifiers no restrictions scope should not be decreased
but we can increase
throws clause no restriction if child class throws any checked exception compulsary parent class must throw same checked exception or its parent
MEthod resolution always takes care by compiler based on ref type always takes care by jvm based on runtime obj
compile time poly/early binding/static poly Run time poly/late binding/dynamic poly
26)Note
static and abstract cannot be declared together
27)Polymorphism
same name multiple forms
overloading comes under this
overriding also under this
usage of one parent to hold child objects is an example of poluorphism
example list l = new ArrayList
list l = new Linkedlist
list l = new stack
list l = new vector
parent class reference can be used to hold child object but by using this reference we can call only parent class methods and we cant call child specific methods
P --- > m1
C ---> m2
P obj = new C();
p.m2//we get compile time error in this case
p.m1()//this is valid
But by using child object reference we can call both parent and child class methods
C obj = new C();
obj.m1();
obj.m2();
Both are valid
28)When v should go for parent reference to hold child
If we do not know run time object then go for parent reference
Arraylist can hold any type of objects
while retriving if we are not aware then use parent rference
In array list get method always returns object type
If mehod returns arraylist/linkedlist/stack then declare method return type as List as it is parent
29)OOPS
Encapsulation -- security
Polymorphism -- flexibility
Inheritance -- reusability
Above are 3 pillars of oops
30)Coupling
Degeree of dependency between components is called coupling and if dependency is less then it i loosely coupling if it is more then tightly coupling
Enhancement becomes difficult in tight coupling
Reusability is not posssible here .it is supressed
Maintanability is tough
31)Cohesion
For every component we difine its own responsibility then it is called cohesion
High cohesion is good programmig practice
Seperate presentation -- view
controller --- operation
model --dada objects
Then this is high cohesion
32)Object type casting
Parent class can hold child class object
example Object o = new String("aaa");
Interface ref can be used to hold implemented class object
Object o = new String("aaa");
StringBuffer sb = (StringBuffer)o;//It is valid till compile time
33)Type casting Rule
A b = (C)d;
A and C is class or interface name
b and d is name of ref variable
Converting d object to c type and assigning to A type reference variable
Conditions to checked
Check relation between C and d .there should be some relation then no compile time error
String s = new String("nnn");
stringBuffer sb = (StringBuffer)s;
then we get compile time error since no relation b/w string na d string buffer
Inconvertible type name of compile time error
Cond 2 ) C must be derived or same tye as A
Example
Object o = new String("aaa");
StringBuffer sb = (StringBuffer)o;//It is valid till compile time
//we get run time error as class cast excption
Example
Object o = new String("aaa");
StringBuffer sb = (String)o;//Compile time error , incomatible types
Cond 3)underly object tye of d must be same or derived class of C
Runtime object type of 'd' must be either same or derived type of c else we will get runtime exception saying class cast exception
Object o = new String("aaa");
Object o = (String)o;
Valid as all conditions are met
34)We are not creating new object in type casting ,for existing object we are creating new reference.
Note
A<---B<---C
B b = new C();
same as (B)C
A a = new C();
same as (A)((B)c)
35)When ever we are executing a java class follwwing sequence of steps will be executed as the part of atatic control flow
1)Identification of static members from top to bottom[1 to 6]
2)Execution of static variables assignments and static blocks from top to bottom[7 to 12]
3)Execuion of main method[13 to 15]
Example
class based{
1..only identification static in i = 10;7..
static{
2..only identification m1();8..
S.O.P("First static block")10..
}
3..p s v main()
{
m1();13..
S.O.P("main method");15..
}
4..p s v m1()
{
s.o.p(j)9.. 14..
}
5..static{9..
s.o.p("second static block");11..
}
6..static int j = 20;12..
}
O/P
0
First static block
second static block
20
main method
36)Read Indirectly Write Only(RIWO)
With in static block if we read any variable then it is direct read
If we read through method and call method in static block then it is indirect method
If a variable is just identified by the JVM and not assigned any value then it is in RIWO.In tis case direct read is not allowed we get compile time error
i.e illegal forword reference
static blocks are 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
example 1) loading native libraries at the time of class loading
37)Without writing main method it is possible to print some statements to console through static block
Without static block and with out main peint some thing
Example one
class test{
static int x = m1();
public static int m1()
{
s.o.p("hello print")
System.exit(0);
return 10;
}
}
Example 2
Class Test
{
static test t = new Test();
{//this is an instance block and it is executed when the object is created
s.o.p("hello");
System.exit(0);
}
Example 3
class Test{
static Test t = new Test();
//when ever we create an object constructor gets invoked
Test()
{
S.O.P("hello");
System.Exit(0);
}
}
}
38)Instance Control Flow
Creating object followng steps
1)Identification of instance members from top to bottom
2)Execution of instance variable assignments and instance blocks from top to bottom
3)Execution of constructor
when ever we are running a java class first static control flow is executed , if we are creating obj in static conrol then above steps will be
executed as a part of instance control flow
39)Note
Static control flow is one time activity which will be performed at time of class loading but
Instance control flow is not one time activity and it will be performed for every object creation.
Note
A<---B<---C
B b = new C();
same as (B)C
A a = new C();
same as (A)((B)c)
35)When ever we are executing a java class follwwing sequence of steps will be executed as the part of atatic control flow
1)Identification of static members from top to bottom[1 to 6]
2)Execution of static variables assignments and static blocks from top to bottom[7 to 12]
3)Execuion of main method[13 to 15]
Example
class based{
1..only identification static in i = 10;7..
static{
2..only identification m1();8..
S.O.P("First static block")10..
}
3..p s v main()
{
m1();13..
S.O.P("main method");15..
}
4..p s v m1()
{
s.o.p(j)9.. 14..
}
5..static{9..
s.o.p("second static block");11..
}
6..static int j = 20;12..
}
O/P
0
First static block
second static block
20
main method
36)Read Indirectly Write Only(RIWO)
With in static block if we read any variable then it is direct read
If we read through method and call method in static block then it is indirect method
If a variable is just identified by the JVM and not assigned any value then it is in RIWO.In tis case direct read is not allowed we get compile time error
i.e illegal forword reference
static blocks are 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
example 1) loading native libraries at the time of class loading
37)Without writing main method it is possible to print some statements to console through static block
Without static block and with out main peint some thing
Example one
class test{
static int x = m1();
public static int m1()
{
s.o.p("hello print")
System.exit(0);
return 10;
}
}
Example 2
Class Test
{
static test t = new Test();
{//this is an instance block and it is executed when the object is created
s.o.p("hello");
System.exit(0);
}
Example 3
class Test{
static Test t = new Test();
//when ever we create an object constructor gets invoked
Test()
{
S.O.P("hello");
System.Exit(0);
}
}
}
38)Instance Control Flow
Creating object followng steps
1)Identification of instance members from top to bottom
2)Execution of instance variable assignments and instance blocks from top to bottom
3)Execution of constructor
when ever we are running a java class first static control flow is executed , if we are creating obj in static conrol then above steps will be
executed as a part of instance control flow
39)Note
Static control flow is one time activity which will be performed at time of class loading but
Instance control flow is not one time activity and it will be performed for every object creation.
40)Object creation is the most costly operation if there is no specific requirement then it is not recomended to create object
41)Instance control flow in parent to child relation ship(When we run child class)
1)Identification of instance members from parent to child
2)execution od instance variable assignments and instance blocks in parent class
3)execution of parent constructor
4)execution of instance variable assignments and instance blocks in child class
5)execution of child constructor
42)From static area we cant access instance members directly bcoz while executing static area JVM may not identify instance members
Class Test{
int x = 10;
P Sv m()
{
S.O.P(x);//we get compile time error non static var cannot be accessed from static context
Test t = new Test();
S.o.p(t.x)//valid we get 10 as o/p
}
}
42)From static area we cant access instance members directly bcoz while executing static area JVM may not identify instance members
Class Test{
int x = 10;
P Sv m()
{
S.O.P(x);//we get compile time error non static var cannot be accessed from static context
Test t = new Test();
S.o.p(t.x)//valid we get 10 as o/p
}
}
43)ways to create an object in java
1)By using new operator
2)By using newInstance() method
3)By isng factory method
4)By using Clone() method
5)By using deserialisation
44)We use constructors to initialise object not create
Diff b/w constructor and instance block
1)For every object creation we need to do some operation other than initialisation then we should go for instance block
2)Incrementing count value for every object creation is an example of instance block
3)Constructor and instance block have their own diff purposes and replacing one concept with another concept may not work always
4)Both constructor and instance block will be executed for every object creation but instance block execution is first followed by constructor next.
45)Count number of objects created in class
public class CountObject {
public CountObject() {
// TODO Auto-generated constructor stub
}
public CountObject(int i) {
// TODO Auto-generated constructor stub
this(20.5);
}
public CountObject(double d) {
// TODO Auto-generated constructor stub
System.out.println(d);
}
static int counter;
{
counter++;
}
public static void main(String[] args) {
CountObject t1 = new CountObject();
CountObject t2 = new CountObject(2);
CountObject t3 = new CountObject(10.5);
System.out.println(counter);
}
}
O/P : 3
46)Rules of writing constructors
1)Name of class and constructor should be same
2)Automatically called when ever we create object and hence return type concept not applicable here even void also
3)Class Test
{
void Test() // no compile time error since compiler tkes it as a method
{
}
}
Method name same as constructor is legal but not good programming practise
4)Modifiers for constructor are public , pvt , protected, default
47)Default Constructor
1)Compiler is responsible to generate default constructor
2)It will generate if and only if we are not wriring constructor
3)It is always no arg constructor
4)Access modifir of default constructor is always same as class modifier(This rule is applicable only for public and default)
5)It contains only one line i.e super();
6)If we do not write super() or this() as first line in constructor then compiler will do this job i.e it will add super();
48)Case 1:
Super() or this() should be placed in first line of constructor if we are trying to place any where else we will get compile time error
Case 2:
Class Test{
Test()
{
super();
this();//compile time error since this is in second line and hence super() and this() both cannot be used
}
}
Case 3:
We can use super() or this() only inside constructor , if we are trying to use outside of constructor we will get compile time error
49)Super(), this()
1)use only in constructors
2)use in first line only
3)use any one but not both
4)these are construtor calls to call super class and current class constructors
5)super and this are keywords to refer super class and current class instance members
6)super and this cannot be used in static context
7)Super(), this() used only once in constructor
8)Super, this can be any number of times
50)
Overloaded Constructors
With in a class we can declare multiple constructors and all these constructors having same name but different type of arguments hence all these constructors are considered as overloaded constructors
Hence overloading concept applicable for constructors
For constructors inheritance and overriding concepts are not applicable but overloading concept is applicable.
Every class in java including abstract class contain constructors but interface do not contain
Since constructors are mainly used for initialization and as interface do not contain instance variables there is no need of constructor
51)Case 1:
Recursive method call is a runtime exception saying stack overflow error but in our program if there is chance of recursive constructor invocation then
code wont compile and we will get compile time error
Recursive contructor invocation
If only possibility is there then comiler immediately throws error
When ever we are writing any argument constructor it is recomended to write no arg constructor.
Special care while writing child class constructor if parent has arg constructor and child has no constructor then by default compiler will provide
default constructor and it will implicity call super and it will not find no arg constructor in parent
valid compiler will provide default constructor for both the classes
Class p{
}
Class c extends Parent{
}
Valid compiler will provide default no arg constructor to child which will implicity call super class constructor
Class p{
p()
{
super();
}
}
Class c extends Parent{
}
Invalid becoz compiler will provide default no arg constructor to child which will implicitily call super and hence it will not find matching constructor
Class p{
p(int i )
{
super();
}
}
Class c extends Parent{
}
52)Note :If parent class constructor throws some checked exception then child class contructor must throw same checked exception or its parent
Class P
{
P()throws IOException
{
}
}
Class C extends P{
}
We compile time error since child class constructor will call parent class constructor (Calling method should handle exception);
Compiler default no arg constructor will contain super
How to handle above case
Class P
{
P()throws IOException
{
}
}
Class C extends P{
try{
super();
}
catch(IOException)
{
}
}
Invalid sinece first statement should be super
Class P
{
P()throws IOException
{
}
}
Class C extends P{
super() throws IOException;
}
Valid above one
53)Singleton classes
For any java class if we are allowed to create only one object such type of class is called single ton class
example runtime , businesselegate,service locator etc
Advantage of singleton class
Improve performance
If several people have same requirement then it is not recomended to create seperate object for every requirement ,we have to create only one object and we can
reuse same object for every similar requirement so that performance and memory utilisations will be improved.This is the central idea of single ton classe
How to create our own single ton classes
We can create our own single ton classes for this we have to use private constructor and private static variable and public factory method
Approach 1:
Class Test{
private static Test t = new Test();
private Test()
{
}
public static Test getTest()
{
return t;
}
}
Disadvantage of above method
Object gets created in the beginning and if we do not use then wastage of resource
Approach 2:
Class Test{
private static Test t = null;
private Test()
{
}
public static Test getTest()
{
if(t==null)
t = new Tets();
return t;
}
}
54)Class is not final but we are not allowed to create child classes how it is possible??
Declare every constructor as private
55)Only Inner classes in Java can be static, not Top level class.
No comments:
Post a Comment