Does 'extends Object' have a purpose or is it redundant? - java

Following a tutorial on the internet regarding Soap development with Java, I found this link, with a rather unusual code for myself.
The code:
public class SoapService extends Object {
/** Creates new SoapService */
public SoapService() {
}
/** This is the SOAP exposes method
*/
public String sayGreeting(String name)
{
return "Hello "+name;
}
}
What's with the 'extends Object' syntax ? I've never encountered this kind of syntax (only on Generics).
Does this syntax has any purpose or is 'plain dumb' ?

Unless the Object class is not actually the java.lang.Object class (the tutorial does not include the imports, so it's hard to see), the extends Object is redundant.

All objects in Java implicitly extend Object, so I'd say it's redundant.

All classes extend Object implicitly anyway so it's just redundant coding having no impact.

Looks a bit like generated code - it's extra effort for a source code generator to omit the "extends" clause if it is not needed, especially if the generator is template-based.

It just means it inherits directly from the Object class. Here is more about inheritance in Java.

No. It's just explicitly doing something that is implicit.

It's unneeded. Every class in Java extends Object at some level. Leave it out, unless you need to clarify something specific.

Extends clause is optional as stated in Java Language Specification. If it is omitted, the class is derived from java.lang.Object. It is just a matter of coding style to write it or not to write it in this case. Usually it is omitted.

It is silly code. Every class in Java extends an Object class. No need to type this explisitly

There is one possibility and that is the person who made it don't want you to extend any classes. You can always do a workaround of course but that is the only thing I can come up with that makes sense.

I think it's redundant.
In Junit source code:
public class TestFailure extends Object {}
I don't know why this class extends Object.

My vote, plain dumb - but then I only play with Java...
But any class inherits from the Object Class as far as I know...

It is legal but useless boilerplate. Everything extends Object so the language spec allows you to leave it out, and it generally should be left out (some writers of coding standards disagree).
The situation is the same in generics (extends Object is implicit and redundant), it is just that for some reason (I have seen some claim early buggy Generics implementations had issues with the ? wildcard) it has caught on a bit more there.

As a matter of fact, it does not seem to be simply redundant, especially when working in the JWS webservices environment.
When defining a class for an XML type to be transported over SOAP, I use the wsimport tool to fetch client dependencies from the WSDL, which creates package-local copies of these classes. By explicitly extending Object, one can seamlessly cast between the classes from the two distinct packages.
Not doing so leads to a compilation error when trying to use a class method from package A that expects an argument type of the class in in package A, and passing in an object generated from the equivalent class in package B.

As java is an object oriented language, it supports inheritance which inherits the properties of the another class, for example all java objects inherits from java.lang.Object class.From the above example it is understood that it is the explanation of inheritance. Note that all classes, whether they state so or not, will be inherit from java.lang.Object.

Any class that doesn't explicitly extend another class,implicitly extends Object

all classes extends the java.lang.Object by default. You can see it
here

Why not make it explicit?
I'm for adding it in - not everyone "implicitly" knows that every Java class implicitly extends Object. By writing it explicitly they don't have to guess.

Related

Java inheritance, two-step inheritance

I have the main abstract class that is a base for bunch of classes. Some of them does not need all the fields and methods from the main abstract class, so I have created second abstract class and splitted main abstract class into two parts. The main abstract class contains, for example, a, x fields and their getters/setters, the second abstract class inherits from the main and contains additional b, c fields and their getter/setters. There are simple classes that are inheriting from the main class,and more complicated are inheriting from the second class. I want to create objects of each class as instances of the main class. Is it right way to do that? I have to type check and cast when I want to use methods from the second abstract class. It makes my code complicated. How can I solve this problem?
MainAbstractClass ---> SecondAbstractClass ---> MyComplicatedClasses
|
|
V
MySimpleClasses
One of the OO principles is Favor composition over inheritance.
This means that common behavior is not provided through base classes but via Component classes which are passed in via dependency injection (preferably as constructor parameters.
The answer depends on your actual needs.
You can instead choose to store the extended abstract class specific fields in a class that does not implement your base class and make it a member of more complicated classes.
You can choose to keep everything in a single base class and nothing forces you to use all the fields of an interface in every class that implemented your interface.
You can also keep using your approach but since you store the classes as an instance of the base class, it will be hard to read.
I believe that if you think code does not look very good, it is probably not good. However, there is usually no single answer to this kind of design questions and the best solution is relative to your preferences.
I think this need of type cast is a smell of fragile design. Here when we assume MyComplicatedClass ISA KIND OF MainAbstractClass as shown by TJ Crowder then object must behave as MainAbstractClass (meaning it can honor only API of MainAbstractClass). If it expects special treatment as MyComplicatedClass its false commitment and will need Casting. Such casting (by identifying type) goes against OO principles and kills polymorphism. Later this will end up in Ladder of InstanceOf and type casts as in the scenarios rightly pointed out by T.J. Crowder.
I would suggest readdress the design. e.g. though our all user defined type instances ARE KIND OF Object, but we use Object API only for methods defined in Object class. We do not use Object o = new MyClass(). There are occasions in frameworks or like Object.equals() method where type cast is needed as API is defined before even concrete extension is written. But it is not a good idea for such simple complete (without open hooks for extensions) Hierarchies.

Why is it mandatory for a class to be abstract when it has atleast one abstract method?

What is the reason that I can't create a concrete class with abstract methods in it?
Is it enforced just to make sure that no object is created without abstract method definition? or is there another plausible reason for this restriction?
An abstract class is, by definition, incomplete. Therefore, you should not be able to instantiate abstract classes. An interesting side effect of this definition is that you can create abstract classes that have all concrete methods. It's just that you think that your class is incomplete and shouldn't be able to be instantiated.
abstract class in the java constext is defined as the class has at least one
abstract method. And an abstract method is just a not implemented method. This is a design decision that was just copied from c++ where it is exactly the same. The only difference is, that in c++ you do not need to tell the compiler that a class is abstract, the compiler knows it even without you telling it. Why this design decision was made in c++ I can't tell you, but having it eleminates a complete class of errors. The error that a method of a class get's called, when the method is not implemented in that sub class.
You are right, the reason is to prevent creating an object with no implementation for a method or more.
Because when you create an Abstract class you are in the middle of your abstractions level. i Mean you have some questions about class responsibilities or this class must to do something but they dont care how, partially. If you dont wanna have an implemented method, you must to create an interface.
In my opinion the answer is in the class responsibilities and abstraction and not in the technology scope.

About the Java interface and polymorphism

I just met an strange case when reading the Java doc. Here is the link to Oracle's java doc on Arrays.asList method, http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList(T...)
There is an example in the doc
List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
My question is, as List is an interface, why can we declare stooges as a 'List', rather than a concrete subclass implementing List(e.g. ArrayList or LinkedList)?
So does it mean that we can have a reference variable of interface type? It looks quit weird to me as I always think that interface stands only for polymorphism, and we should never really use a interface type variable.
Could anyone please give me some clue on this?
Think of the List interface as a guarantee. Any class that implements List will be guaranteed to have the methods of the interface. When Arrays.asList() returns a List you're not actually getting an interface, you're getting a concrete class that is guaranteed to implement the methods listed in the List interface.
As to your "we should never really use a interface type variable" you're actually suppose to do that. It's called "programming to the interface". It's much more flexible if you can return a List as opposed to something like a LinkedList. The caller of your method isn't coupled to your specific implementation internal implementation which might use, and return, a LinkedList. If at some point you wanted to return a ArrayList instead of the LinkedList the caller would not have to change any code because they only care about the interface.
What does it mean to "program to an interface"?
Just a word of note, Serializable is a marker interface and a little odd because of that. It doesn't guarantee that methods are there, but instead guarantees that the creator of the class that implements serializable has thought about the many issues associated with serializing a class (overriding readObject/writeObject, compatiblity with other serialized forms, and other issues http://www.javapractices.com/topic/TopicAction.do?Id=45). So Serializable is still offering a guarantee, like List is, but it isn't about method signatures, it's about an extralinguistic feature of the language.
http://en.wikipedia.org/wiki/Marker_interface_pattern
Using an Interface as a reference type is a perfectly valid practice in Java. For example, the Serializable interface will do this inside it's class, so that any object that is passed to it can be serialized.
This is also how Java provides something that resembles Multiple Inheritance. For example:
public interface A { }
public class B implements A {}
public class program {
B bClass = new B();
A aObject = (A)bClass;
}
That way the same object can be referenced with different reference types, and all without messing up an inheritance chain!
The interface defines a contract or a specification for an implementation. Which is the methods and their signature. So a class that implements an interface has to respect that contract. This way you can change implementation without affecting the code that uses interfaces for declaring variables.
In the example you mentioned:
You don't know what implementation of the List interface Arrays.asList is using unless you look into the code. So how would you know which one to use? (see javadoc for list interface to see what implementations it has)
The implementation is subject for change, what if Arrays.asList decides to use another implementation? Your code will be broken.
The signature of the method Arrays.asList is that it returns List<T> so if you want to have a concrete implementation as variable you'll have to cast that return value which is bad practice or to create new - let's say ArrayList - and copy all the elements into it, which is just an unnecessary overhead.
Effective Java by Bloch is a great book on Java best practices. In particular, item #52 talks about this: "If the appropriate interface types exist ... declared using the interface types."
The general notion is that, for greatest flexibility and understandability, you should use the type that best reflects the context, which is usually the interface. In the example, you provided, does the exact implementation matter or just that it is a List. Of course, if the code requires an ArrayList-specific method or if the code is relies on an ArrayList-specific behavior, then use the concrete class.
There are occasional exceptions, such as when using GWT-RPC, but this is for implementation reasons.
This is really good example of polymorphism power, if you like you can look at the source code of Arrays.asList() here Arrays.asList(T...a) ,you will find that it takes varibale length input and defines its own private static concrete class ArrayList that implements List interface rather than using the well known java.util.ArrayList or other java Collection type,
this may be to make it more efficient or something, you want to implement your own class and you return it to the user without overwhelming him by implementation details since there is an interface he can deal with your private class through.

Can i change default super class set by compiler in java?

every java class has root class is Object class. can i change that class and place of my own class class MyObject extends Object. it have some more functionally.
this thing is possible ???
No, it's not possible. It's not even a compiler issue. java.lang.Object as the root of the inheritance hierarchy is a very fundamental fact of the language definition and even the VM specification.
No, this is not possible. All objects in Java must derive from java.lang.Object.
If you want to add functionality to every object in your system, then I would just introduce your own MyObject class and make sure that all of your classes derive from this. If you want to extend functionality to existing objects, then I'd use static helper methods to do this (in C# you'd use extension methods, but no such option exists in Java).
I have never heard of anything like that. Why would you want to? It would make your code impossible to follow for anyone but you. Every Java programmer out there assumes that either you explicitly extend a class or you extend Object.
Is it really that much work to put in "extends MyObject" at the beginning of your classes? I am pretty sure that Eclipse (and other IDEs) can be configured to automatically insert it for you.
Beside that this seems a questionable approach to me -
you can use bytecode instrumentation to archive this
(but this is not done at compile-time but at vminit/classload time - depending on the type of instrumentation used).

Why would both a parent and child class implement the same interface?

I inherited some legacy Java (1.4) code and this design decision appears regularly. I can't understand if there's any purpose or reason to it.
public interface SoapFacade extends iConfigurable{ }
public class SoapFacadeBase implements SoapFacade{
...
}
public class SoapFacadeImpl extends SoapFacadeBase implements SoapFacade{
...
}
As I understand interfaces (and my experimentation has reinforced), there is no purpose to having both the parent and the child implement the same interface. In this scenario, everything from SoapFacade is implemented in SoapFacadeBase, but the method in iConfigurable is implemented in SoapFacadeImpl. However, that doesn't create a need to have SoapFacadeImpl implement SoapFacade.
Is there something I don't know about interfaces that would give this pattern some purpose or benefit? Are there underlying costs beyond lack of clarity that should drive refactoring it? Or should it simply be refactored for clarity/simplicity?
As I understand interfaces (and my experimentation has reinforced), there is no purpose to having both the parent and the child implement the same interface.
No. Technically, it is completely redundant.
It does however document the fact that you intend SoapFacadeImpl to be a SoapFacade and it ensures that you get a compile error, if you (or someone else) decides to remove implements SoapFacade from the base class.
You see this pattern everywhere in the standard Java Collections API. ArrayList implements List even though its base class (AbstractList) already, does. Same holds for HashSet / AbstractSet and the Set interface.
If you use the interface also as a marker. Class.getInterfaces(); will only return directly instanced interfaces.
I actually find that design pointless. Implemented interfaces, as you stated, are just inherited, so there's no need to copy and paste "implements SomeInterface" on the children classes.
It's not clearer, smarter, or whatsoever...
It is nonsense, don't do it.
Especially in a public API like java collections. It's absolutely nonsense.

Categories

Resources