Final Keyword In Java
variableThe
final keyword in java is used to restrict the user. The final keyword can be used in many context. Final can be:
- variable
- method
- class
The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only. We will have detailed learning of these. Let's first learn the basics of final keyword.
final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).
final method
If you make any method as final, you cannot override it.
final class
If you make any class as final, you cannot extend it.
Is final method inherited?
Ans) Yes, final method is inherited but you cannot override it.
What is blank or uninitialized final variable?
A final variable that is not initialized at the time of declaration is known as blank final variable.
If you want to create a variable that is initialized at the time of creating object and once initialized may not be changed, it is useful. For example PAN CARD number of an employee.
It can be initialized only in constructor.
Can we initialize blank final variable?
Yes, but only in constructor.
more details...
instanceof operator
The
instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface).
The instanceof operator is also known as type comparison operator because it compares the instance with type. It returns either true or false. If we apply the instanceof operator with any variable that have null value, it returns false.The
instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface).
imple example of instanceof operator
Let's see the simple example of instance operator where it tests the current class.
- class Simple{
- public static void main(String args[]){
- Simple s=new Simple();
- System.out.println(s instanceof Simple);
- }
- }
Downcasting with instanceof operator
When Subclass type refers to the object of Parent class, it is known as downcasting. If we perform it directly, compiler gives Compilation error. If you perform it by typecasting, ClassCastException is thrown at runtime. But if we use instanceof operator, downcasting is possible.
more details...
Abstract class in Java
A class that is declared with abstract keyword, is known as abstract class. Before learning abstract class, let's understand the abstraction first.
Abstraction
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only important things to the user and hides the internal details for example sending sms, you just type the text and send the message. You don't know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstaction
There are two ways to achieve abstraction in java
- Abstract class (0 to 100%)
- Interface (100%)
Abstract class
A class that is declared as abstract is known as
abstract class. It needs to be extended and its method implemented. It cannot be instantiated.
abstract method
A method that is declared as abstract and does not have implementation is known as abstract method.
Understanding the real scenario of abstract class
In this example, Shape is the abstract class, its implementation is provided by the Rectangle and Circle classes. Mostly, we don't know about the implementation class (i.e. hidden to the end user) and object of the implementation class is provided by the factory method.
A factory method is the method that returns the instance of the class.
Abstract class having constructor, data member, methods etc.
Note: An abstract class can have data member, abstract method, method body, constructor and even main() method.
Rule: If there is any abstract method in a class, that class must be abstract.
Rule: If you are extending any abstact class that have abstract method, you must either provide the implementation of the method or make this class abstract.
Another real scenario of abstract class
The abstract class can also be used to provide some implementation of the interface. In such case, the end user may not be forced to override all the methods of the interface.
Note: If you are beginner to java, learn interface first and skip this example.
|
What is abstraction?
Abstraction is a process of hiding the implementation details and showing only functionality to the user.more details...
|
Abstraction lets you focus on what the object does instead of how it does it.
What is the difference between abstraction and encapsulation?
Abstraction hides the implementation details whereas encapsulation hides the data.more details... |
Abstraction lets you focus on what the object does instead of how it does it.
What is abstract class?
A class that is declared as abstract is known as abstract class.It needs to be extended and its method implemented.It cannot be instantiated. more details...
Can there be any abstract method without abstract class?
No, if there is any abstract method in a class, that class must be abstract.
Can you use abstract and final both with a method?
No, because abstract method needs to be overridden whereas you can't override final method.
Is it possible to instantiate the abstract class?
No, abstract class can never be instantiated.
|
|
|
|
|
|
more details...
Interface in Java
An
interface is a blueprint of a class. It has static constants and abstract methods.
The interface is a mechanism to achieve fully abstraction in java. There can be only abstract methods in the interface. It is used to achieve fully abstraction and multiple inheritance in Java.An
interface is a blueprint of a class. It has static constants and abstract methods.
Interface also
represents IS-A relationship.
It cannot be instantiated just like abstract class.
Why use Interface?
There are mainly three reasons to use interface. They are given below.
- It is used to achieve fully abstraction.
- By interface, we can support the functionality of multiple inheritance.
- It can be used to achieve loose coupling.
The java compiler adds public and abstract keywords before the interface method and public, static and final keywords before data members.
In other words, Interface fields are public, static and final bydefault, and methods are public and abstract.
Understanding relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another interface but a
class implements an interface.
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as multiple inheritance.
Q) Multiple inheritance is not supported in case of class but it is supported in case of interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in case of class. But it is supported in case of interface because there is no ambiguity as implementation is provided by the implementation class.
Note: A class implements interface but One interface extends another interface .
What is marker or tagged interface ?
An interface that have no member is known as marker or tagged interface. For example: Serializable, Cloneable, Remote etc. They are used to provide some essential information to the JVM so that JVM may perform some useful operation.
Nested Interface
Note: An interface can have another interface i.e. known as nested interface. We will learn it in detail in the nested classes chapter.
What is interface?
Interface is a blueprint of a class that have static constants and abstract methods.It can be used to achive fully abstraction and multiple inheritance. more details...
Can you declare an interface method static?
No, because methods of an interface is abstract bydefault, and static and abstract keywords can't be used together.
Can an Interface be final?
No, because its implementation is provided by another class.
|
What is marker interface?
An interface that have no data member and method is known as a marker interface.For example Serializable,Cloneable etc.
What is difference between abstract class and interface?
1)An abstract class can have method body (non-abstract methods). | Interface have only abstract methods. |
2)An abstract class can have instance variables. | An interface cannot have instance variables. |
3)An abstract class can have constructor. | Interface cannot have constructor. |
4)An abstract class can have static methods. | Interface cannot have static methods. |
5)You can extends one abstract class. | You can implement multiple interfaces. |
|
|
|
Can we define private and protected modifiers for variables in interfaces?
No, they are implicitely public.
|
When can an object reference be cast to an interface reference?
An object reference can be cast to an interface reference when the object implements the referenced interface.
Encapsulation in Java
Encapsulation is a process of wrapping code and data together into a single unit e.g. capsule i.e mixed of several medicines.
We can create a fully encapsulated class by making all the data members of the class private. Now we can use setter and getter methods to set and get the data in it.
Java Bean is the example of fully encapsulated class.
Advantage of Encapsulation
By providing only setter or getter method, you can make the class read-only or write-only.
It provides you the control over the data. Suppose you want to set the value of id i.e. greater than 100 only, you can write the logic inside the setter method.
|
|
|
more details...
Object class in Java
The
Object class is the parent class of all the classes in java bydefault. In other words, it is the topmost class of java.
The Object class is beneficial if you want to refer any object whose type you don't know. Notice that parent class reference variable can refer the child class object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any type like Employee,Student etc, we can use Object class reference to refer that object. For example:
The Object class provides some common behaviours to all the objects such as object can be compared, object can be cloned, object can be notified etc.
Methods of Object class
The Object class provides many methods. They are as follows: |
Method | Description |
public final ClassgetClass() | returns the Class class object of this object. The Class class can further be used to get the metadata of this class. |
public int hashCode() | returns the hashcode number for this object. |
public boolean equals(Object obj) | compares the given object to this object. |
protected Object clone() throws CloneNotSupportedException | creates and returns the exact copy (clone) of this object. |
public String toString() | returns the string representation of this object. |
public final void notify() | wakes up single thread, waiting on this object's monitor. |
public final void notifyAll() | wakes up all the threads, waiting on this object's monitor. |
public final void wait(long timeout)throws InterruptedException | causes the current thread to wait for the specified milliseconds, until another thread notifies (invokes notify() or notifyAll() method). |
public final void wait(long timeout,int nanos)throws InterruptedException | causes the current thread to wait for the specified miliseconds and nanoseconds, until another thread notifies (invokes notify() or notifyAll() method). |
public final void wait()throws InterruptedException | causes the current thread to wait, until another thread notifies (invokes notify() or notifyAll() method). |
protected void finalize()throws Throwable | is invoked by the garbage collector before object is being garbage collected. |
more details...
Object Cloning in Java
The
object cloning is a way to create exact copy of an object. For this purpose, clone() method of Object class is used to clone an object.
The
java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates
CloneNotSupportedException.
The
clone() method is defined in the Object class. Syntax of the clone() method is as follows:
- protected Object clone() throws CloneNotSupportedException
Why use clone() method ?
The
clone() method saves the extra processing task for creating the exact copy of an object. If we perform it by using the new keyword, it will take a lot of processing to be performed that is why we use object cloning.
Advantage of Object cloning
Less processing task.
more details...
Array in Java
Normally, array is a collection of similar type of elements that have contiguous memory location.
In java, array is an object the contains elements of similar data type. It is a data structure where we store similar elements. We can store only fixed elements in an array.
Array is index based, first element of the array is stored at 0 index.
Advantage of Array
- Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
- Random access: We can get any data located at any index position.
Disadvantage of Array
- Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in java.
Types of Array
There are two types of array.
- Single Dimensional Array
- Multidimensional Array
Single Dimensional Array
Syntax to Declare an Array in java
- dataType[] arrayRefVar; (or)
- dataType []arrayRefVar; (or)
- dataType arrayRefVar[];
Instantiation of an Array in java
- arrayRefVar=new datatype[size];
Declaration, Instantiation and Initialization of Java Array
We can declare, instantiate and initialize the java array together by:
This comment has been removed by the author.
ReplyDelete