Can i change default super class set by compiler in java? - 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).

Related

How to check a specific class type exists in the inheritance chain

I have a class which is implements the decorator pattern. I need to check whether a specific class appear in the inheritance chain. Normally, I would just use instanceof.
However, I don't have the class definition during dev time. In other words, I get the class name (as a String) at run time. In this situation, how could I check this given class name appears in the inheritance chain?
Firstly, sounds horrible. Reflection is usually a really bad idea.
Edit: As #Holger points out in the comments, dynamic checking of type hierarchies is also a really bad idea. (Shame there's more than one new language feature coming for that. Ho hum.) Even more generally, keep your type hierarchies flat. But that's a whole new kettle of fish. In my experience, it's reflection that typically (not always, Credit Suisse!) highlights and promotes confusion.
Having said that: You will, of course, need the fully qualified class name (although you could probe a sequence of packages). From there, Class.forName methods will allow you to recover the Class object (though if you are using multiple class loaders, it could get messier). Then you just need Class.isAssignableFrom.

Is it mandatory utility class should be final and private constructor?

By making private constructor, we can avoid instantiating class from anywhere outside. and by making class final, no other class can extend it. Why is it necessary for Util class to have private constructor and final class ?
This is not a mandate from a functional point of view or java complication or runtime. However, it's a coding standard accepted by the wider community. Even most static code review tools, like checkstyle, check that such classes have this convention followed.
Why this convention is followed is already explained in other answers and even OP covered that, but I'd like to explain it a little further.
Mostly utility classes are a collection of methods/functions which are independent of an object instance. Those are kind of like aggregate functions as they depend only on parameters for return values and are not associated with class variables of the utility class. So, these functions/methods are mostly kept static. As a result, utility classes are, ideally, classes with only static methods. Therefore, any programmer calling these methods doesn't need to instantiate the class. However, some robo-coders (maybe with less experience or interest) will tend to create the object as they believe they need to before calling its method. To avoid that, we have 3 options:
Keep educating people to not instantiate it. (No sane person can keep doing it.)
Mark the utility class as abstract: Now robo-coders will not create the object. However, reviewers and the wider java community will argue that marking the class as abstract means you want someone to extend it. So, this is also not a good option.
Private constructor: Not protected because it'll allow a child class to instantiate the object.
Now, if someone wants to add a new method for some functionality to the utility class, they don't need to extend it: they can add a new method as each method is independent and has no chance of breaking other functionalities. So, no need to override it. Also, you are not going to instantiate it, so no need to subclass it. Better to mark it final.
In summary, instantiating a utility class (new MyUtilityClass()) does not make sense. Hence the constructors should be private. And you never want to override or extend it, so mark it final.
It's not necessary, but it is convenient. A utility class is just a namespace holder of related functions and is not meant to be instantiated or subclassed. So preventing instantiation and extension sends a correct message to the user of the class.
There is an important distinction between the Java Language, and the Java Runtime.
When the java class is compiled to bytecode, there is no concept of access restriction, public, package, protected, private are equivalent. It is always possible via reflection or bytecode manipulation to invoke the private constructor, so the jvm cannot rely on that ability.
final on the other hand, is something that persists through to the bytecode, and the guarantees it provides can be used by javac to generate more efficient bytecode, and by the jvm to generate more efficient machine instructions.
Most of the optimisations this enabled are no longer relevant, as the jvm now applies the same optimisations to all classes that are monomorphic at runtime—and these were always the most important.
By default this kind of class normally is used to aggregate functions who do different this, in that case we didn't need to create a new object

Check if object is instanceof a protected class

Say I am using a Java library that has the following method
public static SomeInterface foo();
The interface SomeInterface has multiple implementations, some of which are protected within the library's package. One of these implementation is TheProtectedClass
What would be the best way to check if the object returned by foo() is an instance of TheProtectedClass?
My current plan is to create an Utils class that lives within my project but in the same package as the protected class. This Utils can refer to TheProtectedClass since it is in the same package and thus it can check if an object is instanceof TheProtectedClass.
Any other ideas?
EDIT: Some people are asking "why" so here is more context.
I am using jOOQ and in some part of my code, I want to know if the Field instance that I have is an instance of Lower.
Currently, I use field.getName().equals("lower") but this isn't as robust as I'd like it to be.
I realize that since Lower is a protected class, it isn't part of the API and that it can change but I am ok with that.
Class.forName("TheProtectedClass").isAssignableFrom(foo())
although it is a bad idea for many reasons. You're breaking the encapsulation and the abstraction here. If it's package-private, you shouldn't have to concern with it outside. If it's protected, you should explicitly inherit from it and use the API provided by class for this case.
The less obvious but more correct solution is to get an instance of TheProtectedClass, and compare it by
guaranteedTPCInstance.getClass().isAssignableFrom(foo())
, while still being kind of hacky, at least is more portable and OOPy IMO.
As to your idea of creating a class in the same package as TheProtectedClass to avoid being package-private - it's a viable solution, but a) it breaks the basic principle of encapsulation and the programming contract of the TPC class; packaging is done by library/class authors for a reason - to prevent irresponsible data access and using private API or undocumented proprietary methods, b) it's not always possible (and shouldn't be possible in case of properly designed library classes), since those classes can be not only package-private, but final or effectively final (anonymous inner classes etc) - for the reasons described by Bloch in EJ 2nd, "favor composition over inheritance" item, see also Good reasons to prohibit inheritance in Java? Use of final class in Java etc c) you can't do it with some Java library classes, as you can't define your class to be and use e.g. java.lang package. As such, the only "portable" solution is through reflection and through what I described.
tl;dr The fact you can piggyback another package by mimicking its package definition is an obvious C-style deficiency of Java's syntax (allowing programmer to do what he shouldn't be able to normally do; same goes with some specific reflection methods); hacks made this way are neither maintainable nor safe.
NOTE: If you you expect to do something in a internal implementation-dependent and, at the same time, portable and maintainable (e.g. impervious to implementation changes/class name changes etc) way, you're obviously expecting the impossible.
It appears that the best solution is to create a package in your project that has the same package as the package-private class and either expose TheProtectedClass.class as a Class<?> or simply add a simple method that checks if your Object is instanceof TheProtectedClass.
This does not require reflection, it is fast and relatively safe (compilation will break if the package-private class changes name).

SONAR Violation IllegalType, why it is important to fix it?

I have noticed in SONAR that I have a violation that is called IllegalType in my java Code. I looked for this and in Checkstyle explain about it this :
Checks that particular class are never used as types in variable declarations, return values or parameters. Includes a pattern check that by default disallows abstract classes.
Rationale: Helps reduce coupling on concrete classes. In addition abstract classes should be thought of a convenience base class implementations of interfaces and as such are not types themselves.
But I don't understand really why is this a problem in my code. If anyone can explain me better maybe with an example it could be great!. Thanks at all.
What Aaron Digulla said in his comments is a good practice for sure. However I also found this IllegalType issue with my own Abstract Classes (instead of interfaces) which don't seem to me to be pretty clear. I understand the benefits of using intefaces insteaf of classes, and I also understand that abstract classes are partially classes (so much more a class than a interface) but I don't see the benefits of this rule, as I can find cases where I can return a concrete class (no abstract) which is a superclass of what I'm actually returning.
Not all violations that Sonar finds are for everyone. The check IllegalType (docs) tries to make sure you don't use classes that most developers deem "broken" in some way like Vector (use ArrayList instead).
Other classes shouldn't be used as a return type. Always return List instead of ArrayList, Set instead of HashSet, Map instead of HashMap - that way, consumers of your code don't know any unnecessary details about your implementation. If you find you need to replace HashMap with TreeMap (or vice versa) in a method, that will be much more simple if you don't have to change all the places as well where this method was called.
Generally, the check isn't a problem as such (your code works) but fixing those will make your code easier to maintain in the future.

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

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.

Categories

Resources