FAQ Database Discussion Community


Final keyword in typescript?

typescript,final
Is there any way to make a variable available to be assigned only once? Like this interface IFACE{ a: number; final b: number; } IFACEConstructor (a: number): IFACE { return {a: a, b: 1} } test = IFACEConstructor(2); test.a = 5 //OK test.b = 2 //Error ...

I'm only assigning one value to my final variable but still I'm getting an error

java,class,final
I'm getting an error when making my instance Strings cardRank and cardSuit final and I think that I'm only assigning them values once in my code. I've commented which ones I'm talking about in my code. import java.util.Arrays; public class Card{ protected static final String[] SUITS = {"spades", "clubs", "hearts",...

Does final keyword in c++ allow for additional compiler optimizations?

c++,inheritance,virtual,compiler-optimization,final
I was thinking about virtual calls and how they work. I understand that virtual calls can be inlined and hardcoded at compile time for value types. If the pointer type is of a class declared as final (like sealed in c#) could this allow the compiler to do the same...

Overloaded final function in derived class [duplicate]

c++,c++11,polymorphism,overloading,final
This question already has an answer here: Why does an overridden function in the derived class hide other overloads of the base class? 3 answers How can I use final overloaded function from derived class? Compiler says 'no matching function for call to 'B::foo()''. class A { public: virtual...

Java Applet - Cannot inherit from final class

java,applet,classloader,final
We have a java applet which is working OK in most client environments, primarily Windows 7, but recently we have been asked to support Ubuntu clients as well. The problem is that when the applet is fired up on the Ubuntu client (running Firefox and the natively installed "IcedTEA" Java...

Implementing an interface provided by a Client

java,interface,client,final
I have following task public class Event { private final Integer id; private final Collection<Market> market; private final Boolean completed; public Event(Integer id, Collection<Market> market, Boolean completed) { this.id = id; this.market = market; this.completed = completed; } public Integer getId() { return id; } public Boolean getCompleted() { return...

what is the difference between constant variables and final variables in java? [duplicate]

java,variables,constants,final
This question already has an answer here: Difference between Static and final? 8 answers Please help me understand the difference between the constant variables and final variables in Java .I am a bit confused with it....

Odd behaviour of final on a virtual function

c++,final,c++14,undefined-reference
I've encountered a strange case when the final keyword is added to a virtual function declaration, with its definition on a separate .cpp file. Consider the following example: IClass.hpp class IClass //COM-like base interface { protected: virtual ~IClass(){} //derived classes override this public: virtual void release() final; }; dllmain.cpp (shared...

non final - immutable classes

java,immutability,final
I have read and have always been told that immutable classes must be final . but i was wondering if it is possible to have a non final class object as immutable one. in this link (Why would one declare an immutable class final in Java?) what if the immutable...

Android Java: Using setOnClickListener in for loop

java,android,for-loop,final
I'm in the early stages of android development and I had a problem with a for loop. Here is my code: for (int i=0; i<=30; i++){ tableRows[i] = new TableRow(this); tableRows[i].setId(i); tableRows[i].setLayoutParams(tableRowParams); tableRows[i].setBackgroundResource(R.drawable.bg); textViews1[i] = new TextView(this); textViews1[i].setText("Eng Kelime " + i); textViews1[i].setTextSize(25); textViews1[i].setTextColor(Color.WHITE); textViews1[i].setId(i); textViews1[i].setPadding(20, 30, 0, 0); textViews1[i].setLayoutParams(Params2);...

What is the difference between final, const and static variables in java

java,variables,static,const,final
What is the difference between final, const and static variables in java with code example please `

Variable 'final' modifier lost in Bytecode?

java,jvm,final
Analyzing the bytecode of this simple class, I have come to the conclusion that the compiler doesn't retain any information about a local variable being final. This seems weird though, since I believe the HotSpot compiler could actually use this information to do optimizations. Code: public static void main(String[] args)...

Java performance in creating objects

java,performance,final
I'm trying to improve my knowledge in Java performance optimization and I tried multiple approach to create an object. I came across this behaviour I'm not familiar with regarding usage of final members in a class: the creation of an object is far less expensive (in terms of time) if...

How is concatenation of final strings done in Java?

java,string,final
When I compile this snippet. public class InternTest { public static void main(String...strings ){ final String str1="str"; final String str2="ing"; String str= str1+str2; } } Which produces the following byte code public static void main(java.lang.String...); flags: ACC_PUBLIC, ACC_STATIC, ACC_VARARGS Code: stack=1, locals=4, args_size=1 0: ldc #16 // String str 2:...

How can a constant be defined without using a literal?

java,constants,final,literals
I'm struggling to understand how a constant can be defined without using a literal. Does final int A = 1 + 1 count?

Is it possible to extend a final class in Java?

java,inheritance,final,extends
On possible duplicate: This thread is not asking how to extend a final class. It is asking why a class declared as final could possibly extend another class. From this thread: A final class is simply a class that can't be extended. However, I have a helper class which...

should a java class' fields always be final?it 's a good pratice? [closed]

java,final
Should a Java class' fields always be final? Is it a good practice? I know what 'final' means for a primitive or Object Type. My question is should I often (or always) use fields with final? e.g. public class MemoryUsage { private final long init; private final long used; private...

Immutable class in Java

java,class,immutability,final
As per many documentations, I have seen that an immutable class should have the following features: class should be final all the methods should be final all the variables should be final there should not be any setters But my questions are: What if I have a class with only...

Why does shadowing affect `final` behavior?

java,final
Here are three SSCCE which I believe should compile and behave the same. The only thing I'm changing is the first line of "run". Exhibit 1 public class FinalExperiment { private TinyThing thing; public static void main(String[] args) { FinalExperiment instance = new FinalExperiment(); instance.run(); } public void run() {...

Trying to understand final variables

java,final
Final variables. I have read everything I could find on it on this site, and others, and I almost understand them, but I'm still a bit confused. So, I know the official answer for why we would declare a variable as final: it locks the variable and prevents it from...

What is the difference between the keyword 'Private' and 'Final'?

php,oop,methods,visibility,final
Having a confusion between Private and Final in PHP. For example I have 3 classes: Class A (parent class) Class B (child class) Class C (other class) What I understand: A: Public variables and methods are accessible to the class A, class B and class C B: Private variables and...

Possible to add a new class that can be cast to an existing final class?

java,class,casting,final
I have class A defined in a library: public final class A {blah} And then I want to hack it somewhere using a new class B to substitute it: A a = new A(); A a = (A) new B(); B has all the methods and members in A, so...

Can I set a final variable in Java with a result of a divison? [duplicate]

java,static,singleton,final
This question already has an answer here: Why the result of 1/3=0 in java? 10 answers I want to have a global-scale variable, so some graphical objects can always have the same size in relation to the window. My idea: public static final double GLOBALSCALE = SCREENWIDTH / 1920;...

static and final static assignment

java,variables,static,variable-assignment,final
I was using same kind of concept , I used in first class. b was initialized to 0 and I got 0 everywhere I used b. After some time I got the reason and ran debugger and saw a has not been allocated any value till function call.variable a has...

How to make sure my map is never modified once set in my Builder pattern?

java,multithreading,dictionary,thread-safety,final
Below is my builder pattern which I am using in one of my projects and I wanted to make it thread safe in multithreading environment. Once the ClientKey is set, I don't want anyone to modify it again. public final class ClientKey { private final long userId; private final int...

Java Factory pattern - How to prevent anonymous subclasses

java,factory,final
I'm doing a school assignment where I have to implement the Factory pattern. I have come a long way, but there is one last thing I have not been able to get working. I have the following classes: //Human.java package human; public abstract class Human{ public static Human create(String namn,...

OnItemclick loosing value of string

android,string,final,onitemclick
Good day everyone. Unfortunately i don't have much experience with java and i run into a probably very basic issue. I am filling a list view and when i click one of the list items i want to send a string to another intent. but the value of the string...

Can't initialize static final field in constructor

java,final
Why am I not allowed to assign the final modifier in the following case: public static final float aspectRatio; public TestBaseClass() { // TODO Auto-generated constructor stub screenWidth = Gdx.graphics.getWidth(); screenHeight = Gdx.graphics.getHeight(); aspectRatio = screenWidth/screenHeight; } I thought when I declare a variable as final and leave it blank(not...

Handling of `final` by the JVM

java,jvm,final
In a comment to this question, I'm claiming that final in some cases must be honored by the JVM. The safe publication of final variables has been already asked and so was the handling of static final members. But what about enforcing classes and methods being final and forbidding overwriting...

avoiding “Potential null pointer access”

java,nullpointerexception,final
which would you say is the best practice when implementing the following problem: MyClass myVariable = null; if ( ..condition 1.. ) { myVariable = new MyClass(1); } else if ( ..condition 2.. ) { myVariable = new MyClass(2); } myVariable.execute(); Which would be a good solution to the warning?...

Where are static final variables used in java?

java,final,static-members
I am studying java and wanted to know what's the usage of static final variables in application designing. Please provide some examples too.

Might not have been initialized error at null check

java,initialization,final
I'm checking if the variable is initialized but at that point netbeans is giving me variable reader might not have been initialized warning. How do I fix/suppress this? This is my code (summary): final Reader reader; try { reader = new Reader(directory); //additional stuff that can cause an exception }...

How to force a class to declare a final variable?

android,abstract-class,final
For the moment, I created an abstract class like this: public abstract class MyClass { public final static String TAG; ... } But it gives me an error of not initializing a final variable. Then I tried to initialize it from a constructor, but it didn't work either (gives the...

Java use of non-final variable to set final variable

java,variables,final
This is probably a dumb question, but I'll risk asking it anyway. Often I need to create a final variable for use somewhere else and the value of that variable will need to be set based on some condition. This is how I typically do it: String notFinalVersion = null;...

Shortening a piece of code gives an error; How do I solve this issue? [duplicate]

java,swing,final,mouselistener
This question already has an answer here: A final counter in a for loop? 6 answers I have this piece of code in a method: switches[0].addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent e) { if(switchstate[0] == false) { if((e.getX() >= OFFBUTTONLEFT && e.getX() <= OFFBUTTONRIGHT) && (e.getY() >= OFFBUTTONTOP && e.getY()...

Passing non-final integer in another class

java,multithreading,for-loop,integer,final
I have this problem: I want to execute multiple threads at once, using a for-loop. I want to pass the variable "i" to a method in the thread. But there is an error occuring, I cannot pass a non-final variable "i" into another class. How can I fix that? This...

What steps can you make to make a java object with a setter to be immutable? [duplicate]

java,final
This question already has an answer here: How final keyword works 13 answers What can you do to make an object such as this immutable? I am mostly concerned about solving public void someMethod(SomeObject someObject) { } <== This case For example: public class SomeObject { private String someString;...

In Java can making a local variable final in a non-static method that is called many times cause a memory leak?

java,memory-leaks,final
For example lets say we have: public void doThis() { final Foo foo = Foo.getInstance(); ... initialize foo somehow... baz(Bar.getInstance(foo)); // adds Bar instance to something ... bar will be popped from some list, used, and disposed of... } Can a memory leak occur for this scenario? I'm just not...

Variable is accessed from within inner class , needs to be declared final

android,checkbox,inner-classes,final
I am using multiple check boxes and need to perform different operations on checked i.e increment some static variables according to the checkbox selected. So the problem is i cant make the variable i to be final (using a loop) , otherwise it is not accessible in the inner class....

Static (and final) field initialization in an enum in Java

java,enums,static,initialization,final
Say I have this enumerated type of Colours as follows: public enum Colour { RED, GREEN, BLUE; } I want to randomize a colour out of those three, following the suggestion found over there: http://stackoverflow.com/a/8114214/2736228 But I don't want to make a call to values() over and over again, so,...

Using variables / Static variables to 'name' values to aid readability

java,static,final
public class myObject extends someOtherObject(){ final int MAINBOX_X = 0; final int MAINBOX_Y = 1; final int BUTTON_X = 2; final int BUTTON_Y = 3; final int TEXT_X = 4; final int TEXT_Y = 5; public myObject(int x, int y){ super(); //'coordinates' is an array of pairs, x and y...

Why would a program compile for me, but not for another person?

java,compiler-errors,final
My code is below. It compiles fine for me, however my professor is saying he's getting an error because I don't have a few variables in my class declared final. Eclipse doesn't seem to have a problem with this on my machine so I don't know how to fix what...

Initialization order of final fields

java,constructor,final,jls
Consider these two classes: public abstract class Bar { protected Bar() { System.out.println(getValue()); } protected abstract int getValue(); } public class Foo extends Bar { private final int i = 20; public Foo() { } @Override protected int getValue() { return i; } public static void main(String[] args) { new...