• No results found

Data Hiding :

In document Core Java Meterial (Page 113-132)

Case 4: Variable naming conflicts Eg : interface Left {int i = 100;}

I. Data Hiding :

1. It means, the data should not go out directly. We can achieve this by declaring data members as private. (providing security)

2. The outside person is allowed to access data through methods only.

II. Abstraction :

1. Hiding implementation details is called “abstraction”.

Eg : Generation of a car 1.men 2. rod. 3. key 4. touch screen only by owner. Abstraction may be comfortable but too much cause – ve serve.

Advantages :

1. As we r not highlighting our internal implementation; we can get more security.

2. Without affecting outside word, v r able to change internal implementation. Hence, enhancement is easy.

We can achieve abstraction by providing a public interface for the end user. Eg : Keyboard is an interface for us, the internal implementation is always hided

III. Encapsulation : (key benefit of is security i.e. data hiding)

1. If a class follows – Data Hiding and Abstraction, that class is said to be encapsulated class.

Encapsulation : data hiding + abstraction

Note : The getter and setter methods, in real-time contain code regarding

authentication.

2. Hiding data behind methods is the central concept of encapsulation.

Advantages :

i. Security ii. Enhancement

iii. Maintainability (of code) iv. Modularity

Disadv :

The –ve side of encapsulation is :

It increases the length of code (because for every property

(data member) we have to write getter & setter methods) and slows down the execution.

Tightly Encapsulated Class :

1. A class is said to be tightly encapsulated if and only if all the data members are declared as “private”.

Eg : which of the following classes r tightly encap sulted ? i. class x

{

private int i = 10; (Tightly encapsulated – data member declared as private) public int get i ( )

{ return i; }

public void set i (int i) { this. i = i; } } ii. class x { private int i = 10; public void set i (int i) {

this. i = i; }

}

(Outside person can’t access (i) directly i.e. data not going out directly

⇒ tightly encapsulated) iii. class x { private int i = 10; } class y extends x { int j = 10;

}

(class y is not T.E. – there is no rule that if parents is T.E., Child also has to be T.E., - Y data member is not P.Vote it is not T.E.)

iv. class x {

int i = 10; x is not T.E. } class x extends { private int j = 20; } class z extends { private int k = 30; }

(Y is extending x, the non-private data of x is available to ‘y’ also) (Generally in java class itself indicates encapsulation)

Conclusion :

If the parent is not tightly encapsulated then no child class is tightly encapsulated

Note :

The protected member is available to the child class directly but not at all available to its sub child classes.

IV Inheritance (Is-A relationship) :

1. “Is –A” relationship is also known as inheritance.

2. By using “extends” keyword, we can implement inheritance concept. 3. The key benefit of inheritance is reversibility.

Eg 1: class person { int age; string name; string weight; string height; string eat( );

string sleep( ) }

Eg 2: class SWEngg extends person { string devignation; float salary; float code ( ); float dance ( ); float play ( ); float sleep ( ) } Eg 3: Amitab ↓ Abishek → Suggestible ↓ Chetab Eg 4: A – has 10 methods ↓ B – 12 (10 + 2) ↓ C – 12 (10+2+1) ↓ D ↓ E ↓ F ↓ G

We think ‘C’ has all the methods and it is advs. This is tve side

But –ve side is : To create child class obj all its parent class objs have to be created, but obj. creation is always.

4. According to real-time coding standard, 8-10 levels of inheritance is acceptable, beyond that it is not suggestible because it may create performance problems; for every child class object creation all the parent class objects we have to create. Eg : class parent { public void M1( ) { SOPln (“parent”); } }

Class child extends parent { Public void M2( ) { SOPln (“Child”); } P S V M (String args[ ]) }

Case 1 : Parent P = new parent ( ); P.M1 ( ); // Parent

P.M2( ); // Parent has no idea of what child class has, with parent clan ref. Child clam can’t be called.

Case 2 : Child C = new child( );

C.M1( ); // Parent → no such mett (M1) by in child clam, it executes parent class methods. C.M2( ); // Child

Case 3 : Parent P = new child( ); → Runtime object is child. P.M1( ); // Parent

P.M2( ); // CTE }

}

(Parent class ref. Can hold child clan obj but by using that ref we can’t call child clay specific methods.)

(Child class ref can’t hold parent class object)

Conclu :

1. The parent never aware of child-class specific. Methods. Parent.M2( );

2. Child aware of all the parent class methods. Child.M1 ( );

3. Child class reference can never hold parent class object. Child C = new parent ( );

4. The parent class ref can be used to hold child class instances. But by using that reference we r allowed to call only parent class methods. We r not allowed to call child class specific methods. Violation leads to CTE.

If parent class method is overridden in child class, and if v calling that parent method with children clan reference then the overridden method is executed but not the parent clan method.

V. Aggregation (Has A relationship):

(We use this concept in general but we don’t know) Note : Also known as composition.

Eg : Car contains (cabiposed of) engine, steer, seats – etc.

⇒ Car has Engine

1. HAS – A relationship also known as composition or aggregation. By using several objects, we can compose an object.

Eg : Class Engine Class Car

{ {

M1( ) Engine C = new Engine( );

M2( ) }

M3( ) }

⇒ A car HAS-A Engine reference.

2. The advantage of HAS-A relationship is reusability. 3. No keyword for mentioning HAS-A relationship.

4. HAS – A relationship increases the dependency between components which results in maintenance and enhancement problems.

Eg : without engine there is no car ⇒ dependency Eg : class sample

{

P S V M (String[ ] args) {

system out print in (“Kiran”); }

}

Method Signature :

In C, C++ method signature refers to return type + method name + arguments list. Eg ; Void M1( )

1. In Java, method signature consists of method name followed by arguments (the order of arguments is also important) Eg : M1( )

Eg : Public Void M1( ) Meth. Signature → M1( ) Public int M2 (int i, float f) → M2 (int i, float f) Note : Return type is not part of method signature in java. 2. class test

{

P Void M1( ) { } P void M2 (int I) { }

P void M3 (int I, float f) { } }

For the above class, compiler creates a table containing method signatures.

Test: 1 M1( ) 2 M2 (int) 3 M3 (int, float) class client { P S V M (S[ ] a) {

Test t = new Test( );

t.M1( ); → compiler checks; t.M2(10);

t.M3(23); }

(CTE : can’t resolve symbol M3 (double) method signature)

(‘t’ which class ref – test then it cheking M1( ) signature in table, if it matches the corresponding method is executed).

3. 2 methods with same signature is not possible in Java. Violation leads to compile time error. (Because compiler finds it ambiguous which method has to be executed).

CTE : M1() is already defined in test Class test

{

P V M1( ){ }

P int M1( ) { } return 10; }

4. In order to link method calls with corresponding implementations, compiler checks the method signature.

Overloading :

1. Overloading & overriding, both comes under polymorphism.

In C, to find absolute value of an integer we have a method abs (int).

To find abs value of long int we can’t use we have labs (long int) for floating point abs value fabs (float f)

⇒ For every data types we have separate type we have to remember all the in.. & code is complex. It is because 2 methods with same signature is not possible.

This problem is resolved in oops by using over OR. 2. In C, 2 methods with same name is not allowed.

Eg : If u want to find absolute value we have the following methods: abs ( ) – int

labs ( ) – long fabs ( ) – float…etc

For every data type, declaring anew method is always problem and it increases the complexity of the programming.

3. To resolve this, in the object oriented pgmg we can declare more than one method with the same sname (which is nothing but method over leading) so that the programming becomes very simple:

Eg : ‘max’ method in math Class

Max (int i, int j) Max (long l, long m) Max (double d, double e)

Method Overloading :

1. Two methods with the same method name but different arguments (atleast order) r said to be over loaded methods.

2. In case of overloading, the method names must be same, the arguments list must be different, never consider return type/access modifiers throws clause.

Eg 1 : class test {

P V M1( ) { SOPln (“No arg”);} P V M1 (int i) { SOPln (“inte”);} }

CTE : P V M1( ) P int M1( ) Eg 2: class test 1

{

P V M1( ) { SOPln (“No arg”);} P V M1 (int i) { SOPln (“inte”);} P S V M (S[ ] args)

{

Test 1 t1 = new test ( ); t1.M1( ); // No-arg t1.m1(10); // Inte }

3. Compiler is checking (or) resolve methods based on reference type (not based on runtime objects) in case of overloading, which is also known as “Compile-time resolution of overloaded methods.

Automatic promotion in Overloading :

1. In the case of overloading method resolution, compiler will always check for exact matched signature. If it is not finding, compiler will promote the argument to the next level. If it is not finding at that level also, it repeats the same process for the next level until double type, still if the compiler will not find the desired method, at last it will rise compile-time error.

The following r possible promotions in java method over leading. byte → short → int → long → float → double

chart Eg : class test

{

P V M1(double d) {SOPln (“double”)}; P S V M(S[ ] a)

{

Test t1 = new Test ( ); t1.M1(‘a’); t1.M1(‘10’); t1.M1(‘10L’); t1.M1(’10.3f’); t1.M1(’10.3’); } }

O/P : double (only)

If we declare any method with double as the argument that method can be applicable for any primitive data type except Boolean. Eg. Math.sqrt (double)

By using this method, we can find sqrt of byte, short, char, int, long, float and double values.

Case 1 :

Class test {

P V M1(String S) {SOPln (“String Version”);} P V M1(Object O) {SOPln (“Object Version”);} P S V M(S[ ]a)

{

Test t = new Test ( );

t1.M1(‘Pandu’); // String Version

t1.M1(‘new Object( )); // Object Version t1.M1(‘new Thread( )); // Object Version,

Thread is implicitly promoted to object. t1.M1(null); // NO CTE. O/P : String Version

} } Case 2 : Class test { P V M1(int i, float f) {

SOPln (“int, float”); Perfectly Overloaded.

} (Only order of arguments is changed) P V M1(float f, int i)

{

SOPln (“float, int”); }

P S V M (S[ ] a) {

test t = new test ( );

t1.M1(10, 10.5f); // Int, Float t1.M1(10.5f, 10); // Float, Int

t1.M1(10, 10); // CTE : Ambiguous reference to M1 is ambiguous. }

}

int, float float, int int, int

t.M1 CTE float, int int, int

(10,10)

⇒ Always child level data types get priority. (done by compiler).

Case 3 :

Class test {

P V M1(String Buffer S) {

SOP (“String Buffers”); } P V M1 (String S1) { SOP (“String”); } P S V M(S[ ] a) {

Test t = new Test( ); t.M1(null); //CTE }

}

CTE : reference to M1 is ambiguous t.M1(null)

Case 4 :

Class test {

Public void M1(Animal a) Class Animal

{ {

SOP (“Animal Version”); }

} Class Monkey

Public Void M1(Monkey M) Extends Animal

{ {

SOP (“Monkey Version”); } }

P S V M(S[ ]a) }

Case 1 : Test t = new Test ( );

Monkey M = new Monkey ( ); t.M1(M); // Monkey Version.

Case 2 : Animal a = new Animal ( );

t.M1(a); // Animal Version.

Case 3 : Animal as = new Monkey( );

t.M1(a1); // Animal Version

Compiler never bothers the run time obj, it considers only reference type.

Conclu : In case of overloading, the compile resolves the method call based on

reference type not based on run-time objects.

Overriding :

Eg : Class Father Class child extends father {

Gold

Land Available

Money

Subbu( ) {different implementation} }

1. Whatever the parent has by default available for the child classes. If the child class doesn’t want to use a particular method of the parent class it is allowed to provide its own implementation by overriding parent class method.

While overriding we have to follow certain rules :

Overriding Rules :

1. Method names and the argument list order also must be same. i.e. signature of the methods must be same.

Eg : Class P Class C extends P

Public Void MIC Public Void MIC --- { --- --- ⇒Overriding } --- } }

2. If parent class method, doesn’t want to allow child class to override, declare that as ‘final’ (security purpose).

The final methods cannot be overridden.

Eg : Class P Class C extends P

{ {

Final Public Void M1( ) Public Void M1( )

{ {

SOP(“Parent”); SOP(“Child”);

} ---

} }

}

CTE : M1 in C can’t override M1 in P; Overridden method is final.

3. A final method cannot be overridden but a non-final method can be overridden as final.

i.e. declaring M1( ) of ‘C’ as final.

4. Private methods will not be available for the child class and hence overriding concept is not applicable for the private methods.

5. If u want, we can declare exactly similar parent class method in the child class, but these methods r not overriding methods.

Eg :

Class P {

Private Void M1( ) {SOP (“Parent”);}; }

Class C extends P These r not overriding methods. {

Private void M1( ) {SOP(“Child”);} }

No CTE

6. In the case of overriding, the return types must be same. This rule is applicable until 1.4 version, violation leads to CTE.

Eg :

Class P {

Public Void M1( ) {SOP (“Parent”);}; }

Class C extends P different return types. {

Public int M1 ( ) {SOP(“Child”);} }

CTE Saying : M1( ) in C can’t override M1( ) in P; attempting to use incompatible return types.

found : int required : void

7. But from 1.5 version onwards covariant return types r also allowed. Co-variant return type means, need not be parent class return type its child classes also allowed as the return type.

Eg : If the return type of parent class method is object then the return type of child class method must be object until 1.4 version.

But in 1.5 version, need not be object may be its child class like string is also allowed. Eg : Class P { Public Object M1( ) }

return new object ( ); }

} Co-variant return type

Class C extends P allowed in 1.5 but not in {

{

return “Kiran”; }

}

Note : P = Object P = String C = String C = Object Co-variant Not co-variant return types

The concept of co-variant return types application for only object/reference types but not for primitive types.

A

Overriding Not B (Child of A)

overriding Overridding

C (Child of B)

8. While overrding, weakering the access specifier is not allowed. Violation leads to CTE.

Parent : Public Protected Default Private Child : Public

Protected Default Private

Note : Same Private methods in parent, child class r not considered as overridden methods but treated as separate methods.

Eg :

Class P {

Public Void M1( ) CTE :

{ M1( ) in C cannot

SOP(“Parent”); Override M1( ) in } P Attempting to assign

} weaker access pri vileges;

Class C access decreased was public. {

Private Void M1( ) {

SOP(“Child”) }

}

9. Inside interface all the methods r by default public and abstract. While implementing any interface method we should declare that method as public, otherwise V will get a compile time exception saying :

Attempting to assign weaker access privileges. Eg : interface Left {void M1( );}

Class x implements Left { Public Void M1( ) { } Void M1( ) { } Private Void M1( ) { } Protected Void M1( ) { } } Exceptions in Overriding :

1. The exceptions which r checked by compiler for smooth execution of the program at run time r called “Checked Exceptions”

The exceptions which r unable to check by the compiler r called “unchecked Array IOOBE Arithmetic Exceptions”

2. Error and its subclass r considered as Runtime Exception and its subclasses unchecked exceptions and all the remaining by default considered as checked exceptions.

3. Whether an exception is checked or unchecked it is always occur at Run-time only.

4. Checked Exceptions r again divided into partially checked and fully checked. A checked exception is called fully checked exception if and only if all its child classes also checked other wise considered as partially checked exception. Eg : for fully checked : IO Exception

Eg : for partially checked ; Exception

1. In the case of overriding v r not allowed to increase the size of the checked exceptions. But there is no rule for unchecked exceptions.

Import java 10-*;

Eg :

Class P 1 throws IO Exception

{ 2 throws IO Exception

Public Void M1( ) 3 throws IO Exception

{ 4 Exception

SOPln(“Parent”); 5 throws IO Exception

} 6 throws IO Exception

}

Class C extend P 1 throws IO Exception

{ 2 throws IO Exception

Public Void M1( ) 3 throws IO Exception

{ 4 throws IO Exception

SOP(“Child”) 5 throws IO Exception }

} 6 throws IO Exception

> javac c.java 2. Results in CTE :

(The size of checked exception is increased)

M1( ) in C can’t override M1( ) in ‘P’; overridden method does not throw java.lang. exception.

Exercise : Already mentioned in the pgm.

2. We can override a synchronized method as non-synchronized and a non synchronized method as the synchronized.

3. We can override a native method as non-native and non-native method as a native. Eg : It is recommended to override native has a code method in our classes.

4. We can override an abstract method as non-abstract method to provide implementation we can also override a non-abstract method to abstract. In that case, the child classes of child class r responsible to provide implementation abstract. Eg1 :

Class P {

abstract void M1( );

class C extends P { Void M1( ) { } } Eg2 : Class P { void M1( ) { }

} non-abstract to abstract (SUPERUUU) abstract class C extends P

{ abstract void M1( ); } 5. Class P { Public Void M1( ) { SOPln (“Parent”); } } Class C extends P { Public Void M1( ) { SOPln (“Child”); } P S V M (String[ ] args) } Case 1 : P P1 = new P( ); P1.M1( ); // Parent Case 2 : C C1 = new C( ); C1.M1( ); // Child

Case 3 : P P = new d( ); P.M1( ); // Child

/* Note : Parent class reference can hold child class instance. At compile time compiler checks the reference type P and checks whether M1 ( ) is present or not if not them CTE once it is satisfied, later at rum-time JUM checks which run-time (child class) object is that, once it is decided whether method M1( ) is overridden, then child class method is called, it not a then parent class method is executed because parent class members r by default available for child class */

In case of overriding, the method resolution taken case by JVM based on run-time object this process is also known as :

“Dynamic method dispatch” (or) “Dynamic Polymorphism” (or) “Runtime Polymorphism” (or) “Last binding”.

In document Core Java Meterial (Page 113-132)

Related documents