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
extendsA
and has a method,func(int m)
that prints outs the given int value. - We create a new instance of
Bart
and call thefunc()
method, using as parameters a char, a float and an int. Thefunc()
method is not overriden in classBart
, but it is inherited toBart
. The class can use both the methods of classA
and its ownfunc()
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.
Great information, I get so much information from post and replies. I request you to please write some informative post on java Training.