Inheriting a class which is built using a static inner class Builder - java

I have a Class A with quite a number of member variables. In order to make it immutable and validate the member variables during construction, I made its constructor private and used an inner public static builder class (ClassABuilder) to build it. (Joshua Bloch Effective Java, Item 2).
Now what I do not understand is, how other programmers will subclass Class A to implemet their own specific behavior. I read through the disadvantages of Builder Pattern from the book but did not see subclassing mentioned as one. Am I missing something? Is there an elegant way around this?
Making the constructor protected was one of my thoughts, but it would still be taking the public static ClassABuilder, so how to add new member variables in the sub class?

Create an inner public static ClassBBuilder builder in ClassB that is a subclass of ClassABuilder

Why constructor of A use Buildler as a parameter. When user invokes Builder.create, builder must initialize default protected constructor of A, and then simply set of A's fields. So B you can easily inherit class B from A

Related

Constructor of a class

I am having trouble understanding this.
"Lastly, modify WordTransformer and SentenceTransformer so you can not create an instance of the class. Remember, with static methods and variables, you do not need to make an instance of a class. (Hint: a constructor of a class is what allows an instance of that class to be created...new WordTransformer(), what keyword can you add to the definition of that constructor that will prevent the construct from being called anywhere but in the class itself?)"
It says so you can not create an instance of this class, but if you make the class private it becomes an error. Says the only options are public static or final.
well you shall qualify the constructor as private, not the class. cf this document:
Private constructors prevent a class from being explicitly instantiated by its callers.
here's an example:
public class WordTransformer {
private WordTransformer() {
}
}
N.B.: as it sounds a lot like an assignment, I hope that you'll read the linked documentation and understand why and when to use it!
Make the constructor private:
private WordTransformer(){}
private WordTransformer(...) {
...
}
Making the constructor private will allow other methods of this class to create instances of the class but no one can create instances from the outside. Example of when this is used in practice is the singleton pattern or builder pattern.
Private constructor and static methods on a class marked as final.

Is there a way to change the value of a variable declared in an Interface in other classes in JAVA? [duplicate]

Why are interface variables static and final by default in Java?
From the Java interface design FAQ by Philip Shaw:
Interface variables are static because Java interfaces cannot be instantiated in their own right; the value of the variable must be assigned in a static context in which no instance exists. The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned by program code.
source
public: for the accessibility across all the classes, just like the methods present in the interface
static: as interface cannot have an object, the interfaceName.variableName can be used to reference it or directly the variableName in the class implementing it.
final: to make them constants. If 2 classes implement the same interface and you give both of them the right to change the value, conflict will occur in the current value of the var, which is why only one time initialization is permitted.
Also all these modifiers are implicit for an interface, you dont really need to specify any of them.
Since interface doesn't have a direct object, the only way to access them is by using a class/interface and hence that is why if interface variable exists, it should be static otherwise it wont be accessible at all to outside world. Now since it is static, it can hold only one value and any classes that implements it can change it and hence it will be all mess.
Hence if at all there is an interface variable, it will be implicitly static, final and obviously public!!!
(This is not a philosophical answer but more of a practical one). The requirement for static modifier is obvious which has been answered by others. Basically, since the interfaces cannot be instantiated, the only way to access its fields are to make them a class field -- static.
The reason behind the interface fields automatically becoming final (constant) is to prevent different implementations accidentally changing the value of interface variable which can inadvertently affect the behavior of the other implementations. Imagine the scenario below where an interface property did not explicitly become final by Java:
public interface Actionable {
public static boolean isActionable = false;
public void performAction();
}
public NuclearAction implements Actionable {
public void performAction() {
// Code that depends on isActionable variable
if (isActionable) {
// Launch nuclear weapon!!!
}
}
}
Now, just think what would happen if another class that implements Actionable alters the state of the interface variable:
public CleanAction implements Actionable {
public void performAction() {
// Code that can alter isActionable state since it is not constant
isActionable = true;
}
}
If these classes are loaded within a single JVM by a classloader, then the behavior of NuclearAction can be affected by another class, CleanAction, when its performAction() is invoke after CleanAction's is executed (in the same thread or otherwise), which in this case can be disastrous (semantically that is).
Since we do not know how each implementation of an interface is going to use these variables, they must implicitly be final.
Because anything else is part of the implementation, and interfaces cannot contain any implementation.
public interface A{
int x=65;
}
public interface B{
int x=66;
}
public class D implements A,B {
public static void main(String[] a){
System.out.println(x); // which x?
}
}
Here is the solution.
System.out.println(A.x); // done
I think it is the one reason why interface variable are static.
Don't declare variables inside Interface.
because:
Static : as we can't have objects of interfaces so we should avoid using Object level member variables and should use class level variables i.e. static.
Final : so that we should not have ambiguous values for the variables(Diamond problem - Multiple Inheritance).
And as per the documentation interface is a contract and not an implementation.
reference: Abhishek Jain's answer on quora
static - because Interface cannot have any instance. and final - because we do not need to change it.
Interface : System requirement service.
In interface, variable are by default assign by public,static,final access modifier.
Because :
public : It happen some-times that interface might placed in some other package. So it need to access the variable from anywhere in project.
static : As such incomplete class can not create object. So in project we need to access the variable without object so we can access with the help of interface_filename.variable_name
final : Suppose one interface implements by many class and all classes try to access and update the interface variable. So it leads to inconsistent of changing data and affect every other class. So it need to declare access modifier with final.
Java does not allow abstract variables and/or constructor definitions in interfaces. Solution: Simply hang an abstract class between your interface and your implementation which only extends the abstract class like so:
public interface IMyClass {
void methodA();
String methodB();
Integer methodC();
}
public abstract class myAbstractClass implements IMyClass {
protected String varA, varB;
//Constructor
myAbstractClass(String varA, String varB) {
this.varA = varA;
this.varB = VarB;
}
//Implement (some) interface methods here or leave them for the concrete class
protected void methodA() {
//Do something
}
//Add additional methods here which must be implemented in the concrete class
protected abstract Long methodD();
//Write some completely new methods which can be used by all subclasses
protected Float methodE() {
return 42.0;
}
}
public class myConcreteClass extends myAbstractClass {
//Constructor must now be implemented!
myClass(String varA, String varB) {
super(varA, varB);
}
//All non-private variables from the abstract class are available here
//All methods not implemented in the abstract class must be implemented here
}
You can also use an abstract class without any interface if you are SURE that you don't want to implement it along with other interfaces later. Please note that you can't create an instance of an abstract class you MUST extend it first.
(The "protected" keyword means that only extended classes can access these methods and variables.)
spyro
An Interface is contract between two parties that is invariant, carved in the stone, hence final. See Design by Contract.
In Java, interface doesn't allow you to declare any instance variables. Using a variable declared in an interface as an instance variable will return a compile time error.
You can declare a constant variable, using static final which is different from an instance variable.
Interface can be implemented by any classes and what if that value got changed by one of there implementing class then there will be mislead for other implementing classes. Interface is basically a reference to combine two corelated but different entity.so for that reason the declaring variable inside the interface will implicitly be final and also static because interface can not be instantiate.
Think of a web application where you have interface defined and other classes implement it. As you cannot create an instance of interface to access the variables you need to have a static keyword. Since its static any change in the value will reflect to other instances which has implemented it. So in order to prevent it we define them as final.
Just tried in Eclipse, the variable in interface is default to be final, so you can't change it. Compared with parent class, the variables are definitely changeable. Why? From my point, variable in class is an attribute which will be inherited by children, and children can change it according to their actual need. On the contrary, interface only define behavior, not attribute. The only reason to put in variables in interface is to use them as consts which related to that interface. Though, this is not a good practice according to following excerpt:
"Placing constants in an interface was a popular technique in the early days of Java, but now many consider it a distasteful use of interfaces, since interfaces should deal with the services provided by an object, not its data. As well, the constants used by a class are typically an implementation detail, but placing them in an interface promotes them to the public API of the class."
I also tried either put static or not makes no difference at all. The code is as below:
public interface Addable {
static int count = 6;
public int add(int i);
}
public class Impl implements Addable {
#Override
public int add(int i) {
return i+count;
}
}
public class Test {
public static void main(String... args) {
Impl impl = new Impl();
System.out.println(impl.add(4));
}
}
I feel like all these answers missed the point of the OP's question.
The OP did not ask for confirmation of their statement, they wanted to know WHY their statement is the standard.
Answering the question requires a little bit of information.
First, lets talk about inheretence.
Lets assume there is a class called A with an instance variable named x.
When you create a class A, it inhereits all the properties of the Object class. Without your knowledge when you instantiate A, you are instantiating an Object object as well, and A points to it as it's parent.
Now lets say you make a class B that inherits from A.
When you create a class B, you are also creating a class A and a Object.
B has access to the variable x. that means that B.x is really just the same thing as B.A.x and Java just hides the magic of grabbing A for you.
Not lets talk about interfaces...
An interface is NOT inheretence. If B were to implmement the interface Comparable, B is not making a Comparable instance and calling it a parent. Instead, B is promising to have the things that Comparable has.
Not lets talk a little bit of theory here... An interface is a set of functions you can use to interact with something. It is not the thing itself. For example, you interface with your friends by talking to them, sharing food with them, dancing with them, being near them. You don't inheret from them though - you do not have a copy of them.
Interfaces are similar. There is only one interface and all the objects associate with it. Since the interface exists only one time as a Class (as opposed to an instance of itself) it is not possible for each object that implements the interface to have their own copy of the interface. That means there is only one instance of each variable. That means the variables are shared by all the classes that use the interface (a.k.a. static).
As for why we make them public...
Private would be useless. The functions are abstract and cannot have any code inside them to use teh private variable. It will always be unused. If the variable is marked as protected, then only an inheritor of the class will be able to use the variables. I don't think you can inhereit from interfaces. Public is the only viable option then.
The only design decision left is the 'final'. It is possible that you intend to change the shared variable between multiple instances of a class. (E.G. Maybe you have 5 players playing Monopoly and you want one board to exist so you have all the players meet the interface and a single shared Board - it might be that you want to actually make the board change based on the player functions...) [I recommend against this design]
For multithreaded applicatiosn though, if you don't make the variable static you will have a difficult time later, but I won't stop you. Do it and learn why that hurts <3
So there you go. final public static variables

Why have public static class inside a class

I was going through some code and I saw this:
public class A {
public A(SomeObject obj) {
//Do something
}
//Some stuff
public static class B {
//Some other stuff
}
}
I was wondering since even the inner class is public why have it as nested and not a separate class?
Also, can I do this here: new A.B(SomeObject) ? I feel this defeats the purpose of a static class but I saw this implementation as well so wanted to know.
I was wondering since even the inner class is public why have it as nested and not a separate class?
That's really a matter to ask whoever wrote the class. It can allow the outer class to act as a "mini-namespace" though - if the nested class is only useful in the context of the outer class, it seems reasonable. It indicates deliberate tight coupling between the two classes. I most often see this in the context of the builder pattern:
Foo foo = new Foo.Builder().setBar(10).build();
Here it makes sense to me to have Foo.Builder nested within Foo rather than as a peer class which would presumably be called FooBuilder.
Note that it also gives some visibility differences compared with just unrelated classes.
Also, can I do this here: new A.B(SomeObject) ?
No, because B doesn't have a constructor with a SomeObject parameter - only A does (in the example you've given).
I feel this defeats the purpose of a static class
You should try to work out exactly what you deem the purpose of a static class to be, and in what way this defeats that purpose. Currently that's too vague a statement to be realistically discussed.
You would have an inner class like this so
you can keep an class which only exists to support the outer class encapsulated.
you want to be able to access private members of the outer class or other nested classes.
you want a nested class with static fields (a weak reason I know ;)
you have a class with a very generic name like Lock or Sync which you wouldn't want to be mixed with other classes of the same name used by classes in the same package.
can I do this here: new A.B(SomeObject) ?
You can.
I feel this defeats the purpose of a static class
It takes getting used to but once you start you may have trouble not turning your entire program into one file.java ;)
1. A static inner class is known as Top-Level Class.
2. This static class has direct access to the Its Outer class Static method and variables.
3. You will need to initialize the static Inner class in this way from Outside...
A a = new A();
A.B b = new A.B();
4. new A.B(SomeObject) won't work... because you don't have a constructor with SomeObject as parameter...
5. But when the Inner class is Non-static, then it have implicit reference to the Outer class.
6. The outer and inner class can extends to different classes.
7. An interface's method can be implemented more than once in different or same ways, using Inner Class.
This pattern is used very often with the builder pattern. It not only makes clear the relation between a class and its builder, but also hides the ugly builder constructor/factory and makes builder more readable. For example in case you need your built object to have optional and not optional properties.
public class AnObject {
public static class AnObjectBuilder {
private AnObject anObject;
private AnObjectBuilder() {
}
private void newAnObjectWithMandatory(String someMandatoryField, ...) {
anObject = new AnObject(someMandatoryField,...)
}
public AnObjectBuilder withSomeOptionalField(String opt) {
...
}
}
public static AnObjectBuilder fooObject() {
return (new AnObjectBuilder()).newAnObjectWithMandatory("foo")
}
public static AnObjectBuilder barObject() {
return (new AnObjectBuilder()).newAnObjectWithMandatory("bar")
}
}
This way the client code have to call first the static method on the AnObjectBuilder class and then to use the optional builder methods:
AnObject.fooObject("foo").withSomeOptionalField("xxx").build(); without creating the builder object.
Pretty readable :)
I was wondering since even the inner class is public why have it as nested and not a separate class?
Have a look at this thread: Why strange naming convention of "AlertDialog.Builder" instead of "AlertDialogBuilder" in Android
Also, can I do this here: new A.B(SomeObject) ?
(Update) No, you can't do this, since B doesn't have a constructor that asks for SomeObject.
I hope this helps.
I was wondering since even the inner class is public why have it as
nested and not a separate class?
The simple reason it is allowed is packaging convenience.
Static nested class in Java, why?
http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
yes, you can do new A.B(SomeObject). But you don't have to take my word for it, try it out.

using interface to communicate between 2 java classes

I have 2 classes A and B.
class A implements Constants{
private int state;
}
class B implements Constants{
foo(){
//want to set state variable of class A like this
state = state1
}
}
interface Constants{
public final int state1;
public final int state2;
}
I don't want to have an instance of class A in class B. How should I do this?
If I have a function to set the variable in the interface, then both the classes must implement this function. That would be wrong right? Because then 2 definitions for the same function would conflict?
There is nothing called functions in java. They are methods.
You can have getters and setters in your classes for the properties to set and get them from external classes.
Your question is unclear.
If your B class extends the A class, then through the constructor of the B class, you can set the properties of the A class that is the super class.
Hope it helps!
Having an interface does not mean that the variable will be shared between the classes, it is more of a way to define classes that MUST override the functions in the interface. You can read the very basics on them here. To share a variable between two classes, you can either make the variable static and put it in another class that both your classes extend (in effect a global variable, which is bad practice and not thread safe), or have one of the classes have an instance of the other and call getters/setters.
EDIT: there is a similar question here that shows you what I mean about the static variable.
You generally want to avoid writing any method in a class that attempts to alter the internal state of another class. Whatever trick you come up with to accomplish such a thing, you are breaking the principle of encapsulation which is the whole reason for using classes in the first place.
If there is some state that you wish to have accessible from multiple classes, I would recommend breaking that state out into it's own class and have each of the two classes interact with it through getter/setter or utility methods.

Why are interface variables static and final by default?

Why are interface variables static and final by default in Java?
From the Java interface design FAQ by Philip Shaw:
Interface variables are static because Java interfaces cannot be instantiated in their own right; the value of the variable must be assigned in a static context in which no instance exists. The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned by program code.
source
public: for the accessibility across all the classes, just like the methods present in the interface
static: as interface cannot have an object, the interfaceName.variableName can be used to reference it or directly the variableName in the class implementing it.
final: to make them constants. If 2 classes implement the same interface and you give both of them the right to change the value, conflict will occur in the current value of the var, which is why only one time initialization is permitted.
Also all these modifiers are implicit for an interface, you dont really need to specify any of them.
Since interface doesn't have a direct object, the only way to access them is by using a class/interface and hence that is why if interface variable exists, it should be static otherwise it wont be accessible at all to outside world. Now since it is static, it can hold only one value and any classes that implements it can change it and hence it will be all mess.
Hence if at all there is an interface variable, it will be implicitly static, final and obviously public!!!
(This is not a philosophical answer but more of a practical one). The requirement for static modifier is obvious which has been answered by others. Basically, since the interfaces cannot be instantiated, the only way to access its fields are to make them a class field -- static.
The reason behind the interface fields automatically becoming final (constant) is to prevent different implementations accidentally changing the value of interface variable which can inadvertently affect the behavior of the other implementations. Imagine the scenario below where an interface property did not explicitly become final by Java:
public interface Actionable {
public static boolean isActionable = false;
public void performAction();
}
public NuclearAction implements Actionable {
public void performAction() {
// Code that depends on isActionable variable
if (isActionable) {
// Launch nuclear weapon!!!
}
}
}
Now, just think what would happen if another class that implements Actionable alters the state of the interface variable:
public CleanAction implements Actionable {
public void performAction() {
// Code that can alter isActionable state since it is not constant
isActionable = true;
}
}
If these classes are loaded within a single JVM by a classloader, then the behavior of NuclearAction can be affected by another class, CleanAction, when its performAction() is invoke after CleanAction's is executed (in the same thread or otherwise), which in this case can be disastrous (semantically that is).
Since we do not know how each implementation of an interface is going to use these variables, they must implicitly be final.
Because anything else is part of the implementation, and interfaces cannot contain any implementation.
public interface A{
int x=65;
}
public interface B{
int x=66;
}
public class D implements A,B {
public static void main(String[] a){
System.out.println(x); // which x?
}
}
Here is the solution.
System.out.println(A.x); // done
I think it is the one reason why interface variable are static.
Don't declare variables inside Interface.
because:
Static : as we can't have objects of interfaces so we should avoid using Object level member variables and should use class level variables i.e. static.
Final : so that we should not have ambiguous values for the variables(Diamond problem - Multiple Inheritance).
And as per the documentation interface is a contract and not an implementation.
reference: Abhishek Jain's answer on quora
static - because Interface cannot have any instance. and final - because we do not need to change it.
Interface : System requirement service.
In interface, variable are by default assign by public,static,final access modifier.
Because :
public : It happen some-times that interface might placed in some other package. So it need to access the variable from anywhere in project.
static : As such incomplete class can not create object. So in project we need to access the variable without object so we can access with the help of interface_filename.variable_name
final : Suppose one interface implements by many class and all classes try to access and update the interface variable. So it leads to inconsistent of changing data and affect every other class. So it need to declare access modifier with final.
Java does not allow abstract variables and/or constructor definitions in interfaces. Solution: Simply hang an abstract class between your interface and your implementation which only extends the abstract class like so:
public interface IMyClass {
void methodA();
String methodB();
Integer methodC();
}
public abstract class myAbstractClass implements IMyClass {
protected String varA, varB;
//Constructor
myAbstractClass(String varA, String varB) {
this.varA = varA;
this.varB = VarB;
}
//Implement (some) interface methods here or leave them for the concrete class
protected void methodA() {
//Do something
}
//Add additional methods here which must be implemented in the concrete class
protected abstract Long methodD();
//Write some completely new methods which can be used by all subclasses
protected Float methodE() {
return 42.0;
}
}
public class myConcreteClass extends myAbstractClass {
//Constructor must now be implemented!
myClass(String varA, String varB) {
super(varA, varB);
}
//All non-private variables from the abstract class are available here
//All methods not implemented in the abstract class must be implemented here
}
You can also use an abstract class without any interface if you are SURE that you don't want to implement it along with other interfaces later. Please note that you can't create an instance of an abstract class you MUST extend it first.
(The "protected" keyword means that only extended classes can access these methods and variables.)
spyro
An Interface is contract between two parties that is invariant, carved in the stone, hence final. See Design by Contract.
In Java, interface doesn't allow you to declare any instance variables. Using a variable declared in an interface as an instance variable will return a compile time error.
You can declare a constant variable, using static final which is different from an instance variable.
Interface can be implemented by any classes and what if that value got changed by one of there implementing class then there will be mislead for other implementing classes. Interface is basically a reference to combine two corelated but different entity.so for that reason the declaring variable inside the interface will implicitly be final and also static because interface can not be instantiate.
Think of a web application where you have interface defined and other classes implement it. As you cannot create an instance of interface to access the variables you need to have a static keyword. Since its static any change in the value will reflect to other instances which has implemented it. So in order to prevent it we define them as final.
Just tried in Eclipse, the variable in interface is default to be final, so you can't change it. Compared with parent class, the variables are definitely changeable. Why? From my point, variable in class is an attribute which will be inherited by children, and children can change it according to their actual need. On the contrary, interface only define behavior, not attribute. The only reason to put in variables in interface is to use them as consts which related to that interface. Though, this is not a good practice according to following excerpt:
"Placing constants in an interface was a popular technique in the early days of Java, but now many consider it a distasteful use of interfaces, since interfaces should deal with the services provided by an object, not its data. As well, the constants used by a class are typically an implementation detail, but placing them in an interface promotes them to the public API of the class."
I also tried either put static or not makes no difference at all. The code is as below:
public interface Addable {
static int count = 6;
public int add(int i);
}
public class Impl implements Addable {
#Override
public int add(int i) {
return i+count;
}
}
public class Test {
public static void main(String... args) {
Impl impl = new Impl();
System.out.println(impl.add(4));
}
}
I feel like all these answers missed the point of the OP's question.
The OP did not ask for confirmation of their statement, they wanted to know WHY their statement is the standard.
Answering the question requires a little bit of information.
First, lets talk about inheretence.
Lets assume there is a class called A with an instance variable named x.
When you create a class A, it inhereits all the properties of the Object class. Without your knowledge when you instantiate A, you are instantiating an Object object as well, and A points to it as it's parent.
Now lets say you make a class B that inherits from A.
When you create a class B, you are also creating a class A and a Object.
B has access to the variable x. that means that B.x is really just the same thing as B.A.x and Java just hides the magic of grabbing A for you.
Not lets talk about interfaces...
An interface is NOT inheretence. If B were to implmement the interface Comparable, B is not making a Comparable instance and calling it a parent. Instead, B is promising to have the things that Comparable has.
Not lets talk a little bit of theory here... An interface is a set of functions you can use to interact with something. It is not the thing itself. For example, you interface with your friends by talking to them, sharing food with them, dancing with them, being near them. You don't inheret from them though - you do not have a copy of them.
Interfaces are similar. There is only one interface and all the objects associate with it. Since the interface exists only one time as a Class (as opposed to an instance of itself) it is not possible for each object that implements the interface to have their own copy of the interface. That means there is only one instance of each variable. That means the variables are shared by all the classes that use the interface (a.k.a. static).
As for why we make them public...
Private would be useless. The functions are abstract and cannot have any code inside them to use teh private variable. It will always be unused. If the variable is marked as protected, then only an inheritor of the class will be able to use the variables. I don't think you can inhereit from interfaces. Public is the only viable option then.
The only design decision left is the 'final'. It is possible that you intend to change the shared variable between multiple instances of a class. (E.G. Maybe you have 5 players playing Monopoly and you want one board to exist so you have all the players meet the interface and a single shared Board - it might be that you want to actually make the board change based on the player functions...) [I recommend against this design]
For multithreaded applicatiosn though, if you don't make the variable static you will have a difficult time later, but I won't stop you. Do it and learn why that hurts <3
So there you go. final public static variables

Categories