why every class in java is a subclass of object? [duplicate] - java

This question already has answers here:
Why does every object in Java implicitly extend java.lang.Object class?
(11 answers)
Closed 8 years ago.
The Object class, in the java.lang package, sits at the top of the class hierarchy tree. Every class is a descendant, direct or indirect, of the Object class. Every class you use or write inherits the instance methods of Object.
why do we need a class that is the super class of every other class in java ?

Because this is how Java is being designed. Java treats everything (except pirmitives) as an object including your self-defined objects.
There is an advantage by making all newly created classes to extend from Object. It allows common methods and attributes to be automatically available upon creation of a new object.
Some of the common methods are for example: toString() and equals()..etc

It's useful to have a common behavior/interface among all types for operations like comparison among other things.
It's also useful for when you want to make an array or other collection which contains or can contain different types.

Having Object as an implicit base class of all Java classes helps you write code that does not depend on the precise type, such as a collection, a class that produces string representations, and so on. See documentation of java.lang.Object for a list of methods what every class supports "out of the box".
This is by no means a required feature of all languages: there are other languages where there is no mandatory common subclass. Doing it this way was a choice of the language designers.

Related

Why do you have to define methods in the class rather than the interface? [duplicate]

This question already has answers here:
What does it mean to "program to an interface"?
(33 answers)
Closed 3 years ago.
So, according to GeeksForGeeks, an interface may have fields and method signatures, but those methods cannot be defined.
A class that implements an interface must then define the body of every method in the interface it implements.
If this is the case, what is the point of the method signatures in the interface? Why not allow oneself wiggle room rather than restricting yourself to have to define methods that you may or may not want to use?
Well, there are two points in that.
First, Java supports an implementation in interfaces. You need to use the default keyword, which is in Java since Java 9 (I am not quite sure about the version number). But, why would you do that?
Interfaces share a common interface for several classes and can therefor be used as data types. You can for example write a method, which needs a parameter of an interface type. Within the method you can then call all the parameters methods, where you know their signature, based on the interface.
The point here is, that interfaces describe common behavior. That is, what interfaces are for!
The difference between (abstract) classes and interfaces is: in (abstract) classes, you define, what you have and what it will look like. Inheritance in this case then is a relation of extension (or spezialization), so you describe it in form of the child IS a parent, but it may have something more. But the IS relation is the basic point.
Interfaces describe the behavior, so a class that implements a interface acts like that interface. LinkedList and ArrayList are quite good examples. Internally they look quite different, but they both store many elements (as hash lists do too). Both classes implement the List interface, because you can both treat them as lists: you can for example iterate over them, which is not the case in hash maps.
Thus, if you want to share common structure and content, use inheritance and maybe abstract classes to group them. If you want to share common behavior, use interfaces, because it doesn't matter, how they look inside, but what you can do with them. So you group it by action.
That's not always true. You can provide a default implementation in the interface:
interface SomeInterface {
default int combine(int a, int b) { return a + b; }
}
Now the method implementing SomeInterface can override combine method, but it doesn't have to. In that case it falls back to the default implementation.
Defining methods in the interface allows you to get all benefits of polymorphism. For example, if you have a List, you don't know what exact implementation of List was used to create it - whether it's ArrayList or LinkedList or something else, but you know that you can, for example, add elements in it and get elements from it, because methods add and get are defined in the List interface.

Why only java.lang. Object is given superclass in java? [duplicate]

This question already has answers here:
Why Object class is Superclass in java [closed]
(4 answers)
Closed 6 years ago.
Is there any reason sun microsystems make Object for all javaclass for superclass. I face the question my last interview. I hope, I can find answers here
Thanks
Following could be the reasons for this design decision,
By having the Object as the super class of all Java classes, without knowing the type we can pass around objects using the Object declaration.
Before generics was introduced, imagine the state of heterogeneous Java collections. A collection class like ArrayList allows to store any type of classes. It was made possible only by Object class hierarchy.
The other reason would be to bring a common blueprint for all classes and have some list of functions same among them. I am referring to methods likehashCode(), clone(), toString() and methods for threading which is defined in Object class.
Please check the below link. I hope it will answer your question.
Why object is super class in JAVA

How does a class literal work? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is a class literal in Java?
I was going through literals in the Java tutorial where I came across this sentence:
Finally, there's also a special kind of literal called a class literal, formed by taking a type name and appending ".class"; for example, String.class. This refers to the object (of type Class) that represents the type itself.
Which doesn't make any sense to me, even though I paid attention to all the other topics prior to this. Can anyone explain in simple language with examples or references?
Instances of the class java.lang.Class represent classes and interfaces in a running Java application. For each class in the application, there is an instance of Class. The SomeClass.class syntax is a way to get from SomeClass to the corresponding instance of Class.
A class literal is just a special type to use when you want to do something involving the class itself, rather than an instance.
Here's a short list of a few things I commonly use this for (not at all comprehensive, but you can get a good idea)
1.) Reflection, you want to instantiate something in run-time that you may not know (perhaps it was stored in a variable of type Class)
2.) You want to check if 2 objects are of the same related type, you can write something along the lines of: B.class.isAssignableFrom(a.getClass());
3.) You want to list all the methods, or public variables within a class, perhaps for documentation.
There are many other uses, but these are the main ones I find myself using in common practice.
Speaking simple language: that thing, which you call class literal is an object which fully describes some class: all its methods, all its fields, all its annotations, class's modifiers and so on. It is needed for creating new instances of that class in runtime.
Short example:
Class x = String.class;
System.out.println(x);
you can use x to create runtime instances of the class it points to or to test the class of an object against it.
It evaluates to be the class identifier of the reference or primitive type's wrapper class. The expression void.class evaluates to the class identifier of the Void class. Same thing with 'String.class'

What is an Interface? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is an interface in Java?
Im confused by this term. I search google and this is what I found.
An interface is the place where two different things meet and interact. This term often comes up with regard to computers. Data processing takes place inside the computer, and thoughts take place inside the user of the computer, and they meet at an interface, which is a keyborad and a monitor screen (and usually speakers as well). [DATA -> INTERFACE <- USER]
But in this site I found this.
Java contains many libraries in those packages (Swing, etc.), and the API is the interface by which we request services (perform actions, etc.).[PACKAGES->API<-PROGRAMMER]
But in java we use it like this...
public interface A
public class B implements A
We use it to implement methods from A. Interface here is not a connection between B and methods().
The everyday definition of "interface" seems far removed from the technical meaning of interface in Java, but the two definitions are easily related. In Java, an interface is the specification of the place where an object and other code interact. As with the use of "interface" more generally, a Java object can be treated as having more than one interface.
The critical difference between a Java interface and a Java class is that an interface is purely a specification, whereas a class is a specification plus an implementation of one side of the interface (the object side). (There's an exception: if a class is declared abstract, methods can also be declared abstract, in which case their implementation is defined by subclasses.) A Java class can be declared to implement one or more interfaces, which means that the class (if it is not abstract) must include an implementation for each method specified in each interface.

Class object in Objective C

I am coming from Java to Objective C, and the idea of a class object has me wondering about similarities with Java. From the Objective C guide in Apple documentation:
A class definition's information is compiled and recorded in data structures made available to the runtime systems. The compiler creates just one object, a class object, to represent the class.
So my understanding is that the class object is created for all classes that are going to be used by the program, and a class object is what is used to create objects for that class.
For comparison, does the JVM have a similar object for all classes it loads?
Given that Java was derived directly from Objective-C (no, really, it was), the runtime models of the two are quite similar.
In Java, the notion of a "Class" isn't quite as generic as it is in Objective-C.
In Objective-C, a Class is an instance of what is known as the metaclass. For all intents and purposes, each Class object in Objective-C does exactly as you say; it describes a particular class available in the Objective-C runtime.
The same is conceptually true of Java classes. There is one key difference. In Objective-C, class methods are inherited across subclasses and more significantly a subclass can override a superclass's class method(s).
For example, the NSArray class implements the +array class method (the '+' means "class method"). The NSMutableArray subclass of NSArray overrides +array to return a mutable instance instead.
java.lang.Class is more akin to the Objective-C runtime API; it is the mechanism via which you introspect the classes available in the runtime. Since Java doesn't have functional API, the API is wrapped up in an appropriately named class. java.lang.Class is kinda the runtime API and the metaclass all in one.
A comparable structure in Java would be java.lang.Class.
I think there is a class object for each class.
That class object is the one that, at low level, is used for functions as class_getName(), class_getSuperclass(), class_getVersion(), class_respondsToSelector(). If there would be a single class object for all the classes, then those functions would return the same result for all the classes.

Categories