POLYMORPHISM
POLYMORPHISM
POLYMORPHISM:- Polymorphism came from the two GreeK words poly means
many and morphs meaning forms. The ability to exit in different forms is called polymorphism.
In java a variable an object or a method can exit in different forms, this performing various task
depending on the context.
There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.
If you overload a static method in Java, it is the example of compile time polymorphism.
Method signature:-
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
Write a program to create Sample class which contains two methods with the same name
but with different signatures.
Class Sample
class Poly
s.add(30,40,50);
In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.
There are many differences between method overloading and method overriding in java. A list
of differences between method overloading and method overriding are given below:
Polymorphism with static method:-static method is a method whose single copy in memory is shared by
all the objects of the class.
class One
System.out.println(“”+(x*x));
}
}
class Poly
o.calculate(25);
2. when the programmer does not want others to override his method, he should declare his method as
final.
System.out.println(“Hello”);
}
class B
void method2()
A.method1();
Final class:-
A final class is a class which is declared as final. Final keyword before class prevents inheritance. This
means sub classes can not be created to a final class.
Type casting: Convert a value from one data type to another data type is known
as type casting.
1. byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean is not done
automatically. Also, the char and Boolean data types are not compatible with each other.
1. double -> float -> long -> int -> char -> short -> byte
In the following example, we have performed the narrowing type casting two times. First, we
have converted the double type into long data type after that long data type is converted into
int type.
Ex:- write a java program for NarrowingTypeCasting
INTERFACE IN JAVA
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods
in the Java interface, not method body. It is used to achieve abstraction and multiple
inheritance in java.
In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.
interface printable{
void print();
}
class Demo implements printable
{
public void print(){System.out.println("Hello");
}
public static void main(String args[]){
Demo obj = new Demo();
obj.print();
}
}
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
If you are not using any IDE, you need to follow the syntax given below:
1. javac -d directory javafilename
For example
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep
the package within the same directory, you can use . (dot).
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to
the current package.
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
1. Subpackage in java
2. Package inside the package is called the subpackage. It should be created to categorize
the package further.
3. Let's take an example, Sun Microsystem has definded a package named java that
contains many classes like System, String, Reader, Writer, Socket etc. These classes
represent a particular group e.g. Reader and Writer classes are for Input/Output
operation, Socket and ServerSocket classes are for networking etc and so on. So, Sun has
subcategorized the java package into subpackages such as lang, net, io etc. and put the
Input/Output related classes in io package, Server and ServerSocket classes in net
packages and so on.
Example of Subpackage
package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
To Compile: javac -d . Simple.java
Output:Hello subpackage
In Java, an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked Exceptions
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are
known as checked exceptions. For example, IOException, SQLException, etc. Checked exceptions
are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception code. It
means we can't use try block alone. The try block must be followed by either catch or
finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is executed
whether an exception is handled or not.
throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an
exception in the method. It doesn't throw an exception. It is always used with method
signature.
Java throws keyword
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception. So, it is better for the programmer to provide
the exception handling code so that the normal flow of the program can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers' fault that he is not
checking the code before it being used.
JavaExceptionDemo.java
Testthrows1.java
1. import java.io.IOException;
2. class Testthrows1{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{
7. m();
8. }
9. void p(){
10. try{
11. n();
12. }catch(Exception e){System.out.println("exception handled");}
13. }
14. public static void main(String args[]){
15. Testthrows1 obj=new Testthrows1();
16. obj.p();
17. System.out.println("normal flow...");
18. }
19. }
There are many differences between throw and throws keywords. A list of differences between
throw and throws are given below:
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
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.
1. interface A{
2. void a();
3. void b();
4. void c();
5. void d();
6. }
7.
8. abstract class B implements A{
9. public void c(){System.out.println("I am c");}
10. }
11.
12. class M extends B{
13. public void a(){System.out.println("I am a");}
14. public void b(){System.out.println("I am b");}
15. public void d(){System.out.println("I am d");}
16. }
17.
18. class Test5{
19. public static void main(String args[]){
20. A a=new M();
21. a.a();
22. a.b();
23. a.c();
24. a.d();
25. }
26. }
Output:I am a
I am b
I am c
I am d