Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Java.Lang.Math not abstract?

The "abstract" keyword means you cannot create an instance of the class (an object).

Java.Lang.Math is preceded with the following keywords

public final class Math {
...
}

But no "abstract" keyword. The class simply provides a collection of related static variables and methods, like PI and sin().

Static means that those variables/methods can't be unique between different instances of the object (there is only one copy of those variables/methods associated with the class itself). So why even allow the programmer to create an instance of the class? Why not precede with "abstract"?

like image 353
Niko Bellic Avatar asked Jul 22 '14 19:07

Niko Bellic


2 Answers

final and abstract keywords can't be applied together because final class can't be overridden and abstract classes are meant for override.

A class that is declared final cannot be subclassed that is used for creating an immutable class such as String

It's better explained under JSL section - 8.1.1. Class Modifiers

  1. An abstract class is a class that is incomplete, or to be considered incomplete.

  2. A class can be declared final if its definition is complete and no subclasses are desired or required.

both above statements are contradicting each-other.


If you want to read more about then have a look at Java Tutroial on A Strategy for Defining Immutable Objects

  1. Don't provide "setter" methods — methods that modify fields or objects referred to by fields.
  2. Make all fields final and private.
  3. Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
  4. If the instance fields include references to mutable objects, don't allow those objects to be changed:
    • Don't provide methods that modify the mutable objects.
    • Don't share references to the mutable objects.
like image 142
Braj Avatar answered Nov 09 '22 15:11

Braj


java.lang.Math is a Utility class (contains only static utility methods).

Correct way to define utility class is to make it final so that no other class can extend it and to have private no-args constructor so that no one can create an instance of the class.

So you won't be able to create instance of class any how. However if you go by abstract approach, you cannot use final and there is no way you can prevent it from being extended. Hence former approach is better.

like image 13
Gladwin Burboz Avatar answered Nov 09 '22 15:11

Gladwin Burboz