So I've been reading Effective Java by Joshua Bloch and noticed two points which I actually have encountered in my work.
Point 1: Making setter methods to make code more readable.
In his example, we have a class with a ridiculously huge constructor. When people instantiate the class, it's hard to tell what's going on with all the parameters. Thus, he suggested making a minimalistic constructor and have setter methods for all other options, so instead of...
MyClass clazz = new MyClass(a, b, c,
d, e, f, g);
you would write....
MyClass clazz = new MyClass(a, b,
c); clazz.setDitto(d);
clazz.setEcho(e);
clazz.setFunzies(f);
clazz.setGumballs(g);
Which, as a huge supporter of readable code, I liked a lot.
Point 2: In general, he suggested having immutable classes. He goes into great depth on why having immutable classes is much better than having a class that could be in several different states. I can definitely say that he sold the idea to me, and I can't wait to make most classes I write from now on immutable, except....
What happens when you have an immutable class with a huge constructor? You can't make setter methods for it; that would break immutability. I tried skimming through the rest of the book, but I don't think he covers a solution for this.
There is the possibility of making one-time use setter methods, but just the fact that a setter method is available to a class that is supposedly immutability is disheartening, even if it does just throw an Exception if you try it subsequent times.
Does anyone have any good ideas on how to handle this problem? I'm currently facing this issue at work where I have an Immutable class with a huge constructor which I'd like to refactor to something that's more readable without breaking immutability.
One option is to provide a separate builder class that provides the setters, which is responsible for constructing the actual object.
In the second edition of Bloch's "Effective Java", item 2 illustrates this for an immutable class. The key ideas are:
The builder has a mutable field for each option.
The builder passes itself as a single argument to the immutable class's constructor.
Introduce Parameter Object, maybe? It kind of moves the problem around, but maybe in useful ways. Your parameter object needs no methods; it just holds the data, and you set it up, instead of your real class. Then your real class initializes itself in the constructor via the parameter object.
You can go with fluent interfaces: Building big, immutable objects without using constructors having long parameter lists
See also:
Constructor Parameters - Rule of Thumb
Having one request object as a Method Signature parameter, which constitute all the required parameters
How about having an abstract base class which supports getters but no setters for all the attributes of the class, a derived sealed "immutable" class whose constructor accepts a base-class object, and a derived mutable class which includes setters for all the properties?
Related
I am learning Java, I know what inheritance and composition is, I saw numerous examples of polymorphysim showed using inheritance, so my first question is,can same be done using composition? If yes, please show with a small example.
My second question is, can it be said that polymorpysim is basically method overloading and/or is method overiding ? if yes, then why ?
First question
Polymorphism can be achieved in Java in two ways:
Through class inheritance: class A extends B
Through interface implementation: class A implements C.
In the later case, to properly implement A's behaviour, it can be done though composition, making A delegate over some other class/es which do the tasks specified in Interface C.
Example: Let's suppose we have already some class imeplementing interface C:
class X implements C
{
public String getName() {...}
public int getAge() {...}
}
How can we create a new class implementing C with the same behaviour of X? Like this:
class A implements C
{
private C x=new X();
public String getName() {return x.getName();}
public int getAge() {return x.getAge();}
}
Second question
No, polymorphism is not method overloading and/or method overriding (in fact, overloading has nothing to do with Object Oriented Design):
Method overloading consists on creating a new method with the same name that some other (maybe inherited) method in the same class but with a different signature (=parameter numbers or types). Adding new methods is OK, but that is not the aim of polymorphism.
Method overriding consists on setting a new body to an inherited method, so that this new body will be executed in the current class instead of the inherited method's body. This is a advantage of polymorphism, still is not the base of it either.
Polymorphism, in brief, is the ability of a class to be used as different classes/interfaces.
No, not really. Polymorphism and composition or aggregation (composition is a more rigid form of aggregation wherein the composed objects' lifetimes are tied together) are different ways of reusing classes.
Composition involves aggregating multiple objects to form a single entity. Polymorphism involves multiple objects that share analogous behavior.
For example, a Car object might be composed of two Axle objects, a Chassis object, four Wheel objects (which themselves may be composed of a Rim, a Tire, six LugNuts and so on). When you instantiate a Car, your Car constructor would instantiate all the parts that go along with it. That's composition. (Aggregation would use all the same part objects but not necessarily instantiate them in its constructor.)
A Car object might also not be useful on its own, but rather as a blueprint for numerous more specialized implementations of cars, such as SportsCar, SUVCar, SedanCar, and the like. In this case, the Car object might define a Car interface that would define common behaviors such as Steer, HitTheGas and Brake, but leave the implementations of those behaviors to the implementing classes. Then, a consumer of a Car object can declare an object of type Car, instantiate it as any of the implementing classes such as SportsCar, call the methods defined in the Car interface, and get the behavior implemented in the instantiated class. That's polymorphism.
For a decent tutorial on both, with some comparisons, have a look at this. Keep in mind that the UML diagrams have an inaccuracy: while the examples do indeed describe composition as opposed to aggregation, the related UML class diagrams have white diamonds where they should be black. UML class diagram syntax uses a white diamond for class associations that are aggregations and a black one for those that are compositions.
Also, this post has some good information, in particular tdammers's answer halfway down the page.
There is book answer, if one remember about all the firemans are fireman but some are drivers, chiefs etc. There you need polymorphism. There is things you can do with classes and it's a general idea in OOP as language constraints. Overriding is just what you can do with classes. Also permissions and local and/or global scopes. There is default constructor for any class. There is namespace scope, program, class etc.
All Classes and methods are functions but not all functions are methods
You can override class but not method. Those are static or volatile. Cos method can only return the value. So overriding the method has no sense. I hope this will turn you, if nothing, toward how it was meant to be. Inheritance is mechanism how polymorphism works.
My apologies for unintentional mistakes during too much data.
I'd like to create a few immutable objects for my codebase. What's the best way to really deliver the message that a given class is intended to be immutable? Should I make all of my fields final, and initialize during object construction? (This seems really awkward...) Should I create some Immutable interface, and have objects implement it? (Since Java doesn't have some standard interface behind this, I thought they had some other way of dealing with it.) What's the standard way this is dealt with? (If it's simply done by adding a bunch of comments around the fields exclaiming that they shouldn't be modified once initialized, that's fine too.)
Should I make all of my fields final, and initialize during object construction?
Yes. And ensure that those types are themselves immutable, or that you create copies when you return values from getter methods. And make the class itself final. (Otherwise your class on its own may be immutable, but that doesn't mean that any instance of your class would be immutable - because it could be an instance of a mutable subclass.)
(This seems really awkward...)
It's hard to know what to suggest without knowing how you find it to be awkward - but the builder pattern can often be useful. I usually use a nested static class for that, often with a static factory method. So you end up with:
Foo foo = Foo.newBuilder()
.setName("asd")
.setPoints(10)
.setOtherThings("whatever")
.build();
Yes and no. Making all fields final is not a guarantee in and of itself. If you'd like to get really in-depth with this there are a number of chapters in Effective Java by Joshua Bloch dealing with immutability and the considerations involved. Item 15 in Effective Java covers the bulk of it and references the other items in question.
He offers these five steps:
Don’t provide any methods that modify the object’s state (known as muta-
tors).
Ensure that the class can’t be extended.
Make all fields final.
Make all fields private.
Ensure exclusive access to any mutable components.
One way to learn how to do all of this is to see how the language designers make classes immutable by reviewing the source for classes like String which are immutable (for example see http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java).
Write a unit test that will fail if your coworkers make the class mutable.
Using Mutability Detector, you can write a test like this:
import static org.mutabilitydetector.unittesting.MutabilityAssert.assertImmutable;
#Test public void isImmutable() {
assertImmutable(MyImmutableThing.class)
}
If a coworker comes along, and, for example, adds a setter method to your class, the test will fail. Your use case is one of the core purposes of Mutability Detector.
Disclaimer: I wrote it.
I want to get my head around the idea of using setters and getters in superclass and subclass in terms of software good practices.
From your experience, which method of the below are appropriate and also promote good software re-usability:
declaring a protected instance variables in the superclass and let the subclass uses them.
declaring a private instance variables in the superclass with public getter methods to let the subclass inherits the getter methods from the superclass.
Depends on your style of coding. Some prefer concise code over more verbose structured code. If your ultimate goal is interoperability and scalability, you're 'safer' using getters/setters. Another advantage is with the getters/setters you can perform multiple operations instead of only a single operation, for instance getUsers() may actually tabulate multiple data rows. This way you can consolidate that operation instead having to repeat it in subclasses.
Use your best judgement. If the values are simple booleans or strings, probably don't need a g/s. If they're query related or make specific, repeated modifications to state or data, use a g/s approach.
Both methods are acceptable. Normally, I would have public getter/setter methods since anyone can use them, not just subclasses.
I pick number 1. That's exactly the situation where the existence of protected is justified. Getters and setters are for classes using another non-related class.
I pick 1 mostly when I am going to create an abstract class.
Otherwise, I always pick 2 (creating getter/setter). Because:
Not only that avoid any accidental/unintended modification to
class's member variable, it also help when you will go about
creating jUnit test-cases for your classes.
Decouple the classes.
Any good book on Object Oriented Programming will list other benefits of using getter and setter.
I have a bunch of classes extending an abstract Base class.
Each subclass takes an array as in the constructor, (different length depending on class).
These classes could be written by other people.
What is the best way to figure out the length of the array the class needs?
I could:
(A) Require that each derived class have a static method, returning the length.
However, the base class cannot enforce this, since abstract static methods does not work in java.
(B) Each derived class have a constructor with no arguments, and I construct
such classes just to be able to call the countParameters() method, that
I can enforce from the Base class. This feels "cludgy", since I am not interested in creating such object, but only need some info about it.
The reason is that I am creating a GUI, that gives the user the ability to create
instances of Derived classes, but each Derived class takes different number of parameters.
That is, I need to know how to draw the GUI before I can create the classes.
EDIT:
I could just require that each Derived class have a private
constructor, with no arguments, and using reflection I can call the countParameters() method.
EDIT2: Actually, what I am interested in, is what the names of the parameters are.
That is, if the class Derived have the constructor
public Derived(double name1,double name2,...)
I need a way to generate the String[] array
{name1,name2,...}
I guess this would be impossible to do without creating an instance of the class,
but for the user to be able to create such class, he/she needs the parameter names!
Moment 22.
It sounds like you need the Factory Pattern.
In general, it's a bad idea for a base class to know the set of it's descendant's. So you define another class whose job it is to know that.
If you have something like a Shape, with ThisShape and ThatShape as derived classes, then a ShapeCreator will handle the job of creating the specific set of shapes your program supports, giving each one the arguments it needs.
It's not quite clear what you're trying to achieve, but I wonder: Do the subclasses really have to take a single parameter with an array, as opposed to a list of parameters?
Constructor<?> ctor = Test.class.getConstructors()[0];
int parameterCount = ctor.getParameterTypes().length;
ctor.newInstance(new Object[parameterCount]);
how about this code:
public absract Base {
public abstract int size();
public Base(Object[] objs) {
if (objs.length != size()) {
throw new IllegalArgumentException();
}
//rest of your code.
}
each child class needs to implement size method.
hope its help.
I'd go with method A. You can't get the compiler to enforce the existence of such a method, but you can certainly enforce it in your program - no method, no work!
Seriously, this whole scheme is a bit brittle and I can't think of a way to make it significantly better. An incorrect implementation of those subclasses will bomb out, that's life.
A possible remedy would be for you to provide a set of interfaces for those subclasses, such as
SubClassTaking2Args
SubClassTaking3Args
...
and requiring your sub's to implement one of those as a marker interface. But that's just more bureaucracy with little more effect.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java: Rationale of the Object class not being declared abstract
Why is the Object class, which is base class of 'em all in Java, not abstract?
I've had this question for a really really long time and it is asked here purely out of curiosity, that's all. Nothing in my code or anybody's code is breaking because it is not abstract, but I was wondering why they made it concrete?
Why would anyone want an "instance" (and not its presence a.k.a. Reference) of this Object class? One case is a poor synchronization code which uses the instance of an Object for locking (at least I used it this way once.. my bad).
Is there any practical use of an "instance" of an Object class? And how does its instantiation fit in OOP? What would have happened if they had marked it abstract (of course after providing implementations to its methods)?
Without the designers of java.lang.Object telling us, we have to base our answers on opinion. There's a few questions which can be asked which may help clear it up.
Would any of the methods of Object benefit from being abstract?
It could be argued that some of the methods would benefit from this. Take hashCode() and equals() for instance, there would probably have been a lot less frustration around the complexities of these two if they had both been made abstract. This would require developers to figure out how they should be implementing them, making it more obvious that they should be consistent (see Effective Java). However, I'm more of the opinion that hashCode(), equals() and clone() belong on separate, opt-in abstractions (i.e. interfaces). The other methods, wait(), notify(), finalize(), etc. are sufficiently complicated and/or are native, so it's best they're already implemented, and would not benefit from being abstracted.
So I'd guess the answer would be no, none of the methods of Object would benefit from being abstract.
Would it be a benefit to mark the Object class as abstract?
Assuming all the methods are implemented, the only effect of marking Object abstract is that it cannot be constructed (i.e. new Object() is a compile error). Would this have a benefit? I'm of the opinion that the term "object" is itself abstract (can you find anything around you which can be totally described as "an object"?), so it would fit with the object-oriented paradigm. It is however, on the purist side. It could be argued that forcing developers to pick a name for any concrete subclass, even empty ones, will result in code which better expresses their intent. I think, to be totally correct in terms of the paradigm, Object should be marked abstract, but when it comes down to it, there's no real benefit, it's a matter of design preference (pragmatism vs. purity).
Is the practice of using a plain Object for synchronisation a good enough reason for it to be concrete?
Many of the other answers talk about constructing a plain object to use in the synchronized() operation. While this may have been a common and accepted practice, I don't believe it would be a good enough reason to prevent Object being abstract if the designers wanted it to be. Other answers have mentioned how we would have to declare a single, empty subclass of Object any time we wanted to synchronise on a certain object, but this doesn't stand up - an empty subclass could have been provided in the SDK (java.lang.Lock or whatever), which could be constructed any time we wanted to synchronise. Doing this would have the added benefit of creating a stronger statement of intent.
Are there any other factors which could have been adversely affected by making Object abstract?
There are several areas, separate from a pure design standpoint, which may have influenced the choice. Unfortunately, I do not know enough about them to expand on them. However, it would not suprise me if any of these had an impact on the decision:
Performance
Security
Simplicity of implementation of the JVM
Could there be other reasons?
It's been mentioned that it may be in relation to reflection. However, reflection was introduced after Object was designed. So whether it affects reflection or not is moot - it's not the reason. The same for generics.
There's also the unforgettable point that java.lang.Object was designed by humans: they may have made a mistake, they may not have considered the question. There is no language without flaws, and this may be one of them, but if it is, it's hardly a big one. And I think I can safely say, without lack of ambition, that I'm very unlikely to be involved in designing a key part of such a widely used technology, especially one that's lasted 15(?) years and still going strong, so this shouldn't be considered a criticism.
Having said that, I would have made it abstract ;-p
Summary
Basically, as far as I see it, the answer to both questions "Why is java.lang.Object concrete?" or (if it were so) "Why is java.lang.Object abstract?" is... "Why not?".
Plain instances of java.lang.Object are typically used in locking/syncronization scenarios and that's accepted practice.
Also - what would be the reason for it to be abstract? Because it's not fully functional in its own right as an instance? Could it really do with some abstract members? Don't think so. So the argument for making it abstract in the first place is non-existent. So it isn't.
Take the classic hierarchy of animals, where you have an abstract class Animal, the reasoning to make the Animal class abstract is because an instance of Animal is effectively an 'invalid' -by lack of a better word- animal (even if all its methods provide a base implementation). With Object, that is simply not the case. There is no overwhelming case to make it abstract in the first place.
From everything I've read, it seems that Object does not need to be concrete, and in fact should have been abstract.
Not only is there no need for it to be concrete, but after some more reading I am convinced that Object not being abstract is in conflict with the basic inheritance model - we should not be allowing abstract subclasses of a concrete class, since subclasses should only add functionality.
Clearly this is not the case in Java, where we have abstract subclasses of Object.
I can think of several cases where instances of Object are useful:
Locking and synchronization, like you and other commenters mention. It is probably a code smell, but I have seen Object instances used this way all the time.
As Null Objects, because equals will always return false, except on the instance itself.
In test code, especially when testing collection classes. Sometimes it's easiest to fill a collection or array with dummy objects rather than nulls.
As the base instance for anonymous classes. For example:
Object o = new Object() {...code here...}
I think it probably should have been declared abstract, but once it is done and released it is very hard to undo without causing a lot of pain - see Java Language Spec 13.4.1:
"If a class that was not abstract is changed to be declared abstract, then preexisting binaries that attempt to create new instances of that class will throw either an InstantiationError at link time, or (if a reflective method is used) an InstantiationException at run time; such a change is therefore not recommended for widely distributed classes."
From time to time you need a plain Object that has no state of its own. Although such objects seem useless at first sight, they still have utility since each one has different identity. Tnis is useful in several scenarios, most important of which is locking: You want to coordinate two threads. In Java you do that by using an object that will be used as a lock. The object need not have any state its mere existence is enough for it to become a lock:
class MyThread extends Thread {
private Object lock;
public MyThread(Object l) { lock = l; }
public void run() {
doSomething();
synchronized(lock) {
doSomethingElse();
}
}
}
Object lock = new Object();
new MyThread(lock).start();
new MyThread(lock).start();
In this example we used a lock to prevent the two threads from concurrently executing doSomethingElse()
If Object were abstract and we needed a lock we'd have to subclass it without adding any method nor fields just so that we can instantiate lock.
Coming to think about it, here's a dual question to yours: Suppose Object were abstract, will it define any abstract methods? I guess the answer is No. In such circumstances there is not much value to defining the class as abstract.
I don't understand why most seem to believe that making a fully functional class, which implements all of its methods in a use full way abstract would be a good idea.
I would rather ask why make it abstract? Does it do something it shouldn't? is it missing some functionality it should have? Both those questions can be answered with no, it is a fully working class on its own, making it abstract just leads to people implementing empty classes.
public class UseableObject extends AbstractObject{}
UseableObject inherits from abstract Object and surprise it can be implemented, it does not add any functionality and its only reason to exist is to allow access to the methods exposed by Object.
Also I have to disagree with the use in "poor" synchronisation. Using private Objects to synchronize access is safer than using synchronize(this) and safer as well as easier to use than the Lock classes from java util concurrent.
Seems to me there's a simple question of practicality here. Making a class abstract takes away the programmer's ability to do something, namely, to instantiate it. There is nothing you can do with an abstract class that you cannot do with a concrete class. (Well, you can declare abstract functions in it, but in this case we have no need to have abstract functions.) So by making it concrete, you make it more flexible.
Of course if there was some active harm that was done by making it concrete, that "flexibility" would be a drawback. But I can't think of any active harm done by making Object instantiable. (Is "instantiable" a word? Whatever.) We could debate whether any given use that someone has made of a raw Object instance is a good idea. But even if you could convince me that every use that I have ever seen of a raw Object instance was a bad idea, that still wouldn't prove that there might not be good uses out there. So if it doesn't hurt anything, and it might help, even if we can't think of a way that it would actually help at the moment, why prohibit it?
I think all of the answers so far forget what it was like with Java 1.0. In Java 1.0, you could not make an anonymous class, so if you just wanted an object for some purpose (synchronization or a null placeholder) you would have to go declare a class for that purpose, and then a whole bunch of code would have these extra classes for this purpose. Much more straight forward to just allow direct instantiation of Object.
Sure, if you were designing Java today you might say that everyone should do:
Object NULL_OBJECT = new Object(){};
But that was not an option in 1.0.
I suspect the designers did not know in which way people may use an Object may be used in the future, and therefore didn't want to limit programmers by enforcing them to create an additional class where not necessary, eg for things like mutexes, keys etc.
It also means that it can be instantiated in an array. In the pre-1.5 days, this would allow you to have generic data structures. This could still be true on some platforms (I'm thinking J2ME, but I'm not sure)
Reasons why Object needs to be concrete.
reflection
see Object.getClass()
generic use (pre Java 5)
comparison/output
see Object.toString(), Object.equals(), Object.hashCode(), etc.
syncronization
see Object.wait(), Object.notify(), etc.
Even though a couple of areas have been replaced/deprecated, there was still a need for a concrete parent class to provide these features to every Java class.
The Object class is used in reflection so code can call methods on instances of indeterminate type, i.e. 'Object.class.getDeclaredMethods()'. If Object were to be Abstract then code that wanted to participate would have to implement all abstract methods before client code could use reflection on them.
According to Sun, An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed. This also means you can't call methods or access public fields of an abstract class.
Example of an abstract root class:
abstract public class AbstractBaseClass
{
public Class clazz;
public AbstractBaseClass(Class clazz)
{
super();
this.clazz = clazz;
}
}
A child of our AbstractBaseClass:
public class ReflectedClass extends AbstractBaseClass
{
public ReflectedClass()
{
super(this);
}
public static void main(String[] args)
{
ReflectedClass me = new ReflectedClass();
}
}
This will not compile because it's invalid to reference 'this' in a constructor unless its to call another constructor in the same class. I can get it to compile if I change it to:
public ReflectedClass()
{
super(ReflectedClass.class);
}
but that only works because ReflectedClass has a parent ("Object") which is 1) concrete and 2) has a field to store the type for its children.
A example more typical of reflection would be in a non-static member function:
public void foo()
{
Class localClass = AbstractBaseClass.clazz;
}
This fails unless you change the field 'clazz' to be static. For the class field of Object this wouldn't work because it is supposed to be instance specific. It would make no sense for Object to have a static class field.
Now, I did try the following change and it works but is a bit misleading. It still requires the base class to be extended to work.
public void genericPrint(AbstractBaseClass c)
{
Class localClass = c.clazz;
System.out.println("Class is: " + localClass);
}
public static void main(String[] args)
{
ReflectedClass me = new ReflectedClass();
ReflectedClass meTwo = new ReflectedClass();
me.genericPrint(meTwo);
}
Pre-Java5 generics (like with arrays) would have been impossible
Object[] array = new Object[100];
array[0] = me;
array[1] = meTwo;
Instances need to be constructed to serve as placeholders until the actual objects are received.
I suspect the short answer is that the collection classes lost type information in the days before Java generics. If a collection is not generic, then it must return a concrete Object (and be downcast at runtime to whatever type it was previously).
Since making a concrete class into an abstract class would break binary compatibility (as noted upthread), the concrete Object class was kept. I would like to point out that in no case was it created for the sole purpose of sychronization; dummy classes work just as well.
The design flaw is not including generics from the beginning. A lot of design criticism is aimed at that decision and its consequences. [oh, and the array subtyping rule.]
Its not abstract because whenever we create a new class it extends Object class then if it was abstract you need to implement all the methods of Object class which is overhead... There are already methods implemented in that class...