Search code examples
javanetbeanssuperclassoverriding

Is there any way to override methods in NetBeans automatically?


I have to do some overriding on several Java classes from one super class. I used suggestions and shortcuts to do so. NetBeans do automatically override the methods.

But when I need to change a method in the super class, I have to do it one by one. Is there any method to override them automatically?


Solution

  • Thanks to NetBeans, it can be done easily.

    Imagine this is your project structure:

    refactordemo
    |-- Parent.java
    |-- Child.java
    

    and this is the Sample code:

    Parent.java

    package refactordemo;
    public class Parent {
        public static void main(String[] args) {
    
        }
        public String method1() {
            return null;
        }
    }
    

    Child.java

    package refactordemo;
    public class Child extends Parent {
        public static void main(String[] args) {
    
        }
        @Override
        public String method1() {
            return super.method1();
        }
    }
    

    Notice that the method1() of class Child overrides method1() of class Parent.

    Now, if you want to change the signature (return type, method name, parameters) of method1() in class Parent and want those changes in all the child classes, then NetBeans is just what you need.

    1. Go to Parent.java (parent class)
    2. Find the method whose signature you want to change (method1() in this case)
    3. Right click on the method name
    4. Go to Refactor > Change Method Parameters... enter image description here

    There... you have it all.

    What stuff can you do here:

    enter image description here

    1. Add / Remove parameters.
    2. Change data type of existing parameters.
    3. Change access modifier of the method.
    4. Change return type of the method.
    5. Change the name of the method.

    The changes I did

    After making the required changes, click 'Refactor' at the bottom of the window.

    Anytime better than ctrl-c and ctrl-v

    Please note that I am using NetBeans 8.0.1 but as per my knowledge this feature is present since NetBeans 7.3