Friday, January 18, 2019
Wednesday, January 9, 2019
Method overloading and null error in Java?
public class Test
{
// Overloaded methods
public void fun(Integer i)
{
System.out.println("fun(Integer ) ");
}
public void fun(String name)
{
System.out.println("fun(String ) ");
}
// Driver code
public static void main(String [] args)
{
Test mv = new Test();
// This line causes error
mv.fun(null);
}
}
Here the method arguments Integer and String both are not primitive data types in Java. That means they accept null values. When we pass a null value to the method1 the compiler gets confused which method it has to select, as both are accepting the null.
public class Test
{
// Overloaded methods
public void fun(Integer i)
{
System.out.println("fun(Integer ) ");
}
public void fun(String name)
{
System.out.println("fun(String ) ");
}
// Driver code
public static void main(String [] args)
{
Test mv = new Test();
Integer arg = null;
// No compiler error
mv.fun(arg);
}
}
Here we wouldn’t get compile time error because we are specifying that the argument is of type Integer, hence the compiler selects the method1(Integer i) and will execute the code inside that.
{
// Overloaded methods
public void fun(Integer i)
{
System.out.println("fun(Integer ) ");
}
public void fun(String name)
{
System.out.println("fun(String ) ");
}
// Driver code
public static void main(String [] args)
{
Test mv = new Test();
// This line causes error
mv.fun(null);
}
}
Here the method arguments Integer and String both are not primitive data types in Java. That means they accept null values. When we pass a null value to the method1 the compiler gets confused which method it has to select, as both are accepting the null.
public class Test
{
// Overloaded methods
public void fun(Integer i)
{
System.out.println("fun(Integer ) ");
}
public void fun(String name)
{
System.out.println("fun(String ) ");
}
// Driver code
public static void main(String [] args)
{
Test mv = new Test();
Integer arg = null;
// No compiler error
mv.fun(arg);
}
}
Here we wouldn’t get compile time error because we are specifying that the argument is of type Integer, hence the compiler selects the method1(Integer i) and will execute the code inside that.
Sometimes unexpected errors can result when overloading a method that takes a variable length argument?
// Java program to illustrate Varargs and ambiguity
class Test
{
// A method that takes varargs(here integers).
static void fun(int ... a)
{
System.out.print("fun(int ...): " +
"Number of args: " + a.length +
" Contents: ");
// using for each loop to display contents of a
for(int x : a)
System.out.print(x + " ");
System.out.println();
}
// A method that takes varargs(here booleans).
static void fun(boolean ... a)
{
System.out.print("fun(boolean ...) " +
"Number of args: " + a.length +
" Contents: ");
// using for each loop to display contents of a
for(boolean x : a)
System.out.print(x + " ");
System.out.println();
}
public static void main(String args[])
{
// Calling overloaded fun() with different parameter
fun(1, 2); //OK
fun(true, false, false); //OK
//fun(); // Error: Ambiguous!
}
}
In above program, the overloading of fun( ) is perfectly correct. However, this program will not compile because of the following call:
fun(); // Error: Ambiguous!According to (JLS 15.2.2), there are 3 phases used in overload resolution: First phase performs overload resolution without permitting boxing or unboxing conversion, Second phase performs overload resolution while allowing boxing and unboxing and Third phase allows overloading to be combined with variable arity methods, boxing, and unboxing. If no applicable method is found during these phases, then ambiguity occurs.
Methods with Varargs alongwith other parameters?
Hare Java uses both the number of arguments and the type of the arguments to determine which method to call.
Example :-
// Java program to demonstrate Varargs
// and overloading.
class Test
{
// A method that takes varargs(here integers).
static void fun(int ... a)
{
System.out.print("fun(int ...): " +
"Number of args: " + a.length +
" Contents: ");
// using for each loop to display contents of a
for(int x : a)
System.out.print(x + " ");
System.out.println();
}
// A method that takes varargs(here booleans).
static void fun(boolean ... a)
{
System.out.print("fun(boolean ...) " +
"Number of args: " + a.length +
" Contents: ");
// using for each loop to display contents of a
for(boolean x : a)
System.out.print(x + " ");
System.out.println();
}
// A method takes string as a argument followed by varargs(here integers).
static void fun(String msg, int ... a)
{
System.out.print("fun(String, int ...): " +
msg + a.length +
" Contents: ");
// using for each loop to display contents of a
for(int x : a)
System.out.print(x + " ");
System.out.println();
}
public static void main(String args[])
{
// Calling overloaded fun() with different parameter
fun(1, 2, 3);
fun("Testing: ", 10, 20);
fun(true, false, false);
}
}
Example :-
// Java program to demonstrate Varargs
// and overloading.
class Test
{
// A method that takes varargs(here integers).
static void fun(int ... a)
{
System.out.print("fun(int ...): " +
"Number of args: " + a.length +
" Contents: ");
// using for each loop to display contents of a
for(int x : a)
System.out.print(x + " ");
System.out.println();
}
// A method that takes varargs(here booleans).
static void fun(boolean ... a)
{
System.out.print("fun(boolean ...) " +
"Number of args: " + a.length +
" Contents: ");
// using for each loop to display contents of a
for(boolean x : a)
System.out.print(x + " ");
System.out.println();
}
// A method takes string as a argument followed by varargs(here integers).
static void fun(String msg, int ... a)
{
System.out.print("fun(String, int ...): " +
msg + a.length +
" Contents: ");
// using for each loop to display contents of a
for(int x : a)
System.out.print(x + " ");
System.out.println();
}
public static void main(String args[])
{
// Calling overloaded fun() with different parameter
fun(1, 2, 3);
fun("Testing: ", 10, 20);
fun(true, false, false);
}
}
Method Overloading and Ambiguity in Varargs in Java
Java uses the type difference to determine which overloaded method to
call. If one method signature is strictly more specific than the other,
then Java chooses it without an error.
Example :-
//Java program to illustrate
//method overloading in varargs
public class varargsDemo
{
public static void main(String[] args)
{
fun();
}
//varargs method with float datatype
static void fun(float... x)
{
System.out.println("float varargs");
}
//varargs method with int datatype
static void fun(int... x)
{
System.out.println("int varargs");
}
//varargs method with double datatype
static void fun(double... x)
{
System.out.println("double varargs");
}
}
Output:
Example :-
//Java program to illustrate
//method overloading in varargs
public class varargsDemo
{
public static void main(String[] args)
{
fun();
}
//varargs method with float datatype
static void fun(float... x)
{
System.out.println("float varargs");
}
//varargs method with int datatype
static void fun(int... x)
{
System.out.println("int varargs");
}
//varargs method with double datatype
static void fun(double... x)
{
System.out.println("double varargs");
}
}
Output:
int varargs
The rule that the most specific method is chosen according to type promotion.
- double > float
- float > long
- long > int
- int > char
- int > short
- short > byte
Difference between abstraction and encapsulation?
Encapsulation is hiding the implementation details which may or may not be for generic or specialized behavior(s).
Abstraction is providing a generalization (say, over a set of behaviors).
Abstraction is providing a generalization (say, over a set of behaviors).
Is inheritance necessary for encapsulation, abstraction and polymorphism?
- Is Encapsulation possible without inheritance?
- Is Abstraction possible without inheritance?
- Is Polymorphism possible without inheritance?
Is polymorphism possible without inheritance?
Types of Polymorphism
Cardelli defines several types of polymorphism in this article:- Universal
- parametric
- inclusion
- Ad-hoc
- overloading
- coercion
1.) Cases of covariance and contravariance with generics.
2.) Arrays are Serializable and Cloneable although this is not evident anywhere in the type hierarchy.
3.) Concatenation of strings and numbers or of a string plus some other object. Consider also the cases of boxing and unboxing of primitives.
4.) cases of polymorphism (coercion and overloading) are not at all related to inheritance.
Examples
Inclusion
List<Integer> myInts = new ArrayList<Integer>();
|
And in other cases, the relationships are not even evident in the API
Cloneable clone = new int[10];
Serializable obj = new Object[10]
Parametric
The same algorithm can be used to filter all kinds of lists with all
kinds of predicates without having to repeat a single line of code for
every possible type of list.
double sum = 1 + 2.0;
Integer and floating-point arithmetic are totally different. Applying
the plus operator to two operands of different types here is impossible
without some form of coercion.Types of Polymorphism
Cardelli defines several types of polymorphism in this article:- Universal
- parametric
- inclusion
- Ad-hoc
- overloading
- coercion
Wikipedia provides a good definition:
In object-oriented programming, subtype polymorphism or inclusion polymorphism is a concept in type theory wherein a name may denote instances of many different classes as long as they are related by some common super class. Inclusion polymorphism is generally supported through subtyping, i.e., objects of different types are entirely substitutable for objects of another type (their base type(s)) and thus can be handled via a common interface. Alternatively, inclusion polymorphism may be achieved through type coercion, also known as type casting.Another Wikipedia article called Polymorphism in object-oriented programming seems to answer your questions as well.
In Java
This subtyping feature in Java is achieved, among other means, through the inheritance of classes and interfaces. Although the subtyping features of Java may not be evident in terms of inheritance all the time. Take for example the cases of covariance and contravariance with generics. Also, arrays are Serializable and Cloneable although this is not evident anywhere in the type hierarchy. It can also be said that through primitive widening conversion the numeric operators in Java are polymorphic, in certain cases even accepting totally unrelated operands (i.e. concatenation of strings and numbers or of a string plus some other object). Consider also the cases of boxing and unboxing of primitives. These latter cases of polymorphism (coercion and overloading) are not at all related to inheritance.Examples
InclusionList<Integer> myInts = new ArrayList<Integer>();
This is the case to which your question seems to refer i.e. when
there is an inheritance or implementation relationship between the
types, as in this case where ArrayList implements List.As I mentioned, though, when you introduce Java generics, some time the rules of subtyping get fuzzy:
List<? super Number> myObjs = new ArrayList<Object>();
List<? extends Number> myNumbers = new LinkedList<Integer>();
And in other cases, the relationships are not even evident in the APICloneable clone = new int[10];
Serializable obj = new Object[10]
Even so, all these, according to Cardelli, are forms of universal polymorphism.Parametric
public <T> List<T> filter(Predicate<T> predicate, List<T> source) {
List<T> result = new ArrayList<>();
for(T item : source) {
if(predicate.evaluate(item)){
result.add(item);
}
return result;
}
}
The same algorithm can be used to filter all kinds of lists with all
kinds of predicates without having to repeat a single line of code for
every possible type of list. The type of the actual list and the type of
predicate are parametric. See this example with lambda expressions
available in JDK 8 Preview (for the brevity of predicate implementation).filter(x -> x % 2 == 0, asList(1,2,3,4,5,6)); //filters even integers
filter(x -> x % 2 != 0, asList(1L,2L,3L,4L,5L,6L)); //filters odd longs
filter(x -> x >= 0.0, asList(-1.0, 1.0)); //filters positive doubles
According to Cardelli, this is a form of universal polymorphism.Coercion
double sum = 1 + 2.0;
Integer and floating-point arithmetic are totally different. Applying
the plus operator to two operands of different types here is impossible
without some form of coercion.In this example, the types integer and double, are automatically coerced (converted) to type double without an explicit cast. The entire expression is promoted to double. This is so because in Java we have primitive widening conversions.
According to Cardelli, this form of automatic coercion is a form of ad-hoc polymorphism provided for the plus operator.
There are languages in which you could not even sum an integer and a floating-point number without an explicit cast (i.e. AFAIK, SML, in which, by the way, parametric polymorphism is key to overcome this kind of problems).
Overloading
double sum = 2.0 + 3.0;
String text = "The sum is" + sum;
The plus operator here means two different things depending on the
arguments used. Evidently, the operator has been overloaded. This
implies it has different implementations depending on the types of
operands. According to Cardelli, this is a form of ad-hoc polymorphism
provided for the plus operator.What is the purpose of polymorphism?
Polymorphism. Generally, the ability to
appear in many forms. In object-oriented programming, polymorphism
refers to a programming language's ability to process objects
differently depending on their data type or class. More specifically, it
is the ability to redefine methods for derived classes.
IMPORTANT POINTS ABOUT POLYMORPHISM
- A functionality can behave differently for different instances
- The behavior depends on the type of data used in the operation
- Polymorphism is used for implementing inheritance.
ADVANTAGES OF POLYMORPHISM
- It helps programmers reuse the code and classes once written, tested and implemented. They can be reused in many ways.
- Single variable name can be used to store variables of multiple data types(Float, double, Long, Int etc).
- Polymorphism helps in reducing the coupling between different functionalities.
Type Conversion of data Type
Assigning a value of one type to a variable of another type is known as Type Casting. If the data types are compatible, then Java will perform the conversion
automatically known as Automatic Type Conversion and if not then they
need to be casted or converted explicitly.
Example :
Example :
Example :
int x = 10;
byte y = (byte)x;
In Java, type casting is classified into two types,- Widening Casting(Implicit)
- Narrowing Casting(Explicitly done)
Widening or Automatic type converion
Automatic Type casting take place when,- the two types are compatible
- the target type is larger than the source type
public class Test
{
public static void main(String[] args)
{
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}
O/P :-
Int value 100
Long value 100
Float value 100.0
Narrowing or Explicit type conversion
When you are assigning a larger type value to a variable of smaller type, then you need to perform explicit type casting.Example :
public class Test
{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required
System.out.println("Double value "+d);
System.out.println("Long value "+l);
System.out.println("Int value "+i);
}
}
O/P :
Double value 100.04
Long value 100
Int value 100
Tuesday, January 8, 2019
Can be call this() and supper() togther in same method and constructure ?
There is a difference between
Both
Constructor call must always be the first statement. So we can not have two statements as first statement, hence either we can call
Example :-
class TempB {
TempB() // default constructor
{
System.out.println("default constructor");
}
TempB(int x) // one parameter constructor
{
System.out.println("value of x is" + x);
}
}
class C extends TempA {
C() // default constructor
{
super();
this(10);
System.out.println("default constructor");
}
C(int x) // one parameter constructor
{
this(10, 20);
System.out.println("value of x is" + x);
}
C(int x, int y) // two parameter constructor
{
System.out.println("Add result is" + (x + y));
}
public static void main(String[] args) {
new C();
}
}
In above example first statement is correct whare use supper() but after use this. It is not correct because it break the contract of calling first statement.
super()
and this()
.super()
- calls the base class constructor whereasthis()
- calls current class constructor.Both
this()
and super()
are constructor calls.Constructor call must always be the first statement. So we can not have two statements as first statement, hence either we can call
super()
or we can call this()
from the constructor, but not both.Example :-
class TempB {
TempB() // default constructor
{
System.out.println("default constructor");
}
TempB(int x) // one parameter constructor
{
System.out.println("value of x is" + x);
}
}
class C extends TempA {
C() // default constructor
{
super();
this(10);
System.out.println("default constructor");
}
C(int x) // one parameter constructor
{
this(10, 20);
System.out.println("value of x is" + x);
}
C(int x, int y) // two parameter constructor
{
System.out.println("Add result is" + (x + y));
}
public static void main(String[] args) {
new C();
}
}
In above example first statement is correct whare use supper() but after use this. It is not correct because it break the contract of calling first statement.
Difference Between Constructor Overloading and Constructor Chaining?
Constructor Overloading |
Constructor Chaining |
1. Constructor overloading allows a class to have more than one constructor that have the same name as that of the class but differ only in terms of number or type of parameters. | 1. Constructor chaining is a process of calling the one constructor from another constructor with respect to current object. |
2. Constructor overloading is done to construct object in different ways. | 2. Constructor chaining is done to call one constructor from another constructor. |
3. Constructor overloading is achieved by declaring more than one constructor with same name but different parameters in a same class. | 3. Constructor chaining is achieved by this() method. |
4. Constructor overloading is flexible which allows us to create object in different way. | 4. Constructor chaining is useful when we have many constructors in the class and want to reuse that constructor. |
What is the need of Constructor chaining in java?
- Calling a constructor from another constructor , is known as constructor chaining.If we want to access the properties of any constructor then we have to use constructor chaining.
- We know that constructor is neither static nor non static. So we can’t inherit the constructor.But using constructor chaining we can acquire the properties of another constructor.
- There is two ways to achieve the constructor chaining:-
2.) this() (call to this) is used to call the same class constructor. That mean we can achieve the properties of constructor which are present in the same class. For using this() constructor overloading is necessary. Without constructor overloading we can’t get the properties of same class.
Examples :-
Step 1.)
class Temp
{
Temp() //default constructor
{
this(10);
System.out.println("default constructor");
}
Temp(int x) //one parameter constructor
{
this(10,20);
System.out.println("value of x is" +x);
}
Temp(int x,int y) //two parameter constructor
{
System.out.println("Add result is" +(x+y));
}
public static void main(String[] args)
{
new Temp();
}
}
Explanation of Program:- The class Temp contains three constructors: default constructor, one parameter constructor and two parameter constructor.
- The statement : new Temp(); calls a default constructor. Here it calls the one parameter constructor with the help of this(10);
- Then control goes to two parameter constructor with the help of first statement in constructor this(10,20),
- In two parameter constructor the first statement will be executed which prints the “add result is 30”
- Then control goes to one parameter constructor and it executes the second statement which prints “value of x is 10”
- Then control goes to default constructor and it also execute the second statement that prints “default constructor”
Important Points to Remember About Constructor Chaining:
- Whenever you are achieving a constructor chaining using a this() method then it must be the first line in any constructor.
- Whenever we are achieving a constructor chaining using a this() method then there must be atleast one constructor which is not having a this() method as a first line.
- Constructor chaining can be achieved in any order.
- Whenever you want to provide the certain common resources to each object of a class rather than putting the code of each resource in a single constructor, make a separate constructor for each resource and then create their chain.
Is serialVersionUID inherited by subclasses, if I have default serialVersionUID in superclass? Similar to when the superclass is serializable then subclasses are also serializable.
Answer :
Is serialVersionUID inherited by subclasses, if I have default serialVersionUID in superclass?Yes it is inherited, but no, Serialization won't consider it as belonging to the subclass and not use it.
Similar to when the superclass is serializable then subclasses are also serializable.It isn't similar.
Serializable
is an interface and it is subject only to the rules of the language. serialVersionUID
is a special field with its own rules enforced by ObjectInputStream.
How are constructors called during serialization and deserialization?
When there is one class implementing serializable?
When there is parent/child relationship and only child implements serializable?
When there is parent/child relationship and both parent and child implements serializable?
Ans :
An object is serializable only if its class or its superclass implements the
Serializable
(orExternalizable
) interface.
- An object is serializable (itself implements the Serializable
interface) even if its superclass is not. However, the firstsuperclass
in the hierarchy of the serializable class, that does not implements
Serializable interface, MUST have a no-arg constructor. If this is
violated, readObject() will produce a
java.io.InvalidClassException
in runtime. - The no-arg contructor of every non-serializable superclass will run when an object is deserialized. However, the deserialized objects? constructor does not run when it is deserialized.
- The class must be visible at the point of serialization.
- All primitive types are serializable.
- Transient fields (with transient modifier) are NOT serialized, (i.e., not saved or restored). A class that implements Serializablemust mark -transient fields of classes that do not support serialization (e.g., a file stream).
Subscribe to:
Posts (Atom)