Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number in java how it work without a subclass?

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;
like image 304
ahmed khattab Avatar asked Jul 25 '17 10:07

ahmed khattab


People also ask

Which class does not have a subclass?

According to java standard we cant create sub class of a final class.

What is the point of a subclass in Java?

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.

What is subclass and non subclass 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.

Which class Cannot be a subclass in Java?

A class that is declared final cannot be subclassed. This is particularly useful, for example, when creating an immutable class like the String class.


1 Answers

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;
}
like image 154
ΦXocę 웃 Пepeúpa ツ Avatar answered Sep 28 '22 03:09

ΦXocę 웃 Пepeúpa ツ