Home » Core Java » class » You cannot override a method just by using the same name

About Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

You cannot override a method just by using the same name

In this example we shall show you why you cannot override a method just by using the same name. We are using two classes as described below:

  • Class A has a method, char func(char a) that returns a char value. It also has a method, float func(float f) that returns a float value.
  • Class Bart extends A and has a method, func(int m) that prints outs the given int value.
  • We create a new instance of Bart and call the func() method, using as parameters a char, a float and an int. The func() method is not overriden in class Bart, but it is inherited to Bart. The class can use both the methods of class A and its own func() method according to the parameter passed,

as described in the code snippet below.  

package com.javacodegeeks.snippets.core;

class A {

    char func(char c) {

  System.out.println("doh(char)");

  return 'd';
    }

    float func(float f) {

  System.out.println("doh(float)");

  return 1.0f;
    }
}


class Bart extends A {

    //notice tha this function is not overriden
    void func(int m) {

  System.out.println("doh(int)");
    }
}

public class Name {

    public static void main(String[] args) {

  Bart b = new Bart();

  b.func(1);

  b.func('x');

  b.func(1.0f);

  b.func(10);
    }
} 

Output:

doh(int)
doh(char)
doh(float)
doh(int)

  
This was an example explaining why you cannot override a method just by using the same name in Java.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments