Have you ever come across a word or jargon called "Singleton" in java? if you had , and have no idea about it , here is a brief about Singleton Classes in java.
A singleton is an object that cannot be instantiated.It sounds contradictory to what we say "We need to instantiate an object before we can use it".So how can we create and use Singleton Classes? What is its advantages?
for clear precise information , Click Here
Showing posts with label java. Show all posts
Showing posts with label java. Show all posts
Thursday, May 17, 2007
Tuesday, May 8, 2007
Chained Exception
It is the process in which a exception causes another exception with the original cause attached and the chain of exceptions is thrown up to the next higher level exception handler.
For example
The following are the methods and constructors in Throwable that support chained exceptions.
Throwable getCause()
Throwable initCause(Throwable)
Throwable(String, Throwable)
Throwable(Throwable)
For example
try
{
}
catch (IOException e)
{
throw new SampleException("Other IOException", e);
}
The following are the methods and constructors in Throwable that support chained exceptions.
Throwable getCause()
Throwable initCause(Throwable)
Throwable(String, Throwable)
Throwable(Throwable)
Exception Example
try
{
This is where your logic goes like Opening a file
reading a file closing a file,etc
}
catch(FileNotFoundException ff)
{
This gets executed when the expected file is not found
}
catch(IOException ie)
{
This gets executed when the read or write operation failed
}
finally
{
This always executes when the try block exits.The finally block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finally block to insure that resource is always recovered.
}
So far we have seen scenarios where it's appropriate for code to catch exceptions
that can occur within it.In some cases, however, it's better to let a method further
up the call stack handle the exception.In this case, it's better to not catch the
exception and to allow a method further up the call stack to handle it.
This can be done by modifying the method to specify the exceptions it can throw ,
instead of catching them.
For example
public void methodName() throws IOException{}
Java provides numerous classes of exception.All the exception classes are descendant
of Throwable class.
User can create his own exception class by extending the Throwable class. Java
doesnot provide any interfaces for creating exception classes.
Types of Exception
In java there are two types of exceptions.
* Checked Exceptions
* Unchecked Exceptions.
Unchecked are further classifieds into
>> Error
>> Runtime Exceptions
* Checked Exceptions
These are exceptional conditions that a well-written application should anticipate and recover from.
For example java.io.FileNotFoundException.
All exceptions are checked exceptions, except for those indicated by Error,
RuntimeException, and their subclasses.
* Error
These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from.
For example java.io.IOError
* Runtime Exceptions
These are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from.These usually indicate programming bugs, such as logic errors or improper use of an API.
For example NullPointerException,Division by Zero , etc.
* Checked Exceptions
* Unchecked Exceptions.
Unchecked are further classifieds into
>> Error
>> Runtime Exceptions
* Checked Exceptions
These are exceptional conditions that a well-written application should anticipate and recover from.
For example java.io.FileNotFoundException.
All exceptions are checked exceptions, except for those indicated by Error,
RuntimeException, and their subclasses.
* Error
These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from.
For example java.io.IOError
* Runtime Exceptions
These are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from.These usually indicate programming bugs, such as logic errors or improper use of an API.
For example NullPointerException,Division by Zero , etc.
Exceptions in Java
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
When a exception occurs , the system searches for a block of code called "Exception Handler" in the call stack.
Call Stack is nothing but the list of methods that had been called to the method where the exception occured.
The system searches for the appropriate method in the call stack in the reverse order . If the appropriate method is found , the exceptions are handled , else the system terminates.
The block of code that is expected to throw some exception is written in
try.....catch....finally block.
When a exception occurs , the system searches for a block of code called "Exception Handler" in the call stack.
Call Stack is nothing but the list of methods that had been called to the method where the exception occured.
The system searches for the appropriate method in the call stack in the reverse order . If the appropriate method is found , the exceptions are handled , else the system terminates.
The block of code that is expected to throw some exception is written in
try.....catch....finally block.
Saturday, April 7, 2007
Thread synchronization
Consider a scenario ,where two different threads having access to a single instance of a class , and both threads invoke methods on that object and those methods modify the state of the object.
For example , consider a ATM transaction scenario. Suppose there a two people say 'A' and 'B' sharing the same account and each have their own card to withdraw money from ATM.Each goes through a process of checking the available balance and then withdrawing the cash.
Consider 'A' as ThreadA and 'B' as ThreadB.
1.ThreadA checks the balance (balance=Rs.500), and then sleeps for some time.
2.In the mean time , ThreadB checks the balance (balance=Rs.500) and withdraws some cash(withdrawal=200).
3.Now ThreadA wakesup and tries to withdraw the cash of Rs.500 and finds "Not enough money available in your account".
This problem is known as a "race condition," where multiple threads can access the same resource (typically an object's instance variables), and can produce corrupted data if one thread "races in" too quickly before an operation that should be "atomic" has completed.
In this case 'balance' is the variable accessed and modified by both threads , through the methods of checking and withdrawing.
In order to avoid this problem , we implement the concept of synchronization by
1.Marking the variable(balance) private
2.Synchronize the code that modifies the variables.
Synchronization guarants that , when ThreadA has entered the operation of checking and withdrawing , no other thread is allowed to acces or modify the variable(balance) even if ThreadA falls asleep. Other Threads can access and modify , only if ThreadA completes the operation and exits the run method.
sample for the above scenario :
In the above sample just add the word "synchronized" to the makeWithdrawal method like "private synchronized void makeWithdrawal" , because it is in this method we call another method that access and modify the variable balance.
Else if you have wrote these operations within the run() method , just put those operation code within the synchronized block like this.
{
synchronized(this)
{
//code for the operation goes here
}
}
Points to remember :
1.Synchronization is a proccess of locking the object , so that others dont access it.
2.Others can access only , if the thread releases that object
3.Only methods (or blocks) can be synchronized, not variables or classes
4.It is not necessary that all methods should be synchronized
5.The thread doesnot releases the object even it goes to sleep state.
6.Each object just has one lock.
7.A thread can acquire more than one lock , when it invokes a synchronized method of another object.
For example , consider a ATM transaction scenario. Suppose there a two people say 'A' and 'B' sharing the same account and each have their own card to withdraw money from ATM.Each goes through a process of checking the available balance and then withdrawing the cash.
Consider 'A' as ThreadA and 'B' as ThreadB.
1.ThreadA checks the balance (balance=Rs.500), and then sleeps for some time.
2.In the mean time , ThreadB checks the balance (balance=Rs.500) and withdraws some cash(withdrawal=200).
3.Now ThreadA wakesup and tries to withdraw the cash of Rs.500 and finds "Not enough money available in your account".
This problem is known as a "race condition," where multiple threads can access the same resource (typically an object's instance variables), and can produce corrupted data if one thread "races in" too quickly before an operation that should be "atomic" has completed.
In this case 'balance' is the variable accessed and modified by both threads , through the methods of checking and withdrawing.
In order to avoid this problem , we implement the concept of synchronization by
1.Marking the variable(balance) private
2.Synchronize the code that modifies the variables.
Synchronization guarants that , when ThreadA has entered the operation of checking and withdrawing , no other thread is allowed to acces or modify the variable(balance) even if ThreadA falls asleep. Other Threads can access and modify , only if ThreadA completes the operation and exits the run method.
sample for the above scenario :
public class AccountDanger implements Runnable
{ private Account acct = new Account(); public static void main (String [] args) { AccountDanger r = new AccountDanger(); Thread ThreadA = new Thread(r); Thread ThreadB = new Thread(r); ThreadA.setName("ThreadA"); ThreadB.setName("ThreadB"); ThreadA.start(); ThreadB.start(); } public void run() { for (int x = 0; x <>= amt) { System.out.println(Thread.currentThread().getName()+ " is going to withdraw"); try { Thread.sleep(500); } catch(InterruptedException ex) { } acct.withdraw(amt); System.out.println(Thread.currentThread( ).getName( )+ " completes the withdrawal"); } else { System.out.println("Not enough in account for "+ Thread.currentThread().getName() + " to withdraw "+ acct.getBalance()); } }
}class Account { private int balance = 50; public int getBalance() { return balance; } public void withdraw(int amount) { balance = balance - amount; }}In the above sample just add the word "synchronized" to the makeWithdrawal method like "private synchronized void makeWithdrawal" , because it is in this method we call another method that access and modify the variable balance.
Else if you have wrote these operations within the run() method , just put those operation code within the synchronized block like this.
public void run()
{
synchronized(this)
{
//code for the operation goes here
}
}
Points to remember :
1.Synchronization is a proccess of locking the object , so that others dont access it.
2.Others can access only , if the thread releases that object
3.Only methods (or blocks) can be synchronized, not variables or classes
4.It is not necessary that all methods should be synchronized
5.The thread doesnot releases the object even it goes to sleep state.
6.Each object just has one lock.
7.A thread can acquire more than one lock , when it invokes a synchronized method of another object.
Wednesday, March 28, 2007
Ways the Threads leaving Running State
The ways by which a running thread could leave the running state :
1.When a sleep() method is called.
2.When a yield() method is called.
3.When a join() method is called.
4.When a wait() method is called.
5.When the run() method is completed.
6.When its blocked ,waiting for some resources.
7.When the Thread Scheduler Schedules the Threads.
* A call to sleep() Guaranteed to cause the current thread to stop executing for at least the specified sleep duration (although it might be interrupted before its specified time).
* A call to yield() Not guaranteed to do much of anything, although typically it will cause the currently running thread to move back to runnable so that a thread of the same priority can have a chance.
* A call to join() Guaranteed to cause the current thread to stop executing until the thread it joins with (in other words, the thread it calls join() on) completes, or if the thread it's trying to join with is not alive, however, the current thread won't need to back out.
1.When a sleep() method is called.
2.When a yield() method is called.
3.When a join() method is called.
4.When a wait() method is called.
5.When the run() method is completed.
6.When its blocked ,waiting for some resources.
7.When the Thread Scheduler Schedules the Threads.
* A call to sleep() Guaranteed to cause the current thread to stop executing for at least the specified sleep duration (although it might be interrupted before its specified time).
* A call to yield() Not guaranteed to do much of anything, although typically it will cause the currently running thread to move back to runnable so that a thread of the same priority can have a chance.
* A call to join() Guaranteed to cause the current thread to stop executing until the thread it joins with (in other words, the thread it calls join() on) completes, or if the thread it's trying to join with is not alive, however, the current thread won't need to back out.
Thread States
The Life cycle or States of Threads.
1.New
2.Runnable
3.Running
4.Sleeping/waiting/blocked (Not Runnable)
5.Dead
Once the start() method is called, the thread is considered to be alive . A thread is considered dead after the run() method completes.
The isAlive() method is the best way to determine if a thread has been started but has not yet completed its run() method.
New state - when Thread is instantiated , but before the start method is invoked.
Runnable state - when the start method is invoked , and its ready to execution
Running state - This is where the action takes place.
Not Runnable state - This is where , the Thread is still alive ,but not eligible to run.A thread arrives at this state ,when it is blocked waiting for a resource like I/O , or when the sleep method is called or when the wait method is called.
Dead state - A thread is considered dead when its run() method completes.
1.New
2.Runnable
3.Running
4.Sleeping/waiting/blocked (Not Runnable)
5.Dead
Once the start() method is called, the thread is considered to be alive . A thread is considered dead after the run() method completes.
The isAlive() method is the best way to determine if a thread has been started but has not yet completed its run() method.
New state - when Thread is instantiated , but before the start method is invoked.
Runnable state - when the start method is invoked , and its ready to execution
Running state - This is where the action takes place.
Not Runnable state - This is where , the Thread is still alive ,but not eligible to run.A thread arrives at this state ,when it is blocked waiting for a resource like I/O , or when the sleep method is called or when the wait method is called.
Dead state - A thread is considered dead when its run() method completes.
Tuesday, March 27, 2007
Important facts of Threads
* Each thread will start, and each thread will run to completion.
* A thread is done being a thread when its target run() method completes.
* Once a thread has been started, it can never be started again.
* The order in which runnable threads are chosen to run is not guaranteed.
* A thread is done being a thread when its target run() method completes.
* Once a thread has been started, it can never be started again.
* The order in which runnable threads are chosen to run is not guaranteed.
Instantiating, and Starting Threads
The java.lang.Thread class contains the methods to create,start and pause threads.Some basic methods to be known from the Thread class are
1.start()
2.yield()
3.sleep()
4.run()
The 'work to be done' is always put in the run() method.
You can instantiate the thread by two ways.
1.By extending the java.lang.Thread class
2.By implementing the Runnable interface
Mostly you will be using the second one which is a good OO practise.Since java does not allow multiple inheritance , and if you use the first method, you cant inherit from other class.And its also good to extend the java.lang.Thread , only if the class needs to have specialized thread like behaviour.
Constructors in Thread:
1.Thread()
2.Thread(string)
3.Thread(Runnable)
4.THread(Runnable,String)
Where string - Name of the thread , Runnable - Instance of the class that implements Runnable
Even though you instantiate the thread , it doesnot enter the runnable state. In order to run the thread , we need to call the thread.start() method.
For example , when you extend a Thread ,syntax is
Thread t1=new Thread();
t1.start();
Eventhough you implement the Runnable interface , an instance of java.lang.Thread is needed to run the thread , by using the thread.start() method.
For example , when you implement the Runnable interface ,
The following is legal ,but does not start a separate thread
ClassName r = new ClassName();
r.run();
(ClassName -The one that implements Runnable interface)
In order to start the thread , replace the above code by below one.
ClassName obj=new ClassName();
Thread t1=new Thread(obj);
t1.start();
As soon as start() method is called , the following takes place.
* A new thread of execution starts (with a new call stack).
* The thread moves from the new state to the runnable state.
* When the thread gets a chance to execute, its target run() method will run.
1.start()
2.yield()
3.sleep()
4.run()
The 'work to be done' is always put in the run() method.
You can instantiate the thread by two ways.
1.By extending the java.lang.Thread class
2.By implementing the Runnable interface
Mostly you will be using the second one which is a good OO practise.Since java does not allow multiple inheritance , and if you use the first method, you cant inherit from other class.And its also good to extend the java.lang.Thread , only if the class needs to have specialized thread like behaviour.
Constructors in Thread:
1.Thread()
2.Thread(string)
3.Thread(Runnable)
4.THread(Runnable,String)
Where string - Name of the thread , Runnable - Instance of the class that implements Runnable
Even though you instantiate the thread , it doesnot enter the runnable state. In order to run the thread , we need to call the thread.start() method.
For example , when you extend a Thread ,syntax is
Thread t1=new Thread();
t1.start();
Eventhough you implement the Runnable interface , an instance of java.lang.Thread is needed to run the thread , by using the thread.start() method.
For example , when you implement the Runnable interface ,
The following is legal ,but does not start a separate thread
ClassName r = new ClassName();
r.run();
(ClassName -The one that implements Runnable interface)
In order to start the thread , replace the above code by below one.
ClassName obj=new ClassName();
Thread t1=new Thread(obj);
t1.start();
As soon as start() method is called , the following takes place.
* A new thread of execution starts (with a new call stack).
* The thread moves from the new state to the runnable state.
* When the thread gets a chance to execute, its target run() method will run.
Threads Concept
Thread is a light weight process. In java Thread can be said as
1.An instance of class java.lang.Thread
2.A thread of execution
An Instance of Thread is just like anyother objects in java , that has variables and methods , and lives and dies on the heap.
Whereas 'thread of execution' is a light weight process that has its own call stack.
That is ,'instance of class Thread' is related to 'worker' and 'a thread of execution' is related to 'the work to be done'.
From this, it is known that , you need a worker to do the work.So the thread is the worker and the work to be done is present in the run() method.
In java there is one thread per call stack and vice-versa.
Even if you dont create any new threads in your peogram , threads are there running in the back.For example , the main() method runs in one thread called main thread.
We have heared that threads are running concurrently or parallely.We also have heared that processor executes one thing at a time.In which case , both are contradictory.
Here comes the concept of scheduling . What actually happens is ,JVM gets its turn at the CPU by whatever scheduling mechanism the underlying OS uses, and operates like a mini-OS and schedules its own threads regardless of the underlying operating system. In some JVMs, the Java threads are actually mapped to native OS threads.
So, "When it comes to threads, very little is guaranteed".That is ,the behaviour in which the threads work will differ from machine to machine.
1.An instance of class java.lang.Thread
2.A thread of execution
An Instance of Thread is just like anyother objects in java , that has variables and methods , and lives and dies on the heap.
Whereas 'thread of execution' is a light weight process that has its own call stack.
That is ,'instance of class Thread' is related to 'worker' and 'a thread of execution' is related to 'the work to be done'.
From this, it is known that , you need a worker to do the work.So the thread is the worker and the work to be done is present in the run() method.
In java there is one thread per call stack and vice-versa.
Even if you dont create any new threads in your peogram , threads are there running in the back.For example , the main() method runs in one thread called main thread.
We have heared that threads are running concurrently or parallely.We also have heared that processor executes one thing at a time.In which case , both are contradictory.
Here comes the concept of scheduling . What actually happens is ,JVM gets its turn at the CPU by whatever scheduling mechanism the underlying OS uses, and operates like a mini-OS and schedules its own threads regardless of the underlying operating system. In some JVMs, the Java threads are actually mapped to native OS threads.
So, "When it comes to threads, very little is guaranteed".That is ,the behaviour in which the threads work will differ from machine to machine.
Monday, March 26, 2007
Difference final,finally and finalize
* final - constant declaration.
* finally - The finally block always executes when the try block exits, except System.exit(0) call. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
* finalize() - method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method.
* finally - The finally block always executes when the try block exits, except System.exit(0) call. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
* finalize() - method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method.
Garbage Collection
Garbage Collection is not about destroying Objects.
Its all about managing memmory.The reason for the existence of the garbage collector is to recover memory that your program is no longer using.
You cannot force garbage collection to take place.
However calling Sysem.gc() is a "hint" to the runtime engine that , now might be a good time to run the GC. Some implementations take that hint to heart and some don't.
Its all about managing memmory.The reason for the existence of the garbage collector is to recover memory that your program is no longer using.
You cannot force garbage collection to take place.
However calling Sysem.gc() is a "hint" to the runtime engine that , now might be a good time to run the GC. Some implementations take that hint to heart and some don't.
Marker Interface
One of the features of the Java programming language is that it mandates a separation between interfaces (pure behavior) and classes (state and behavior). Interfaces are used in Java to specify the behavior of derived classes. Often you will come across interfaces in Java that have no behavior. In other words, they are just empty interface definitions. These are known
as marker interfaces.
Some examples of marker interfaces in the Java API include:
* java,lang.Cloneable
* java,io.Serializable
* java.util.EventListener,etc.
Marker interfaces are also called "tag" interfaces since they tag all the derived classes into a category based on their purpose.
as marker interfaces.
Some examples of marker interfaces in the Java API include:
* java,lang.Cloneable
* java,io.Serializable
* java.util.EventListener,etc.
Marker interfaces are also called "tag" interfaces since they tag all the derived classes into a category based on their purpose.
Tuesday, March 20, 2007
Constructors in Java
Few points about constructors :
It has no return type.
It can use any access modifier, including private.
Its name must match the name of the class.
You could have both a method and a constructor with the same name in the same class.
Constructors are never inherited.
The default constructor is always a no-argument one.That is , it doesnot have arguments.
It can't be overridden.
It can be overloaded.
You cannot invoke an instance (in other words, nonstatic) method (or access an instance variable) until after the super constructor has run.
Key Rule: The first line in a constructor Must be a call to super() or a call to this().
It has no return type.
It can use any access modifier, including private.
Its name must match the name of the class.
You could have both a method and a constructor with the same name in the same class.
Constructors are never inherited.
The default constructor is always a no-argument one.That is , it doesnot have arguments.
It can't be overridden.
It can be overloaded.
You cannot invoke an instance (in other words, nonstatic) method (or access an instance variable) until after the super constructor has run.
Key Rule: The first line in a constructor Must be a call to super() or a call to this().
Thursday, March 15, 2007
Difference between Overloading and Overriding
Though its easy to determine whether Overloading or overriding takes place , using the argumentlist,return types,access specifiers and exceptions.We do confuse while invoking the methods using reference type and object type.
In case of overloading ,Reference type determines which method is selected from which class.In case of overriding ,Object type determines which which method is selected from which class.
Overloading happens during compile time,while overriding happens during Runtime.
In case of overloading ,Reference type determines which method is selected from which class.In case of overriding ,Object type determines which which method is selected from which class.
Overloading happens during compile time,while overriding happens during Runtime.
Inheritance Concept
Use of Inheritance
* To promote code reuse
* To use polymorphism
Inheritance in java is done by either extending a class or implementing the interfaces.
Inheritance is all about having a parent child relationship.So instead of rewriting the same functionality several times , you can just inhert those from the parent class.
Inheritance relationship can be of two types.
IS-A Relationship
Has-A Relationship
Is-A relationship is said to be direct relationship and can be done by either extending the parent class or by implementing the interface as said earlier.
For example
class Vehicle{}
class car extends vehicle{}
class ford extends car{}
In this case ford IS-A car . car IS-A Vehicle . So in the class Vehicle we can define several properties and functionalities that are similar , and declare several functionalities as abstract so that they can be overriden by the subclasses that inherit them.Since we have abstract methods in Vehicle class , we need to declare Vehicle as a abstract class.
Has-A relationship is said to be indirect relationship , in the sense , you dont want to extend or implement anything , rather create a instance of the class you want to inherit , and use that instance to invoke its methods.In this way the user dont have to know anything about the inherited class.For him,it seems like the functionality is in his Class.
for example
class Animal{}
class Halter { void tie(Rope r) { } }
class horse extends Animal {
Halter myhalter;
void tie(Rope r) { myhalter.tie(Rope r); }
}
In this case horse IS-A Animal.But Halter is not a Animal.Its just a equipment used to tie the horse. So horse Has-A Halter.Though horse doesnot extend or implement Halter it can use the 'tie' functionality by creating a instance of the Halter class.This is done as shown above.Now it seems like , we are invoking the 'tie' functionality of the horse, which in turn invokes the 'tie' functionality of Halter Class.so the actual implementation goes in Halter class and the user need not be aware of what is happening in the Halter class.For him its the tie method in the horse class is performing the operations.
* To promote code reuse
* To use polymorphism
Inheritance in java is done by either extending a class or implementing the interfaces.
Inheritance is all about having a parent child relationship.So instead of rewriting the same functionality several times , you can just inhert those from the parent class.
Inheritance relationship can be of two types.
IS-A Relationship
Has-A Relationship
Is-A relationship is said to be direct relationship and can be done by either extending the parent class or by implementing the interface as said earlier.
For example
class Vehicle{}
class car extends vehicle{}
class ford extends car{}
In this case ford IS-A car . car IS-A Vehicle . So in the class Vehicle we can define several properties and functionalities that are similar , and declare several functionalities as abstract so that they can be overriden by the subclasses that inherit them.Since we have abstract methods in Vehicle class , we need to declare Vehicle as a abstract class.
Has-A relationship is said to be indirect relationship , in the sense , you dont want to extend or implement anything , rather create a instance of the class you want to inherit , and use that instance to invoke its methods.In this way the user dont have to know anything about the inherited class.For him,it seems like the functionality is in his Class.
for example
class Animal{}
class Halter { void tie(Rope r) { } }
class horse extends Animal {
Halter myhalter;
void tie(Rope r) { myhalter.tie(Rope r); }
}
In this case horse IS-A Animal.But Halter is not a Animal.Its just a equipment used to tie the horse. So horse Has-A Halter.Though horse doesnot extend or implement Halter it can use the 'tie' functionality by creating a instance of the Halter class.This is done as shown above.Now it seems like , we are invoking the 'tie' functionality of the horse, which in turn invokes the 'tie' functionality of Halter Class.so the actual implementation goes in Halter class and the user need not be aware of what is happening in the Halter class.For him its the tie method in the horse class is performing the operations.
Inheritence Using Abstract Classes and Normal classes
While playing with minimum of 1 or 2 classes its easy to implement the concept of inheritence using concrete(normal) classes.
But in case of inheriting properties within a hierarchy or family , its better to use Abstract classes , so that you can define some functionalities that is same throughout the hierarchy and you can override several functionalities so that its more specific to that subclass.
So only the circumstance differ and not the concept of inheritence.
But in case of inheriting properties within a hierarchy or family , its better to use Abstract classes , so that you can define some functionalities that is same throughout the hierarchy and you can override several functionalities so that its more specific to that subclass.
So only the circumstance differ and not the concept of inheritence.
Tuesday, March 6, 2007
Encapsulation
It is a process of hiding the implementation details from other classes and just providing a way to access and modify its data.So that ,you can make necessary changes or corrections to your code without affecting or changing the classes that inherits your class.
Consider a situation, where you write a class and your friends inherit it. your class consist of a instance variable declared public as shown below.
class your{
public int size;
}
Now, your friend assigns a value to size , that produces a error in your code.
class friends{
yours y=new yours();
yours.size=-32;
}
Though assigning -32 to size is legal, its bad for you.Because you would be expecting positive values alone. So what will you do now? you would write a setter method that check the value and assigns it to size.
So, there is a need to change your code , as well as your friends code to access the method you have implemented in your class.
This where Encapsulation comes in place.
Benefit of Encapsulation
The ability to make changes in your implementation code without breaking the code of others who use your code is a key benefit of encapsulation.Thus bringing in the Flexibility and Maintainability,and scalability.
In order to do that, Declare your instance variables as private. provide methods to get and set the values of the variable ,like something present in javabeans.
Now lets rewrite your class, so that it is flexible , maintainable , and scalable.
class yours{
private int size;
public int getSize() { return size; }
public void setSize(int x) { //code for checking whether x is positive size=x; }
}
Not only checking, you can also do several other operations, whithout affecting other classes that inherits it.
Consider a situation, where you write a class and your friends inherit it. your class consist of a instance variable declared public as shown below.
class your{
public int size;
}
Now, your friend assigns a value to size , that produces a error in your code.
class friends{
yours y=new yours();
yours.size=-32;
}
Though assigning -32 to size is legal, its bad for you.Because you would be expecting positive values alone. So what will you do now? you would write a setter method that check the value and assigns it to size.
So, there is a need to change your code , as well as your friends code to access the method you have implemented in your class.
This where Encapsulation comes in place.
Benefit of Encapsulation
The ability to make changes in your implementation code without breaking the code of others who use your code is a key benefit of encapsulation.Thus bringing in the Flexibility and Maintainability,and scalability.
In order to do that, Declare your instance variables as private. provide methods to get and set the values of the variable ,like something present in javabeans.
Now lets rewrite your class, so that it is flexible , maintainable , and scalable.
class yours{
private int size;
public int getSize() { return size; }
public void setSize(int x) { //code for checking whether x is positive size=x; }
}
Not only checking, you can also do several other operations, whithout affecting other classes that inherits it.
Tuesday, February 27, 2007
Access Modifiers in Java
Difference between Default and Protected :
Default access modifier is package oriented. For example, Consider Class A has a method or member with default access modifier ,and Class B inherits Class A.Class B can only access the method or member of Class A, if and only if Class B is in the same package as class A.
In case of Protected , it is parent - child oriented. That is , for the above example, Class B can access the protected methods or members of Class A, eventhough Class B belongs to any other package.
In both cases , it is assumed that Class B inherits Class A, and class A is visbile to all classes,i.e, Class A is declared as Public.
And one more thing is, The subclass can see the protected member only through inheritance , and not by creating a instance of the superclass.
The protected member of class A can be accessed by the subclasses of Class B and not by other classes present in the Class B's package by instantiating Class B.
Default access modifier is package oriented. For example, Consider Class A has a method or member with default access modifier ,and Class B inherits Class A.Class B can only access the method or member of Class A, if and only if Class B is in the same package as class A.
In case of Protected , it is parent - child oriented. That is , for the above example, Class B can access the protected methods or members of Class A, eventhough Class B belongs to any other package.
In both cases , it is assumed that Class B inherits Class A, and class A is visbile to all classes,i.e, Class A is declared as Public.
And one more thing is, The subclass can see the protected member only through inheritance , and not by creating a instance of the superclass.
The protected member of class A can be accessed by the subclasses of Class B and not by other classes present in the Class B's package by instantiating Class B.
Subscribe to:
Posts (Atom)