Unable to Create Math object in Java? - java

I am trying to create an object of the Math in Java. Ideally there is no need of creating such an instance as it only has static methods and parameters. I just want to create it whether it will allow me or not. So when I am creating a math class object, compiler error is displayed saying that the Math class constructor is not visible.
But I looked into the Math class code and there is no explict constructor provided, so java will provide a default constructor, which can be accessed outside.

This is correct behavior. The constructor for Math is private as it only contains static utility methods:
private Math() {}

This is from Java docs.
public final class Math {
/**
* Don't let anyone instantiate this class.
*/
private Math() {}
}
The documentation comment itself is sufficient to answer your question.

If you look at the Math class definition, its constructor is private:
private Math() {}
This means that the creator of the class does not want the user to be able to create instances of this class. It makes sense because it's a utility class, which means any method inside the class does not depened on the state of the object. You just need to pass the method parameter values and it will simply give you the intended result. That's why all the methods inside the Math class are static.

You can't do it because its constructor is private. You don't see the constructor in the API because private methods are not listed.
For example take this example:
public class SampleClass {
private static int var1 = 1;
private static int var2 = 1;
private static int var3 = 1;
private SampleClass () {
// This constructor will prevent the default constructor from being invoked
}
public static void runMethod1() {
System.out.println("Value is:" + var1);
}
public static void runMethod2() {
System.out.println("Value is:" + var2);
}
public static void runMethod3() {
System.out.println("Value is:" + var3);
}
}
You can only create an instance of this class from inside the same class. If you try to create it from elsewhere, you will fail.

Related

How to call multiple methods of Anonymous class?

In below chunk of code, I am creating an anonymous class by extending LinkedList but don't know how can I call-up multiple methods outside the anonymous class. I am able to call one method though as mentioned in end by .dummy1()
void methodOC_3() {
int x = 0;
new LinkedList() {
/**
*
*/
private static final long serialVersionUID = -2091001803840835817L;
// Anonymous class is extending class LinkedList
public void dummy1() {
//x=4; Will give error, Or declare x as final variable
//you can read it As Of Now, since it is effectively final.
System.out.println(x);
}
#SuppressWarnings("unused")
public void dummy2() {
dummy1();
System.out.println("Hey there :) ");
}
}.dummy1();
}
I have just started exploring anonymous classes and inner classes. Please let me know if I am missing anything.
You can't.
The only way to be able to call multiple methods is to assign the anonymous class instance to some variable.
However, in your LinkedList sub-class example you can only assign the anonymous class instance to a LinkedList variable, which will only allow you to call methods of the LinkedList class.
If your anonymous class instance implemented some interface that has dummy1() and dummy2() methods, you could assign that instance to a variable of that interface type, which would allow you to call both dummy1() and dummy2().
Only way to call anonymous class's method is by using reflection with reference variable 'linkedList'
LinkedList linkedList = new LinkedList() { ... }
linkedList.getClass().getMethod("dummy1").invoke();
Why exactly do you want your class anonymous? If it's anonymous, you can't refer to it, and this is exactly your problem. So, just don't make it anonymous! You can define local classes within methods:
public static void methodOC_3() {
int x = 0;
class MyList<X> extends java.util.LinkedList<X> {
/**
*
*/
private static final long serialVersionUID = -2091001803840835817L;
public void dummy1() {
//x=4; Will give error, Or declare x as final variable
//you can read it As Of Now, since it is effectively final.
System.out.println(x);
}
public void dummy2() {
dummy1();
System.out.println("Hey there :) ");
}
}
MyList<String> a = new MyList<String>();
a.dummy1();
a.dummy2();
}
This is very useful especially if you want to define multiple mutually recursive helper methods inside another method, without polluting the name space.

How can a child class' overriden method be accessed statically?

So I already know it's impossible to have a static method in an abstract class. However, is there a way for an overridden method in its child class to be accessed without instantiating it?
For example, let's say I have two classes, an abstract class element and its child class Hydrogen, as shown below. This assumes that I will have multiple similar classes, such as Helium, Boron, etc. which are all child classes of Element.
public abstract class Element {
public abstract double getMolarMass();
}
public final Hydrogen extends Element {
#Override
public double getMolarMass() {
return 1.008;
}
}
How would I be able to be able to call the getMolarMass method without having to instantiate the Hydrogen object?
It seems to me you want to have access to constants in your subclasses while at the same time allowing for polymorphic behavior involving these values. You can have a constant and also return it from your method:
public final class Hydrogen extends Element {
public static final double MOLAR_MASS = 1.008;
#Override
public double getMolarMass() {
return MOLAR_MASS;
}
}
Then, you can access the constant statically: Hydrogen.MOLAR_MASS.
What you want to achieve is creating an Enum. There's an enum keyword allowing you to directly do what you seemingly want to achieve.
An enum is effectively a final class with several public static final member variables, which hold references to instances of the class.
enum Element
{
Hydrogen(1.0),
Helium(2.0),
...;
private double mass;
private Element(double masss)
{
this.mass = mass;
}
public double getMasss()
{
return mass;
}
}
You can access the fields directly, e.g.:
Element e = Element.Helium;
System.out.println("The mass of " + e + " is " + e.getMass());
if the method is not static then you can not call it statically,
on the other hand overriding static methods makes no sense and is not allowed in java...

Is there any difference when a field is static or not when it belongs to an abstract class?

public abstract class Test {
private static int value = 100;
}
And
public abstract class Test {
private int value = 100;
}
Since Test is abstract, it can't be instantiated, and therefore it doesn't make any difference whether value is static or not, right?
Is there any difference when a field is static or not when it belongs to an abstract class?
Yes, there is. Even thou your class is abstract, it can have non-abstract non-static methods working with non-static private fields. It is usefull sometimes.
Dummy exaple:
Consider following: you want to hold one integer and give everyone the ability to change it, but you dont want them to set negative values, or values bigger then 15, but the condition isn't known (in general) by everyone, so you want to ensure that when someone sets incorect value, it gets fixed automaticly.
Here is one possible solution:
abstract class MyInt {
private int myInt;
public int getMyInt() {
return myInt;
}
public void setMyInt(int i) {
myInt = checkMyInt(i);
}
protected abstract int checkMyInt(int i);
}
Now you can inplement any logic in checkMyInt() and hand over the instance declared as MyInt
pastebin exaplme
PS: this probably isnt the best solution and i would use interfaces here, but as an example it is enought i hope
Abstract classes can't be instantiated directly. But the whole point of abstract classes is to have subclasses that are instantiated:
public abstract class Test
protected int value;
}
public class TestImpl extends Test {
public TestImpl(int value) {
this.value = value;
}
}
In the above example, each instance of TestImpl (and thus of Test) has its own value. With a static field, the field is scoped to the Test class, and shared by all instances.
The difference between static and non-static fields is thus exactly the same as with any other non-abstract class.
An abstract class is a normal (base) class, just declared to be missing some things, like abstract methods.
So there is definite a difference.

Use of a private constructor

I'm a begginer programmer for Android and I found some code over the internet and I couldn't get what this "Class not meant to be instantiated" means?! Also what's the use of it. I would be very happy if somebody could help here.
public class Settings
{
//some code
private Settings() {} // Class not meant to be instantiated
//some code
}
The constructor is private so only the class itself can create instances. There are several reasons for doing this. A couple off the top of my head...
The class is a "utility" class that only contains static methods and so instantiating it would make no sense. As the class is commented "Class not meant to be instantiated" I guess this is the most likely reason.
The class itself controls its own lifecycle and provides methods for creating instances. For example if the class is a lazy singleton it might provide a method that creates an instance when first called and return this instance on subsequent calls.
It is a private constructor. This means that outside classes cannot create new instances using the default constructor.
A little more info
All Objects in Java have a default constructor:
public MyObject() {}
That is how you can have this class:
public class MyObject{}
and still be able to call:
MyObject mObj = new MyObject();
Private Constructors
Sometimes a developer may not want this default constructor to be visible. Adding any other constructor will nullify this constructor. This can either be a declared constructor with empty parameters (with any of the visibility modifiers) or it can be a different constructor all together.
In the case above, it is likely that one of the following models is followed:
The Settings object is instantiated within the Settings class, and is where all the code is run (a common model for Java - where such a class would also contain a static main(String[] args) method).
The Settings object has other, public constructors.
The Settings object is a Singleton, whereby one static instance of the Settings Object is provided to Objects through an accessor method. For example:
public class MyObject {
private static MyObject instance;
private MyObject(){}//overrides the default constructor
public static MyObject sharedMyObject() {
if (instance == null)
instance = new MyObject();//calls the private constructor
return instance;
}
}
This inner construct
private Settings() {}
is a constructor for Settings instances. Since it is private, nobody can access it (outside of the class itself) and therefore no instances can be created.
The constructor is private so its not meant to be called by anything outside of the class
It's not a nested class, it's a constructor. A private constructor means that you can't construct instances of this class from outside, like this:
Settings s = new Settings(); //Compilation error! :(
Now, if a class can't be instantiated, what could it be for? The most likely reason for this is that the class would return instances of itself from a static method, probably as a singleton. The settings are normally global to the program, so a singleton pattern really fits here. So there would be a static method that goes kind of like this
static private TheOnlySettings = null;
static public getSettings()
{
if(TheOnlySettings == null)
TheOnlySettings = new Settings(); //Legal, since it's inside the Settings class
return TheOnlySettings;
}
See if that's indeed the case.
As other have mentioned, a class having private constructors cannot be instantiated from outside the class. A static method can be used in this case.
class Demo
{
private Demo()
{
}
static void createObjects()
{
Demo o = new Demo();
}
}
class Test
{
public static void main (String ...ar)
{
Demo.createObjects();
}
}
We can have private constructor . Below program depicts the use of private constructor with a static function
class PrivateConstructor {
private:
PrivateConstructor(){
cout << "constructor called" << endl;
}
public:
static void display() {
PrivateConstructor();
}
};
int main() {
PrivateConstructor::display();
}

Odd java assignment rules for final

I've come across some odd behavior in assignment of final variables. You can assign a final varible in a constructor to initialize it, which makes sense. However you can't do the same in a subclass, even if the final variable is a member of the subclass -
public class FinalTest {
public final String name;
public FinalTest()
{
name = "FinalTest";
}
public static class FinalTestSubclass extends FinalTest {
public FinalTestSubclass()
{
name = "FinalTestSubclass"; //<---- this won't compile, assignment to final variable.
}
}
}
Can someone think of a good reason why this should/would work this way?
Every constructor of a subclass must invoke a constructor of the superclass as its first operation. Every final member variable must be initialized before a constructor completes. A final variable can be assigned only once. Given those rules, it is impossible for a subclass constructor to directly assign a value to a final superclass' member.
Making exceptions would increase complexity and create "gotchas" in exchange for limited additional utility.
A practical solution is to provide a superclass constructor that takes a value to be assigned to the final member. This can be protected or package-private if desired. If the superclass is outside of your control, there's a good chance that allowing derived classes to break its assumptions about the finality of its members would cause other problems.
If you were allowed to assign a value to name in FinalTestSubClass it would mean that the value assigned in FinalTest was not actually the final value.
If your example was valid, then this would mean that name could have different values (based upon which class was instantiated), making the final modifier pretty much redundant.
A better question is, why should the behavior you desire be allowed?
informally, final fields should have been initialized when the constructor is finished.
in your subclass constructor, super() has been called implicitly, the constructor of the super class is finished, the final fields in the super class should not be modified.
you may want this instead:
class A
final String s;
A(String s){ this.s = s; }
A() { this("default"); }
class B extends A
B(){ super("B's default"); }
This is standard behavior in Java
The key word final can by used in multiple way, for class close the possibility to inherite from it, for method to override it, for variable allow to be assigned only once in simply words.
For your case this variable is allready assigned in super class,
what You can do is
public class FinalTest {
public final String name = "FinalTest";
public FinalTest()
{
}
public static class FinalTestSubclass extends FinalTest {
public final String name = "FinalTestSubclass";
public FinalTestSubclass()
{
}
}
}
Read more about final variables
In reply to your comment to matt's answer; you can achieve determining the constant in the subclass by passing it in the constructor:
public class FinalTest {
public final String name;
public FinalTest()
{
this("FinalTest");
}
protected FinalTest(String nameConstant)
{
name = nameConstant;
}
public static class FinalTestSubclass extends FinalTest {
public FinalTestSubclass()
{
super("FinalTestSubclass");
}
}
}

Categories

Resources