In java, every class extends Object by default, like that, how we can make our class A can be extends by any class in our application by default.
-
Did you mean should - be extended instead of can-be?. All non-final classes can be extended.TheLostMind– TheLostMind2014-10-15 11:22:55 +00:00Commented Oct 15, 2014 at 11:22
-
There is no way of implicitly having every class in your project extends a class. Object is the only class that classes extend by default. You could of course create a class and have every class explicitly extend it.Andy Hedges– Andy Hedges2014-10-15 11:25:24 +00:00Commented Oct 15, 2014 at 11:25
7 Answers
The short answer - you can't.
The slightly longer answer - you can create you own custom empty class...
public class MyObject {
}
.. and make every class in your project extend it...
public class MyOtherClass extends MyObject {
public int doStuff();
}
... but it's really unlikely there'll be any (good) use for this.
Comments
No. The class that other classes extend by default is Object. You cannot change that. It is a fundamental part of the Java language.
The JLS 8.1.4 says:
Given a (possibly generic) class declaration
C<F1,...,Fn> (n ≥ 0, C ≠ Object), the direct superclass of the class typeC<F1,...,Fn>is the type given in theextendsclause of the declaration ofCif anextendsclause is present, orObjectotherwise.
There is no "wriggle room".
If you want all of the classes in your applications to be subclasses of something other than Object, then you must have an extends clause on each and every one of them.
Comments
Answer: You Cannot !!
Object classis the parent of all theclassesin javaWhat ever
classesyou use is a subclass ofobject classby defaultYou can guarantee there will always be certain methods, like
toString(),equals(),hashCode(), etc.It helps in
synchronization,garbage collectionetc
Why it is like this:
Java is designed this way so Object class helps by providing all the above mentioned and more features which are fundamental for object communication and object identifying so to have these functionality explicitly extending a class not required