Can I have private final fields in abstract class - java

Can I create a abstract class like below..?
abstract class A{
private final String foo;
private final String too;
public A(final String foo, final String too) {
this.foo= foo;
this.too= too;
}
public String getfoo(){
return foo;
}
public String gettoo(){
return too;
}
}

Short: yes.
Long(er): an abstract class is just a class that can't be instantiated as is, since parts might still be missing. Thus i can have private fields. Just note that subclasses don't have access to them, except via the getters/setters.

Your code is correct.
Note: good practice in abstract classes is protected constructor, beacuse class itself cannot be instantiated and the inheriting classes must have to call super(...) constructor.

Yes you can.
Consider the possibility to make them protected instead of private to allow your subclasses i.e. the ones extending this class, to have direct access to the fields..

Yes of course possible.But it is not a good practice because you cant create one object of this class.Main point is that you also dont require this type of class because you have not define any abstract functions inside it. But as per your question you can definitely create this type of abstract class.

Related

Interface clarification

One more clarification about interfaces. Suppose, there is a class:
public interface Foo {
public static final String doSmth();
public static String doSmth2();
public final String doSmth3();
public String doSmth4();
public abstract String doSmth5();
}
1) Can I write abstract in method head in interfaces?
2) Can I omit words static, public, and final ?
There is no such interface. You'll get a compilererror. 1.) final methods can't be overriden. But you'll have to implement them because they are part of the interface. 2.) static methods can't be overriden. And due to this aren't allowed in interfaces (atleast not without methodbody). The accessmodifiers can be left out. But keep in mind, that methods without accessmodifier are packagelocal!!!
Methods are abstract by default in interfaces.
You can never omit static, public is just like in any other class, and you cannot have final methods in an interface.
And just so you know, the code of yours won't compile.
The variables in an interfaces are public static and final implicitely.
You can't create static methods in interfaces.
the final methods cannot be overrides, if a method in interface is final it cannot be override by any class so it has no sense of using final.

importing final fields using interface (RIGHT/WRONG) [duplicate]

This question already has answers here:
What is the use of interface constants?
(13 answers)
Closed 9 years ago.
Recently I saw in somebody's code that he implements his final class variable fields inside an interface ex:
public interface commentSchema{
static final String DB_TABLE_NAME = "comment";
...
}
& he had implemented a class which does need these variables something like this:
public class DbComment implements commentSchema {
// use the DB_TABLE_NAME value here ...
...
}
as you know If someone make an instance of DbComment class because of inheritance aspect, he's gonna be able to access the DB_TABLE_NAME which is not proper because we want to use those values only inside DbComment methods.
now I have several questions:
1) is this implementation proper & ok ?
2) if It's not, how we have to declare these variables outside of DbComment class & make this class be the only class who does see these values. (we don't want to use abstract class coz a class can only extends one other class in java)
3) why we do need to use static for values & methods which exist inside an interface ? (when we implements certain interface for a specific class why do we need to make it static to be seen everywhere?)
4) is there any specification that exactly determine kinds of different declarations for java methods, classes, enums, etc ?
1) is this implementation proper & ok ?
Yes, will work just fine.
2) if It's not how I'm gonna declare these variable outside of DbComment class & make this class be the only class who does see DB_TABLE_NAME value. (I don't want to use abstract class coz a class can only extends one other class in java)
No need as the implementation used works as expected.
3) why we do need to use static for values & methods which exist inside an interface ? (when we implements certain interface for a specific class why do we need to make it static to be seen everywhere?)
You can't make methods in interfaces final or static. The only qualifiers allowed for methods are public and abstract which have, by the way, no effect at all.
For fields, static exists, but also has no effect. All fields declared in a interface will be accessible statically by the implementors and are considered constants.
4) is there any specification that exactly determine kinds of different declarations for java methods, classes, enums, etc ?
The official spec has a chapter on Names and Declaration.
By default, any field declared inside an interface is marked as public static final even if the programmer doesn't do it. This means, any field in the interface will be constant and impossible to modify.
If you don't want that functionality (whatever reasons you could have) then it would be better to have an abstract class instead and mark the field as protected static final.
public abstract class CommentSchema{
protected static final String DB_TABLE_NAME = "comment";
}
Still, if you want to base your design to interfaces, then you can have the interface without this field, then an abstract class that implements this interface and adds the field. By doing this, every class that extends the abstract class will implement the interface and have access to the field:
public interface CommentSchema {
foo();
}
public abstract class CommentSchemaAbstractImpl implements CommentSchema {
protected static final String DB_TABLE_NAME = "comment";
}
public class CommentSchemaRealImpl extends CommentSchemaAbstractImpl {
#Override
public void foo() {
//do something...
baz(DB_TABLE_NAME);
}
private void baz(String s) {
//fancy code here...
}
}
At last, you can forget about all this and create an enum to handle your constants.
public enum TableName {
COMMENT("comment");
private String tableName;
private TableName(String tableName) {
this.tableName = tableName;
}
}

Java- Using a constant in an abstract class that needs to be used by subclasses as well

I have an abstract class and 2 subclasses. There are 4 constants that relate to all the classes. I was going to place the finals in the abstract class but I understand a final variable is not inherited?
Would I have to define the constant in every class (seems inefficient)? Or just make the constant an instant variable (doesn't sound like a good idea)?
What are ways I can go about this?
The following would be available to all of your sub-classes if defined in the abstract class.
public static final Integer MYCONSTANT = 42;
or
static final Integer MYCONSTANT = 42;
or
protected static final Integer MYCONSTANT = 42;
The second one (package-private) is only available to classes within the same package. The third (protected) would be available to all sub-classes irrespective of their package.
Constants are inherited by childrens. You just have to make sure to have them protected or public so the children can access them.
abstract class A {
protected final static String FOO = "bar";
}
class B extends A {
somemethod() {
System.out.println("foo: " + FOO);
}
}
can be accessed from the class and all its children.
Yes they are. But as they are constant it should be final and static , static modifier make it there will be only one 'copy' and if this will be used only used in subclass only then u can use protected or if from other Classes too the must make it public.

Why use Static Nested Classes in Java?

I am new to java and have been scratching my head understanding some its concepts.
I am following the tutorial Java tutorial. However, I cannot find the usefulness of using Static Nested Classes. I mean I think I need some good examples as to why I should want to use it. Can someone provided me some codes as examples so I can understand it better?
thax
The benefit of a static nested class over an "ordinary" class is that you can use it to reflect the relationship between two classes.
For example in the JDK there is java.util.Map and java.util.Map.Entry.
java.util.Map.Entry is declared as a public static interface and doing it this way clearly signposts its relationship to Map. It could have been defined as java.util.MapEntry but doing it as a static nested interface makes it clear that it has a strong relationship to Map.
So you'd probably only use static nested class when the nested class would only ever be used in the context of its parent.
The following example might not be for a Java beginner but one nice example of static nested class is when you want to use the Builder pattern to construct immutable objects of the outer class. The static nested class is allowed to access private members of the outer class thus constructing objects of the outer class although it has a private constructor and initializing private fields of the outer class.
E.g.
public class SomeClass {
private int someField;
private int someOtherField;
private SomeClass()
{}
public static class SomeBuilder {
private int someField;
private int someOtherField;
public SomeBuilder setSomeField(int someField)
{
this.someField = someField;
return this;
}
public SomeBuilder setSomeOtherField(int someOtherField) {
this.someOtherField = someOtherField;
return this;
}
public SomeClass build() throws ValidationException
{
validateFields();
SomeClass someClass = new SomeClass();
someClass.someField = someField;
someClass.someOtherField = someOtherField;
return someClass;
}
private void validateFields() throws ValidationException {
//Validate fields
}
}
public int getSomeField() {
return someField;
}
public int getSomeOtherField() {
return someOtherField;
}
}
Nested or inner class is just an ordinary class defined into other class. The reason to do this is typically to hide inner class from others, i.e. it is yet another level of encapsulation.
Inner class can be private, protected and public that mean exactly the same as for fields and methods.
If inner class is not private you can access it from outside too. Its name is OuterClass.InnnerClass. The nesting depth is not limited by Java specification, so inner class can have its own inner classes etc.
If inner class is not static it has yet another feature: ability to call outer's class methods and fields.
Inner class can be also anonymous. This is very useful for small callbacks, event handlers etc.
Hope this helps. Do not hesitate to ask other more concrete questions.
Another thing I should add is that if an inner class is not static, an instance of it will automatically have a reference to its parent class instance. You can reference it by using: NameOfOuterClass.this.
But if it is static, then it will not.
This, among other things, comes into play during GC (garbage collection).
Because, if an object of the inner class is not being GCed, then the outer class object it references will not be GCed either (in cases where the inner class was not static).

Is there any way to omit a variable from super class?

My application class uses a library that has default two variables in it.
// A class from framework:
public class SuperClass implements Serializable {
private long id;
private long version;
// getter and setter methods for these variables...
}
I should extend this class, in order to access some of the functionality of the framework.
If I extend this class to my own class like this:
public class MyClassChild extends SuperClass {
private long myprimarykey;
private String some column;
private long myversion;
// getter and setter methods for these variables...
}
As per the programming model, those two variables are also accessible.
While implementing operation that requires an Object of type SuperClass.
Is there any idea to extend that SuperClass which is not including those two variables (id, version) ?
I do not know what to do?
Any suggestions pls?
Thanks
You cannot remove these fields, but you can override the getters and setters to do something other than the default (this depends on their access modifiers, but they will probably be protected or greater). This way you can stop the external assigning of these variables, for example. If you choose this route, I would suggest that you familiarize yourself with the ways these fields are used in the superclass so that you can anticipate any knock-on behavior.
In general JPA does not let you override superclass mappings to remove attributes, but depending on your provider it may be possible to do the following:
public class MyClassChild extends SuperClass {
private long myprimarykey;
private String some column;
private long myversion;
// Override superclass mappings
#Transient
long getId() { return super.getId(); }
#Transient
void setId(long id) { return super.setId(long id); }
// etc...
}
EDIT
In addition, it is also possible to override the values of individual columns in a mapped superclass by using the #AttributeOverride annotation, e.g.
#AttributeOverride(name="id", column=#Column(name="EMP_ID"))
#Entity
public class MyClassChild extends SuperClass {
private String some column;
...
}
Nope. If you're inheriting, you get the entire class to come along. If you don't want to inherit all the fields, you're not designing a subclass.
Imagine what would happen if you could omit variables - what would inherited methods do about the now-missing state? Everything would break...
All you can do about that is to make that variable private to the super class so subclasses do not 'see' it.
When you extend a class you are supposedly adding more variables and methods, you cannot subtract.

Categories