I want to know why the result of this code:
Number x = 3;
System.out.println(x.intValue());
System.out.println(x.doubleValue());
generates
3
3.0
as Number is an abstract class in Java.
So when I need to use it - I could use it with some it's subclasses like Integer, Double ...etc. Now I want to know how exactly this part of code works:
Number x = 3;
According to java standard we cant create sub class of a final class.
A subclass is a class that describes the members of a particular subset of the original set. They share many of characteristics of the main class, but may have properties or methods that are unique to members of the subclass. You declare that one class is subclass of another via the "extends" keyword in Java.
In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories: subclass (child) - the class that inherits from another class. superclass (parent) - the class being inherited from.
A class that is declared final cannot be subclassed. This is particularly useful, for example, when creating an immutable class like the String class.
when you do:
Number x = 3;
System.out.println(x.intValue());
System.out.println(x.doubleValue());
Following will happen:
Number x = 3;
this will declare x as int, and will be auto boxed to an object of the class Integer
turning this: Number x = 3;
into Number x = new Integer(3);
then here:
System.out.println(x.intValue());
intValue
is implemented as:
public int intValue() {
return value;
}
System.out.println(x.doubleValue());
and doubleValue
is implemented as:
public double doubleValue() {
return (double)value;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With