Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override class in java

Assume I have a project K

K depends lib.jar

In lib.jar , there is a class named x.y.z.Foo

If i create the same class x.y.z.Foo in K , then in this project when I create a instance of Foo , now will JVM use Foo in K rather than in lib.jar ?


And if it's unstable or depends on something , how to make sure that Foo should use K's version rather than lib.jar?

like image 989
jackalope Avatar asked Jan 05 '13 03:01

jackalope


People also ask

What is class override in Java?

The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method that it overrides.

Can we override class in Java?

Instance methods can be overridden only if they are inherited by the subclass. A method declared final cannot be overridden. A method declared static cannot be overridden but can be re-declared. If a method cannot be inherited, then it cannot be overridden.

What is a override class?

In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes.

Why @override is used in Java?

The annotation @Override is used for helping to check whether the developer what to override the correct method in the parent class or interface. When the name of super's methods changing, the compiler can notify that case, which is only for keep consistency with the super and the subclass.


1 Answers

Java class loading behaviour in a standalone application (at least with no custom classloaders) is stable. Make sure that your k.jar (or path) comes before lib.jar in -cp java arg

java -cp k.jar lib.jar ...

or add dependencies to /META-INF/MANIFEST.MF of your K project as

...
Class-Path: lib1.jar lib2.jar
...

and run

java -jar k.jar

k.jar classes will be loaded first

in Maven it is

<build>
    <plugins>
        <plugin>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                    </manifest>
                </archive>
            </configuration>
        </plugin>
         ...
like image 60
Evgeniy Dorofeev Avatar answered Sep 30 '22 02:09

Evgeniy Dorofeev