Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subclass compilation in Java

I have read that Inheritance is a "compile-time' phenomenon. Also in a different place I have read that the superclass code is loaded by classloader, which I deduce happens at run-time. This is causing me some confusion regarding the nature of inheritance. Does the class file of sublass contain the actual compiled code of superclass, or is it accessed at run-time?

like image 818
Mangesh Kherdekar Avatar asked Feb 10 '14 16:02

Mangesh Kherdekar


People also ask

What is subclass in Java with example?

A subclass is also called a child class and a class whose subclass is made is called a superclass or parent class. The process of creating a subclass of a class is called inheritance. Thus, in the Square-Rectangle example, Rectangle is the superclass and Square is the subclass.

What is a subclass with example?

A subclass is a class derived from the superclass. It inherits the properties of the superclass and also contains attributes of its own. An example is: Car, Truck and Motorcycle are all subclasses of the superclass Vehicle.

What is subclass method in Java?

In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those classes. Definitions: A class that is derived from another class is called a subclass (also a derived class, extended class, or child class).

What is the use of subclass?

A subclass inherits the methods and instance data of its superclasses, and is related to its superclasses by an is-a relationship. For example, if subclass P inherits from superclass Q, and subclass Q inherits from superclass S, then an instance of P is an instance of Q and also (by transitivity) an instance of S.


2 Answers

So consider you create a class that inherits a class that is included in a 3rd party jar file.

In order to compile your code you need to have the 3rd party jar file in the classpath of your compiler.

In order to run your code you will also need the jar file in the classpath of the java command that launches the application.

Your subclass does not contain the code of the superclass, it is in the jar files. Your compiled class contains a reference to the superclass. When your class is loaded by the classloader it searches the classpath for the superclass and loads it.

like image 167
mikea Avatar answered Sep 22 '22 23:09

mikea


Where did you read it's compile time? I guess if you're compiling your subclass then yes, it needs to have a superclass to reference when being compiled.

But when you actually run the code it is dynamically linked as per:

http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-5.html

"The Java Virtual Machine dynamically loads, links and initializes classes and interfaces"

like image 29
rainkinz Avatar answered Sep 22 '22 23:09

rainkinz