This question already has answers here:
Is "public static final" redundant for a constant in a Java interface?
(6 answers)
Closed 3 years ago.
What exactly the meaning of instance fields in JAVA ?
As per am knowing in JAVA :
An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final.
But, When I have tried as below :
interface TempIn
{
TakeInput tv=null;
String name="";
int temp=0;
void printT();
}
and it's working. How ?
Confused...
Simple: all these fields are static and final by default.
Therefore the java language allows you to write down something that is implicitly given.
In other words: imagine the "compiler" putting down the keywords for you.
But I agree, this is a bit of confusing. And it also turns a bit into a "style" thing. In the early years of Java, a lot of people would add these redundant keywords to their interfaces. On the other hand, "clean code" tells us to avoid redundancy in our code. And nowadays, an IDE like IntelliJ will even give you warnings when using the keywords. So, my recommendation:
don't touch old, existing code
talk to your team, and decide what makes sense for you, and for new code, follow that agreement
Related
This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 3 years ago.
I found the following passage in the book "Headfirst java". I don't understand the bolded part in the below passage.
Object: The point to setters (and getters, too) is that you can change
your mind later, without breaking anybody else's code! Imagine if half
the people in your com- pany used your class with public instance
variables, and one day you suddenly realized,
" Oops - there's something I didn't plan for with that value, I'm going to have to switch to a setter method." You break everyone's
code. The cool thing about encapsulation is that you get to change
your mind. And nobody gets hurt. The performance gains from using
variables directly is so miniscule and would rarely be worth it.
The internal representation of that value may change and require a new type be used, which could be hidden from other code using getter/setter methods.
This question already has answers here:
Should I use "this" keyword when I want to refer to instance variables within a method?
(8 answers)
Closed 4 years ago.
I had written a piece of code along the lines of:
public abstract class TestService extends Base {
protected final MappedObject<A, B> mappedObject;
public TestService(Provider provider, ObjectMapper objectMapper) {
mappedObject = new MappedObject.Builder<A, B>(...);
...
}
...
}
However, I have been instructed to prefix this to mappedObject, as it is convention when it comes to setting instance variables. Is this true?
I was under the impression that this as a prefix would only need to be used if there were a parameter with the same name that could cause ambiguity. Hence, a this would be necessary to reference the instance variable rather than the argument passed.
As you seem to be aware, it's not necessary, as long as there is no ambiguity between local and member variables of a class.
However, there are a number of different schools on this, and whether it's "convention" or not varies depending on who you ask (different developers have different preferences, different companies have different conventions, etc.). I would say it's mostly common in school courses. In the real world you might see it in a constructor from time to time, but in my personal experience it's quite rare.
Something that I find is more of a convention, and somewhat ties into this question, is prefixing member variables with m, as in mMappedObject, to indicate that it is a member variable. This is very common - in fact, one could argue that it's probably more common than prefixing this.
This question already has answers here:
Are there any Java method ordering conventions? [closed]
(8 answers)
Closed 7 years ago.
I have come to the question: what is the most preferred way of placing methods? I mean, should first declare static methods, then constructors, then public methods, then protected, then private, etc? Is there some kind of convention, like I guess everyone places fields (instance variables) on top of the code. Is there the same policy about methods?
I guess it depends on the language you use. What about Java?
This is somewhat opinion based, but the Google Java Style doc puts it nicely:
The ordering of the members of a class can have a great effect on learnability, but there is no single correct recipe for how to do it. Different classes may order their members differently.
What is important is that each class order its members in some logical order, which its maintainer could explain if asked. For example, new methods are not just habitually added to the end of the class, as that would yield "chronological by date added" ordering, which is not a logical ordering.
https://google-styleguide.googlecode.com/svn/trunk/javaguide.html#s3.4.2-class-member-ordering
Most of the code I see in the open source world uses some variation of
static fields
instance fields
constructors
methods (instance and static)
anonymous classes
It comes down to team preference, but it is always good to follow convention
Talking about execution, JVM guarantees the order which we cannot change.manage.
But from code readability point of view , YES ordering does looks good. Following coding standards is what should do.
Static fields -> instance fields/variables
As we know, Static Block is always called once class is loaded, so we should have it.
Then constructors, for object creation, there is no point of writing constructor at the end.
also a good read here as suggested above.
This question already has answers here:
What is the point of "final class" in Java?
(24 answers)
Closed 9 years ago.
I know that when final keyword is used before a Class , the Class cannot be inherited by another Class.
But I have never seen its real usage in Java Coding except for immutable classes.
In which scenarios it will be really required to use final keyword before a Class?
And does not it reduce the reusability feature of Java language?
A final class cannot be subclassed. This is done for reasons of security and efficiency. Some of the classes in Java API are final, for example java.lang.System. Sometimes security and immutability is of far more importance than re usability.
According to this IBM developerWorks article :
The common perception is that declaring classes or methods final makes it easier for the compiler to inline method calls, but this perception is incorrect (or at the very least, greatly overstated).
final classes and methods can be a significant inconvenience when programming -- they limit your options for reusing existing code and extending the functionality of existing classes. While sometimes a class is made final for a good reason, such as to enforce immutability, the benefits of using final should outweigh the inconvenience. Performance enhancement is almost always a bad reason to compromise good object-oriented design principles, and when the performance enhancement is small or nonexistent, this is a bad trade-off indeed.
Also read this Open Closed Principle:
Software Entities (Classes, Modules, Functions, etc.) should be open for Extension, but closed for Modification.
final class can not be inherited. So if you want that nobody can inherit your class then you can declare it as final. So you have already answers your own questions. So main usage are
Immutable types
If you dont want someone extend the class.
Both are them are used for security reasons. To protect your system to be changed by using your critical classes. Is not it enough for being a reason?
final keyword can be used with a class in order to provide security. We can take the example of String. String class was made immutable as well as final to enhance security of file handling in java.
Though, performance is also a reason (assuming you are already aware of the internal String pool maintained for making sure that the same String object is used more than once without having to create/re-claim it those many times), but the main reason why String has been made immutable in Java is 'Security'. Surprised? Let's understand why.
Suppose you need to open a secure file which requires the users to authenticate themselves. Let's say there are two users named 'user1' and 'user2' and they have their own password files 'password1' and 'password2', respectively. Obviously 'user2' should not have access to 'password1' file.
As we know the filenames in Java are specified by using Strings. Even if you create a 'File' object, you pass the name of the file as a String only and that String is maintained inside the File object as one of its members.
Had String been mutable, 'user1' could have logged into using his credentials and then somehow could have managed to change the name of his password filename (a String object) from 'password1' to 'password2' before JVM actually places the native OS system call to open the file. This would have allowed 'user1' to open user2's password file. Understandably it would have resulted into a big security flaw in Java. I understand there are so many 'could have's here, but you would certainly agree that it would have opened a door to allow developers messing up the security of many resources either intentionally or un-intentionally.
With Strings being immutable, JVM can be sure that the filename instance member of the corresponding File object would keep pointing to same unchanged "filename" String object. The 'filename' instance member being a 'final' in the File class can anyway not be modified to point to any other String object specifying any other file than the intended one (i.e., the one which was used to create the File object).
More information can be found here Source A
Source B
I research this, and I read this on Hardcore Java, Publisher : O'Reilly ISBN : 0-596-00568-7
Why Classes are tagged Final:
There are two ways to make a class final. The first is to use the keyword final in the class declaration:
public final class SomeClass {
// . . . Class contents
}
The second way to make a class final is to declare all of its constructors as private:
public class SomeClass {
public final static SOME_INSTANCE = new SomeClass(5);
private SomeClass(final int value) {
}
Marking it final saves you the trouble if finding out that it is actual a final, to demonstrate look at this Test class. looks public at first glance.
public class Test{
private Test(Class beanClass, Class stopClass, int flags)
throws Exception{
// . . . snip . . .
}
}
Unfortunately, since the only constructor of the class is private, it is impossible to extend this class. In the case of the Test class, there is no reason that the class should be final. The Test class is a good example of how implicit final classes can cause problems.
So you should mark it final when you implicitly make a class final by making it's constructor private.
A final class cannot be subclassed. This is necessary to improve security even if it has some drawbacks.
E.g. the class java.lang.String is final. Therefore you cannot subclass String and can be sure that a String parameter is never a subclass that does something harmful (e.g. sending the String somewhere).
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Question marks in Java generics.
I'm editing someone else's code for an assignment and I'm trying to clean it up to get rid of the dozens of warnings in it and Eclipse was giving warnings for the use of Collections as a raw type. When I took it's suggested fix it created this.
Collections<?>
Example
public static String separatedString(Collection<?> c, String separator) {
return separatedString(c, "", separator, "", new StringBuffer())
.toString();
}
I was just wondering exactly what this did and whether or not it was safe.
This ist the concept of generics.
Its all about object oriented programming
For example if i declare a variable as Collection<MyClass> ONLY and ONLY objects that are of declared Type or Subtype of MyClass may be put in it.
This is good to keep things straight and put constraints on the way this code should be used.
The question mark stands for class of your choice.
When you initialise the class you can ... whoops just seeing there is an exact duplicate here:
What does the question mark in Java generics' type parameter mean?
Adding
MyClass<?>
adds generics to the code, but doesn't really add much benefit since the naked question mark can mean any class. Google and read up on generics, and you'll learn how to create generics that do constrain what classes may be used and how this adds the benefit of compile-time type checking.
e.g.,
MyClass<? extends Comparable>
Which will constrain coders to only using Comparable types with MyClass. A basic tutorial starts here: Java Generics Tutorial