📜 ⬆️ ⬇️

All about overriding in Java

All good!

This week is practically our anniversary - the fifth group " Java Developer " starts, which means that we again share all sorts of goodies.

Go.
')
If you want to make sure that you redefine in the right way, take a look at this guide, which describes the various tools at your disposal, and some of the pitfalls to watch out for.

A child class can override the methods of an instance of its parent class. This is called method overriding. The signature (return type, parameter type, number of parameters and order of parameters) must be the same as that defined in the parent class. The method override is performed to achieve polymorphism during program execution.



What is polymorphism?

Polymorphism allows you to define one interface and have multiple implementations for it. This is one of the basic principles of object-oriented programming. The word "polymorphism" literally means "the state of the presence of many forms" or "the ability to take different forms." When applied to object-oriented programming languages, such as Java, it describes the ability of a language to process objects of different types and classes through a single, uniform interface.

What is runtime polymorphism (or sending a dynamic method?)

The overridden method is called according to the object to which the method belongs, and not by the type of reference.

What is the benefit of runtime polymorphism?

Static or dynamic polymorphism?

Private, final and static methods use static bindings and are linked by the compiler, while virtual methods are linked at run time based on the object being processed.

Using Override

Use the Override annotation so that the compiler can verify that you really override the method when you count on it. Thus, if you make a common mistake, for example, a typo in the method name or incorrectly set parameters, you will be warned that your method does not actually override it while you are sure of the opposite. Secondly, it improves the readability of the code, making the override more obvious.

In addition, starting with Java 1.6, you can use Override with the same goals to mark when a method implements an interface.

Dynamic Polymorphism Rules

Change method signature

If we use an override, the override method must have the same signature as the override method. You can change the method signature in your child class accordingly, that is, the number of arguments, the type and order of the arguments, and the type of the return value. But this is called overload.

package com.me.overriding; class Parent_params { void method(String a, String b, int v, float d) { System.out.println("parent"); } void method2(String a, String b, int v) { System.out.println("parent"); } void method3(String a, int v) { System.out.println("parent"); } } class Child_Params extends Parent_params { //     , //      ,    //... /*@Override void method(String a){ System.out.println("child"); }*/ //       // /*@Override void method(String a,float d,int a,String b){ System.out.println("parent"); }*/ //Override @Override void method(String a, String b, int v, float d) { System.out.println("child"); } // //      void method(String a, String b, int v) { System.out.println("child"); } void method2(String a, int b, String v) { System.out.println("child"); } void method3(int v, String a) { System.out.println("child"); } } public class Override_Params { public static void main(String[] args) { String temp = "Monday"; Child_Params child_Params = new Child_Params(); /*Parent_params params=new Child_Params(); child_Params=(Child_Params) params; child_Params.method(temp,temp,2);*/ Parent_params params2 = new Parent_params(); child_Params = (Child_Params) params2; child_Params.method(temp, temp, 2); /*up vote 3 down vote accepted  ,      .        Animal   Dog. ,     ,          ,         .    : Animal a = new Dog (); Dog d = (Dog) a;*/ } } 

Type of method return

Return types may vary depending on methods that override each other if return types are reference types. Java supports covariant returns — a return type subtype specialization. A d1 method declaration with a return type of R1 replaces the return value of a d2 method with a return type of R2 if and only if the following conditions are true:


 package com.me.overriding; class Parent1 { public void method(String string) { System.out.println("Parent :" + string); } public void method2(String string) { System.out.println("Parent :" + string); } } class Child1 extends Parent1 { //    Parent1.method (String) @Override public int method(String string) { System.out.println("Child :" + string); } } public class OverrideAllMethods { public static void main(String[] args) { Child1 child1 = new Child1(); child1.method("Me"); } } 

Covariant return type

Returning a covariant means that when overriding a method, the return type of the overriding method is allowed as a subtype of the return type of the override method.

To clarify this with the help of an example, the general case is Object.clone (), which is declared to return an object type. You can override this in your class as follows:


 package com.me.overriding; class ParentCustomClass { public Object m1() { System.out.println(" parent m1()"); return null; } public ParentCustomClass m2() { System.out.println(" parent m2()"); return null; } } class ChildtCustomClass extends ParentCustomClass { @Override public String m1() { System.out.println("child m1()"); return null; } @Override public ChildtCustomClass m2() { System.out.println(" child m2()"); return null; } } public class CoVarientTypes { public static void main(String[] args) { ParentCustomClass class1 = new ChildtCustomClass(); class1.m1(); class1.m2(); /*  d1    R1  --    d2    R2,    ,    :  R1   ,  R2  R1.  R1 ,  R2  .  R1   ,  R2  R1.  R1   , : R1    R2,  R1      R2     R1 = |R2|*/ } } 

Overriding static method (or) Binding method

 package com.me.overriding; class ParentStatic { public static void method(String string) { System.out.println("Parent :" + string); } public void method2(String string) { System.out.println("Parent :" + string); } } class ChildStatic extends ParentStatic { public static void method(String string) { System.out.println("Child :" + string); } } public class StaticMethodOverriding { public static void main(String[] args) { /*1)   (  )       ,  ,        2)    (  ),        ,     ,  ,       . */ ChildStatic.method("Me"); ParentStatic parentStatic = new ChildStatic(); parentStatic.method("Me"); } } 

Static Variable Binding

 package com.me.overriding; class Dad { private static final String me = "dad"; protected String getMe() { return me; } public void printMe() { System.out.println(getMe()); } } class Son extends Dad { private static final String me = "son"; @Override protected String getMe() { return me; } } class StaticVariableOverriding { public static void main(String[] args) { Dad dad = new Son(); dad.printMe(); } } 

Final and private methods

 package com.me.overriding; class Parent_2 { public final void m1() { System.out.println("m1()"); } private void m2() { System.out.println("m2() parent"); } } //      Parent_2 class Child_2 extends Parent_2 { public fianl void m1() { System.out.println("m1()"); } private void m2() { System.out.println("m2() of child"); } } public class FinalandprivateOverriden { public static void main(String[] args) { Parent_2 child_2 = new Child_2(); child_2.m1(); //  m2 ()   Parent_2   child_2.m2(); } }hild_2.m2(); } } 

Redefining Access Levels

 package com.me.overriding; class Parent_Access { protected void method(String a, String b, int v, float d) { System.out.println("parent"); } } class Child_Access extends Parent_Access { //      /*private void method(String a,String b,int v,float d){ System.out.println("parent"); }*/ public void method(String a, String b, int v, float d) { System.out.println("parent"); } } public class Override_AccessLevels { public static void main(String[] args) { } } 

Override with super()

 package com.me.overriding; class SuperParent { public void m1() { System.out.println(" super m1()"); } protected void m2() { System.out.println(" super m2()"); } private void m3() { System.out.println(" super m3()"); } } class SuperChild extends SuperParent { public void m1() { super.m1(); super.m2(); System.out.println("m1()"); } protected void m2() { System.out.println("m2()"); } private void m3() { System.out.println(" m3()"); } } public class OverridingWithSuper { public static void main(String[] args) { SuperParent parent = new SuperChild(); parent.m1(); parent.m2(); } } 

Override with abstraction

 package com.me.overriding; interface Interface { public void m1(); } /*     ,    ,     move ()      AbstractDog:*/ abstract class AbstractClass implements Interface { public abstract void m2(); public void m3() { System.out.println("m3()"); } } /*//   ( )     AbstractDog   Animal,        ,   :*/ class ConcreteClass extends AbstractClass { @Override public void m1() { // TODO     System.out.println("m1()"); } @Override public void m2() { // TODO     System.out.println("m2()"); } @Override public void m3() { // TODO     System.out.println("m3()"); } } public class OverridingWithAbstraction { public static void main(String[] args) { ConcreteClass class1 = new ConcreteClass(); class1.m1(); class1.m2(); class1.m3(); } } 

Override with Exceptions

 package com.me.overriding; import java.io.IOException; import java.nio.file.DirectoryIteratorException; class ExceptionParent { public void m1() throws IOException { System.out.println("m1()"); } } //     throws  ExceptionParent.m1 () //          // CE /*  ExceptionChild  ExceptionParent { public void m1 () throws Exception { System.out.println ( "m1 ()"); }*/ // CE // IllegalArgumentException   /*  ExceptionChild  ExceptionParent { public void m1 () throws Exception, IllegalArgumentException { System.out.println ( "m1 ()"); }*/ // OK bccz   /*  ExceptionChild  ExceptionParent { public void m1 () throws IllegalArgumentException { System.out.println ( "m1 ()"); }*/ /*// CE bcz of Checked  ExceptionChild  ExceptionParent { public void m1 () throws IOException, InterruptedException { System.out.println ( "m1 ()"); }*/ class ExceptionChild extends ExceptionParent { public void m1() throws IOException { System.out.println("m1()"); } } public class OverridingExceptions { public static void main(String[] args) throws IOException { ExceptionParent exceptionParent = new ExceptionChild(); exceptionParent.m1(); } } 

Override from internal private classes

 package com.me.overriding; /* Java-,  ,             */ public class OverrideprivateInnerclass { private String msg = "GeeksforGeeks"; private void fun() { System.out.println("Outer fun()"); } class Inner extends OverrideprivateInnerclass { private void fun() { System.out.println("Accessing Private Member of Outer: " + msg); } } public static void main(String args[]) { //     Inner,   Outer //  . ,     Outer,   //   . OverrideprivateInnerclass o = new OverrideprivateInnerclass(); Inner i = o.new Inner(); //    Inner,    - // ,     Outer     Inner. i.fun(); // o.fun() calls Outer's fun (No run-time polymorphism). o = i; o.fun(); } } 

Override and Overload

 package com.me.overriding; class ParentStatic_1 { public void method(String string) { System.out.println("Parent :" + string); } public void method2(String string) { System.out.println("Parent :" + string); } } class ChildStatic_1 extends ParentStatic_1 { public static void method(String string, int b) { System.out.println("Child :" + string); } public static void method2(String string, int b, float c) { System.out.println("Child :" + string); } } public class OverrideAndOverloadMethods { public static void main(String[] args) { //  (  )    , //  .      //     -   , //  . ParentStatic_1 parentStatic = new ChildStatic_1(); parentStatic.method("Me"); } } 

Multi-level override

 package com.me.overriding; class ParentStatic_2 { public void method(String string) { System.out.println("Parent :" + string); } public void method2(String string) { System.out.println("Parent :" + string); } } class ChildStatic_2 extends ParentStatic_2 { public void method(String string) { System.out.println("Child -1 :" + string); } } class ChildStatic_3 extends ChildStatic_2 { public void method(String string) { System.out.println("Child -2 :" + string); } } class ChildStatic_4 extends ChildStatic_3 { public void method(String string) { System.out.println("Child -3 :" + string); } } public class MultilevelOverriding { public static void main(String[] args) { //     ,    . ParentStatic_2 parentStatic_2 = new ChildStatic_3(); parentStatic_2.method("hey........!"); } } 

Redefining instance methods versus static methods

 package com.me.overriding; class ParentStatic2 { public static void method(String string) { System.out.println("Parent :" + string); } public void method2(String string) { System.out.println("Parent :" + string); } } class ChildStatic2 extends ParentStatic { //         ParentStatic public void method(String string) { System.out.println("Child :" + string); } //         ParentStatic public static void method2(String string) { System.out.println("Child :" + string); } } public class InstanceVsStaticOverriding { public static void main(String[] args) { //      , //       . ParentStatic2 parentStatic = new ChildStatic2(); parentStatic.method("Me"); } } 

Redefining instance methods against static variables

 package com.me.overriding; class B { int a=10; public void print() { System.out.println("inside B super class"); } } class C extends B { int a=20; public void print() { System.out.println("inside C sub class"); } } public class InstanceVariableOverriding { public static void main(String[] args) { B b=new C(); b.print();//it will print inside c sub class System.out.println(ba);//it will print super class variable value=10 /*         , .    ...          Java.  Java     .        ,      ,     .              ...       Java. */ } } 

Constructor override

 package com.me.overriding; class One { public One() { //   } One(int a) { //    } } class Two extends One { /* { //One() { //     //          }*/ Two() { //   } Two(int b) { //    } } public class ConstructorOverriding { /* .     Java.    ,     ,        .    ,      Super,        Sub-.      .     Super Class Constructor  Sub-,  Sub-       ,         Sub-.     ,      .      void,     . */ } 

Constructor with super()

 package com.me.overriding; class Superclass { public Superclass(int x) { System.out.println("000000"); } public Superclass() { System.out.println(" ty"); } public Superclass(String y) {} } class Subclass extends Superclass { public Subclass() { // super (5); //   Superclass(int)  } } public class ConstructorWithSuper { public static void main(String[] args) { new Subclass(); } } 

Overriding another package

 package com.me.overridingtest; import com.me.overriding.PackageParent; public class Child extends PackageParent { @Override public void m1() { System.out.println("m1()"); } @Override protected void m2() { System.out.println("m2()"); } // default     /*default void m3(){ System.out.println("m3()"); }*/ //        final //   public  protected. @Override private void m4() { System.out.println("m1()"); } } package com.me.overriding; import com.me.overridingtest.Parent; public class OtherPackageOverride { public static void main(String[] args) { Parent parent = new com.me.overridingtest.Child(); parent.m1(); parent.m2(); } } package com.me.overriding; public class PackageParent { public void m1() { System.out.println("m1()"); } protected void m2() { System.out.println("m2()"); } // default     /*default void m3(){ System.out.println("m3()"); }*/ private void m4() { System.out.println("m1()"); } } 

Child-to-parent rules: consequences of overriding

 //  -   IS-A: package com.me.overriding; class Parent { public void method(String string) { System.out.println("Parent :" + string); } public void method2(String string) { System.out.println("Parent :" + string); } } class Child extends Parent { @Override public void method(String string) { System.out.println("Child :" + string); } } public class ChildParenRule { public static void main(String[] args) { //  ,   // Parent: Me // Parent parent=new Parent(); // parent.method("Me"); //      Parent      //   CE //      ,  RE //    "main" // java.lang.ClassCastException: com.me.overriding.Parent //      com.me.overriding.Child // at com.me.overriding.ChildParenRule.main (ChildParenRule.java:19) // Parent parent=new Child(); // parent.method("Me"); //    ,     //    // Child child = new Child (); // child.method("Me "); //    -    , //   RE //           child //  ,       // Parent parent=new Child(); // parent.method("Me"); // CE   :       //          //    "main" java.lang.Error: //   : //  ,  «VariableDeclarators»   // LocalVariableDeclaration //  ,  «;»   // LocalVariableDeclarationStatement // at com.me.overriding.ChildParenRule.main (ChildParenRule.java:53) // Child child = (Child) new Parent (); // child.method("Me "); // /* 6 down vote        . Parent parent=new Parent(); ((Child)parent).method("Me");*/ } } 

Instance methods are preferred over default interface methods.

 package com.me.overriding; //   ,     . //     : class Horse1 { public String identifyMyself() { return "I am a horse."; } } interface Flyer { default public String identifyMyself() { return "I am able to fly."; } } interface Mythical { default public String identifyMyself() { return "I am a mythical creature."; } } public class Pegasus extends Horse1 implements Flyer, Mythical { public static void main(String...args) { Pegasus myApp = new Pegasus(); System.out.println(myApp.identifyMyself()); } } //  Pegasus.identifyMyself   I am a horse. 

Programs that contain comments to illustrate the use and effects of the redefinition may have some CE and RE.

THE END

As always, we will be glad to see your comments or questions.

Source: https://habr.com/ru/post/347900/


All Articles