Odd java assignment rules for final - java

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");
}
}
}

Related

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.

Meaning of the Private visibility modifier

In the class 'Tosee' below, hiddenInt is visible when I call s.hiddenInt.
However, when I create a "ToSee" object in another class, 'CantSee', the private variable isn't visible. Why is this so? I was under the impression that private means that in any instance of a class, the client cant see that particular instance variable or method? Why then am I able to see hiddenInt in the main method of 'ToSee'?
public class ToSee {
private int hiddenInt = 5;
public static void main(String[] args) {
ToSee s = new ToSee();
System.out.println(s.hiddenInt);
}
}
public class CantSee {
public static void main(String[] args) {
ToSee s = new ToSee();
System.out.println(s.hiddenInt);
}
}
Private in Java means the variable or method is only accessible within the class where it is declared. If your impression about private was true, it will not be accessible anywhere ever which makes it completely useless.
A main method has special connotations in Java, yet it's still a method belonging to a particular class.
Private fields in the enclosing class are accessible to the main method, either through a local instance (in the case of instance fields) or directly (in the case of static fields).
The modifier private makes a variable or method private to the type (class) it is declared in. So only this class can see it.
You can see the variable hiddenInt in ToSee.main because ToSee.main is a static method of the TooSee class. Thus it can access all private variables of a ToSee, either static or instance variables.
Private does also NOT mean private to an instance. An instance of one class can access the private variables of another instance of the same class.
public class ToSee {
private int hiddenInt = 5;
public void printInt(ToSee toSee){
System.out.println(toSee.hiddenInt);
}
public static void main(String[] args) {
ToSee tooSee1 = new ToSee();
ToSee tooSee2 = new ToSee();
tooSee2.hiddenInt = 10;
tooSee1.printInt(tooSee2); // will output 10
}
}
I was under the impression that private means that in any instance of a class,
the client cant see that particular instance variable or method?
Incorrect! Private access modifier simply means that the variable on which it is used will be accessible only in the enclosing class. Period. Since your main() method is in ToSee class which is where you have the hiddenInt private instance variable, it is visible. Where as in case of CantSee class which is not in the ToSee class it is not visible(you need to use getter/setter methods.)
private means invisible to any code outside of the outermost enclosing class it is present in. Since the CantSee class is separate from the ToSee class it cannot see the private field. If CantSee and ToSee were both members of the same class, or one was a member of the other, then you would be able to read the private field. A few examples of structures in which the private field is readable follow :
public class Outer {
public class ToSee {
...
}
public class CantSee {
...
}
}
or
public class CantSee {
...
public class ToSee {
...
}
}

Unable to Create Math object in 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.

What is the use of a private static variable in Java?

If a variable is declared as public static varName;, then I can access it from anywhere as ClassName.varName. I am also aware that static members are shared by all instances of a class and are not reallocated in each instance.
Is declaring a variable as private static varName; any different from declaring a variable private varName;?
In both cases it cannot be accessed as ClassName.varName or as ClassInstance.varName from any other class.
Does declaring the variable as static give it other special properties?
Of course it can be accessed as ClassName.var_name, but only from inside the class in which it is defined - that's because it is defined as private.
public static or private static variables are often used for constants. For example, many people don't like to "hard-code" constants in their code; they like to make a public static or private static variable with a meaningful name and use that in their code, which should make the code more readable. (You should also make such constants final).
For example:
public class Example {
private final static String JDBC_URL = "jdbc:mysql://localhost/shopdb";
private final static String JDBC_USERNAME = "username";
private final static String JDBC_PASSWORD = "password";
public static void main(String[] args) {
Connection conn = DriverManager.getConnection(JDBC_URL,
JDBC_USERNAME, JDBC_PASSWORD);
// ...
}
}
Whether you make it public or private depends on whether you want the variables to be visible outside the class or not.
Static variables have a single value for all instances of a class.
If you were to make something like:
public class Person
{
private static int numberOfEyes;
private String name;
}
and then you wanted to change your name, that is fine, my name stays the same. If, however you wanted to change it so that you had 17 eyes then everyone in the world would also have 17 eyes.
Private static variables are useful in the same way that private instance variables are useful: they store state which is accessed only by code within the same class. The accessibility (private/public/etc) and the instance/static nature of the variable are entirely orthogonal concepts.
I would avoid thinking of static variables as being shared between "all instances" of the class - that suggests there has to be at least one instance for the state to be present. No - a static variable is associated with the type itself instead of any instances of the type.
So any time you want some state which is associated with the type rather than any particular instance, and you want to keep that state private (perhaps allowing controlled access via properties, for example) it makes sense to have a private static variable.
As an aside, I would strongly recommend that the only type of variables which you make public (or even non-private) are constants - static final variables of immutable types. Everything else should be private for the sake of separating API and implementation (amongst other things).
Well you are right public static variables are used without making an instance of the class but private static variables are not. The main difference between them and where I use the private static variables is when you need to use a variable in a static function. For the static functions you can only use static variables, so you make them private to not access them from other classes. That is the only case I use private static for.
Here is an example:
Class test {
public static String name = "AA";
private static String age;
public static void setAge(String yourAge) {
//here if the age variable is not static you will get an error that you cannot access non static variables from static procedures so you have to make it static and private to not be accessed from other classes
age = yourAge;
}
}
Is declaring a variable as private static varName; any different from
declaring a variable private varName;?
Yes, both are different. And the first one is called class variable because it holds single value for that class whereas the other one is called instance variable because it can hold different value for different instances(Objects). The first one is created only once in jvm and other one is created once per instance i.e if you have 10 instances then you will have 10 different private varName; in jvm.
Does declaring the variable as static give it other special
properties?
Yes, static variables gets some different properties than normal instance variables. I've mentioned few already and let's see some here: class variables (instance variables which are declared as static) can be accessed directly by using class name like ClassName.varName. And any object of that class can access and modify its value unlike instance variables are accessed by only its respective objects. Class variables can be used in static methods.
What is the use of a private static variable in Java?
Logically, private static variable is no different from public static variable rather the first one gives you more control. IMO, you can literally replace public static variable by private static variable with help of public static getter and setter methods.
One widely used area of private static variable is in implementation of simple Singleton pattern where you will have only single instance of that class in whole world. Here static identifier plays crucial role to make that single instance is accessible by outside world(Of course public static getter method also plays main role).
public class Singleton {
private static Singleton singletonInstance = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return Singleton.singletonInstance;
}
}
Well, private static variables can be used to share data across instances of that class. While you are correct that we cannot access the private static variables using constructs like ClassName.member or ClassInstance.member but the member will always be visible from methods of that class or instances of that class. So in effect instances of that class will always be able to refer to member.
What is the use of a private static class variable?
Let's say you have a library book Class. Each time you create a new Book, you want to assign it a unique id. One way is to simply start at 0 and increment the id number. But, how do all the other books know the last created id number? Simple, save it as a static variable. Do patrons need to know that the actual internal id number is for each book? No. That information is private.
public class Book {
private static int numBooks = 0;
private int id;
public String name;
Book(String name) {
id = numBooks++;
this.name = name;
}
}
This is a contrived example, but I'm sure you can easily think of cases where you'd want all class instances to have access to common information that should be kept private from everyone else. Or even if you can't, it is good programming practice to make things as private as possible. What if you accidentally made that numBooks field public, even though Book users were not supposed to do anything with it. Then someone could change the number of Books without creating a new Book.
Very sneaky!
The private keyword will allow the use for the variable access within the class and static means we can access the variable in a static method.
You may need this cause a non-static reference variable cannot be accessible in a static method.
Another perspective :
A class and its instance are two different things at the runtime. A class info is "shared" by all the instances of that class.
The non-static class variables belong to instances and the static variable belongs to class.
Just like an instance variables can be private or public, static variables can also be private or public.
Static variables are those variables which are common for all the instances of a class..if one instance changes it.. then value of static variable would be updated for all other instances
For some people this makes more sense if they see it in a couple different languages so I wrote an example in Java, and PHP on my page where I explain some of these modifiers. You might be thinking about this incorrectly.
You should look at my examples if it doesn't make sense below. Go here http://www.siteconsortium.com/h/D0000D.php
The bottom line though is that it is pretty much exactly what it says it is. It's a static member variable that is private. For example if you wanted to create a Singleton object why would you want to make the SingletonExample.instance variable public. If you did a person who was using the class could easily overwrite the value.
That's all it is.
public class SingletonExample {
private static SingletonExample instance = null;
private static int value = 0;
private SingletonExample() {
++this.value;
}
public static SingletonExample getInstance() {
if(instance!=null)
return instance;
synchronized(SingletonExample.class) {
instance = new SingletonExample();
return instance;
}
}
public void printValue() {
System.out.print( this.value );
}
public static void main(String [] args) {
SingletonExample instance = getInstance();
instance.printValue();
instance = getInstance();
instance.printValue();
}
}
I'm new to Java, but one way I use static variables, as I'm assuming many people do, is to count the number of instances of the class. e.g.:
public Class Company {
private static int numCompanies;
public static int getNumCompanies(){
return numCompanies;
}
}
Then you can sysout:
Company.getNumCompanies();
You can also get access to numCompanies from each instance of the class (which I don't completely understand), but it won't be in a "static way". I have no idea if this is best practice or not, but it makes sense to me.
In the following example, eye is changed by PersonB, while leg stays the same. This is because a private variable makes a copy of itself to the method, so that its original value stays the same; while a private static value only has one copy for all the methods to share, so editing its value will change its original value.
public class test {
private static int eye=2;
private int leg=3;
public test (int eyes, int legs){
eye = eyes;
leg=leg;
}
public test (){
}
public void print(){
System.out.println(eye);
System.out.println(leg);
}
public static void main(String[] args){
test PersonA = new test();
test PersonB = new test(14,8);
PersonA.print();
}
}
>
14
3
When in a static method you use a variable, the variable have to be static too
as an example:
private static int a=0;
public static void testMethod() {
a=1;
}
If a variable is defined as public static it can be accessed via its class name from any class.
Usually functions are defined as public static which can be accessed just by calling the implementing class name.
A very good example of it is the sleep() method in Thread class
Thread.sleep(2500);
If a variable is defined as private static it can be accessed only within that class so no class name is needed or you can still use the class name (upto you).
The difference between private var_name and private static var_name is that private static variables can be accessed only by static methods of the class while private variables can be accessed by any method of that class(except static methods)
A very good example of it is while defining database connections or constants which require declaring variable as private static .
Another common example is
private static int numberOfCars=10;
public static int returnNumber(){
return numberOfCars;
}
*)If a variable is declared as private then it is not visible outside of the class.this is called as datahiding.
*)If a variable is declared as static then the value of the variable is same for all the instances and we no need to create an object to call that variable.we can call that variable by simply
classname.variablename;
private static variable will be shared in subclass as well. If you changed in one subclass and the other subclass will get the changed value, in which case, it may not what you expect.
public class PrivateStatic {
private static int var = 10;
public void setVar(int newVal) {
var = newVal;
}
public int getVar() {
return var;
}
public static void main(String... args) {
PrivateStatic p1 = new Sub1();
System.out.println(PrivateStatic.var);
p1.setVar(200);
PrivateStatic p2 = new Sub2();
System.out.println(p2.getVar());
}
}
class Sub1 extends PrivateStatic {
}
class Sub2 extends PrivateStatic {
}
If you use private static variables in your class, Static Inner classes in your class can reach your variables. This is perfectly good for context security.
ThreadLocal variables are typically implemented as private static.
In this way, they are not bound to the class and each thread has its own reference to its own "ThreadLocal" object.
Private static fields and private static methods can useful inside public static methods. They help to reduce the too much logic inside public static methods.

Overriding a super class's instance variables

Why are we not able to override an instance variable of a super class in a subclass?
He perhaps meant to try and override the value used to initialize the variable.
For example,
Instead of this (which is illegal)
public abstract class A {
String help = "**no help defined -- somebody should change that***";
// ...
}
// ...
public class B extends A {
// ILLEGAL
#Override
String help = "some fancy help message for B";
// ...
}
One should do
public abstract class A {
public String getHelp() {
return "**no help defined -- somebody should change that***";
}
// ...
}
// ...
public class B extends A {
#Override
public String getHelp() {
return "some fancy help message for B";
// ...
}
Because if you changed the implementation of a data member it would quite possibly break the superclass (imagine changing a superclass's data member from a float to a String).
Because you can only override behavior and not structure. Structure is set in stone once an object has been created and memory has been allocated for it. Of course this is usually true in statically typed languages.
Variables aren't accessed polymorphically. What would you want to do with this that you can't do with a protected variable? (Not that I encourage using non-private mutable variables at all, personally.)
class Dad{
public String name = "Dad";
}
class Son extends Dad{
public String name = "Son";
public String getName(){
return this.name;
}
}
From main() method if you call
new Son().getName();
will return "Son"
This is how you can override the variable of super class.
Do you mean with overriding you want to change the datatype for example?
What do you do with this expression
public class A {
protected int mIndex;
public void counter(){
mIndex++;
}
}
public class B extends A {
protected String mIndex; // Or what you mean with overloading
}
How do you want to change the mIndex++ expression without operator overloading or something like this.
If you have the need to override an instance variable, you are almost certainly inheriting from the worng class.
In some languages you can hide the instance variable by supplying a new one:
class A has variable V1 of type X;
class B inherits from A, but reintroduces V1 of type Y.
The methods of class A can still access the original V1. The methods of class B can access the new V1. And if they want to access the original, they can cast themself to class A (As you see dirty programming provokes more dirty progrtamming).
The best solution is to find another name for the variable.
you can override a method,that is all right
but what do you mean by overriding a variable?
if you want to use a variable at any other place rather than super class
u can use super.
as in
super(variable names);
why do you want to override a variable?
i mean is there any need?
we can not overriding structure of instance variables ,but we ovverride their behavior:-
class A
{
int x = 5;
}
class B extends A
{
int x = 7:
}
class Main
{
public static void main(String dh[])
{
A obj = new B();
System.out.println(obj.x);
}
}
in this case output is 5.

Categories

Resources