class

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.

Ilias Tsagklis

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

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

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Akash
3 years ago

Great information, I get so much information from post and replies. I request you to please write some informative post on java Training.

Back to top button