Overloading method

import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import javax.swing .*;
public class TestOverLoading extends JFrame implements ActionListener{
    private JLabel label1,label2,label3,label4;
    private JTextField field1,field2,field3,field4;
    private JButton button;
    private JPanel labelpanel,fieldpanel;
    private Container container;
    //  public static void main(String[] args) {
    public TestOverLoading(){
        label1=new JLabel("Enter first number");
        label2=new JLabel("Enter second number");
        label3=new JLabel("Enter third number:");
        label4=new JLabel("result");
        labelpanel=new JPanel();
        labelpanel.setLayout(new FlowLayout(label1,label,label3,label4));       
        filed1=new JTextField(10);
        field2=new JTextField(10);
        field3=new JTextField(10);
        field4=new JTextField(10);
        fieldpanel=new JPanel();
        fieldpanel.setLayout(new FlowLayout(field1,field2,fiel3,fiel4) );
        container=getContentPane();
        container.add(labelpanel,fieldpanel);
        int num1=Integer.parseInt(field1);
        int num2=Integer.parseInt(field2);
        int num3=Integer.parseInt(field3);
        button=new JButton("Compare");
        int max=maximum(num1,num2);
        int max=maximum(num1,num2,num3);
        button.addActionListener(
                new ActionListener(){;
                public void ActionPerformed(ActionEvent e){
                    JOptionPane.showMessageDialog(null,"The Largest number is"+max);
    public void maximum(num1,num2){
        if(num1>num2)
            return num1;
        else if(num2>num1)
            return num2
    public void maximum(num1,num2,num3){
        return maximum(maximum(num1,num2),num3);
    protected void addImpl(Component comp, Object constraints, int index) {
    public static void main(String[] args) {
        new TestOverLoading();
}{the error message is:-
**H:\My-JAVA Programs\TestOverLoading\src\TestOverLoading.java:34: <identifier> expected**
**public void maximum(num1,num2){**
**H:\My-JAVA Programs\TestOverLoading\src\TestOverLoading.java:34: <identifier> expected**
**public void maximum(num1,num2){**
**H:\My-JAVA Programs\TestOverLoading\src\TestOverLoading.java:38: ';' expected**
**return num2**
**H:\My-JAVA Programs\TestOverLoading\src\TestOverLoading.java:41: <identifier> expected**
**public void maximum(num1,num2,num3){**
**H:\My-JAVA Programs\TestOverLoading\src\TestOverLoading.java:41: <identifier> expected**
**public void maximum(num1,num2,num3){**
**H:\My-JAVA Programs\TestOverLoading\src\TestOverLoading.java:41: <identifier> expected**
**public void maximum(num1,num2,num3){**
**H:\My-JAVA Programs\TestOverLoading\src\TestOverLoading.java:61: class, interface, or enum expected**
I cant correct the error in my code
please help me
thanks in advance.

import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import javax.swing .*;
public class TestOverLoading extends JFrame implements ActionListener{
    private JLabel label1,label2,label3,label4;
    private JTextField field1,field2,field3,field4;
    private JButton button;
    private JPanel labelpanel,fieldpanel;
    private Container container;
    //  public static void main(String[] args) {
    public TestOverLoading(){
        label1=new JLabel("Enter first number");
        label2=new JLabel("Enter second number");
        label3=new JLabel("Enter third number:");
        label4=new JLabel("result");
        labelpanel=new JPanel();
        labelpanel.setLayout(new FlowLayout(label1,label,label3,label4));       
        filed1=new JTextField(10);
        field2=new JTextField(10);
        field3=new JTextField(10);
        field4=new JTextField(10);
        fieldpanel=new JPanel();
        fieldpanel.setLayout(new FlowLayout(field1,field2,fiel3,fiel4) );
        container=getContentPane();
        container.add(labelpanel,fieldpanel);
        int num1=Integer.parseInt(field1);
        int num2=Integer.parseInt(field2);
        int num3=Integer.parseInt(field3);
        button=new JButton("Compare");
        int max=maximum(num1,num2);
        int max=maximum(num1,num2,num3);
        button.addActionListener(
                new ActionListener(){;
                public void ActionPerformed(ActionEvent e){
                    JOptionPane.showMessageDialog(null,"The Largest number is"+max);
    public void maximum(num1,num2){
        if(num1>num2)
            return num1;
        else if(num2>num1)
            return num2
    public void maximum(num1,num2,num3){
        return maximum(maximum(num1,num2),num3);
    protected void addImpl(Component comp, Object constraints, int index) {
    public static void main(String[] args) {
        new TestOverLoading();
}sorry i send it anthor time with code tage. sorry my frinds

Similar Messages

  • Overloaded methods in stack trace

    There is a thing I thinking about.
    When I have overloaded methods and I want to check a stack trace where one of these overloaded methods take part I cannot decide which method was in the frame, unless I have the source and have debug information in the class file.
    It's not so painful because in most cases people have source code and compile with debug option if they need it, and so the method can be looked up.
    Although, it makes harder to implement runtime test or error processing tools, which works upon stack trace elements. Methods could be annotated with version, author, date and other pieces of information. Runtime test or error processing tools could read and process these annotations.
    Current StackTraceElement implementation makes this possible by using Reflection, while there are no overloaded methods in the stack trace.
    It would be great to include some method into the StackTraceElement which return types of parameters of the stacked methods.
    What's your opinion about this?
    Here is a short source which demonstrates the problem:
    public class Test {
         public void a() { throw new NullPointerException(); }
         public void a(int i) { throw new NullPointerException(); }
         public static void main(String[] a) {
               Test t = new Test();
               Random r = new Random(System.currentTimeMillis());
               if(r.nextBoolean()) t.a(); else t.a(0);
    }I can't decide if a() or a(int) was invoked if I dont' have the source or haven't got debug info (line numbers).

    I guess it would be quite useful in certain cases.
    Let's say we make (runtime readable) annotations on methods with author, version and modification date information.
    When we have an exception stack trace with exact information about concerned methods, we have all information to create and dispatch automatically an error report to the responsible persons based on annotations.

  • Use web service with overloaded method

    Hi all,
    Does anyone knows how can I use (e.g in VC or GP) a web service with overloaded methods?
    When I try to use one, I get the following error message:
    com.sap.engine.services.webservices.jaxrpc.exceptions.ProxyGeneratorException: Proxy Generator Error. WSDL Operation with name [search] is overloaded (defined twice). Operation overloading is not supported by proxy generator.
    Can I set something in order to be able to use such type of services. Or some other solution?
    For some reasons I do not want to change the service operation names.
    Thanks in advance!
    Best regards,
    v s

    Hi all,
    Does anyone knows how can I use (e.g in VC or GP) a web service with overloaded methods?
    When I try to use one, I get the following error message:
    com.sap.engine.services.webservices.jaxrpc.exceptions.ProxyGeneratorException: Proxy Generator Error. WSDL Operation with name [search] is overloaded (defined twice). Operation overloading is not supported by proxy generator.
    Can I set something in order to be able to use such type of services. Or some other solution?
    For some reasons I do not want to change the service operation names.
    Thanks in advance!
    Best regards,
    v s

  • Overloaded methods-yes or no & is this a good practice

    say i have two methods with the same name that take in the same parameters and have the same return type. the difference between the two is that one is static while the other is not. Also the methods contain different codes.
    are the methods going to function normally when i use em? also if they do function normally, is this essentially a good practice?
    if code is needed to answer this, please do mention it and i will think of a mini scenario where this can be applied and write a small piece of code for that.
    thanx. help will be appreciated.

    avi.cool wrote:
    duffymo wrote:
    each account has its own password that the user sets when the account is created-this password is declared as a state variable in the class file. One password per account? A bad model, IMO. My on-line banking software associates credentials with me, not my accounts. I see several accounts when I log in, and I don't have to log in individually for each one.
    besides that, theres also a bank password-this is declared and initialized as a static state variable in the class file. some of the operations require the bank password for access while others require account password.Static bank password? I'm very glad this is a throw-away student exercise, because you have no idea what you're doing.hahaaa, tru tru, its for a skool assignment for my first ever programming course. though not a throw away, i putting a lot of work into this :-) i m not actually trying to resolve any security issues here or strengthen account security. basically, I am only trying to exhibit a tiny bit of creativity while showing understanding of course contents. so nothing to stress on :-D i know not very creative but its all i got at this stage.
    i was trying to exhibit the use of overloaded methods in my program by having method to check the password that the user enters to access operations.
    now the ones that require account password, i was thinking of having the password check method as a non-static method since its associated with the object.
    while the ones that need bank password, i wanted to have as static method.
    i wanted both methods to have the same name.You've no idea what you're doing.
    how i solved it,
    i decided on having both methods as static methods. the one that checks account password, takes in two parameters, the account name(object name) and the string to be checkd. the one that checks bank password, takes in only one parameter- the string to be checked.Wrong.i would be really thankful if you could help me rectify my mistake and advice on how i should be doing this. is there a conceptual error? i am a bit confused now.
    Its exactly what I told you.. but now, you just have to come on here and post this :p
    and isn't this sort of like cheating? :P I mean this IS our exam you know... You're basically asking other for the arithmetic and logic lol.

  • Overloaded methods question

    I guess I don't understand overloaded methods as well as I thought I did, because I'm confused about some behavior I'm seeing in my Java program. Here's a sample program that I wrote up to demonstrate the issue:
    public class Polymorphism
         static class Shape
              public void test()
                   System.out.println( "In Shape" );
         static class Rectangle extends Shape
              int height, width;
              public Rectangle( int height, int width )
                   this.height = height;
                   this.width = width;
              public void test()
                   System.out.println( "In Rectangle" );
              public boolean equals( Rectangle rect )
                   return ( height == rect.height ) && ( width == rect.width );
         public static void main( String[] args )
              Shape shape = new Rectangle( 5, 7 );
              shape.test();
              Shape shape1 = new Rectangle( 3, 4 );
              Shape shape2 = new Rectangle( 3, 4 );
              System.out.println( shape1.equals( shape2 ) );
              System.out.println( ((Rectangle)shape1).equals( shape2 ) );
              System.out.println( shape1.equals( (Rectangle)shape2 ) );
              System.out.println( ((Rectangle)shape1).equals( (Rectangle)shape2 ) );
    }And the output looks like this:
    In Rectangle
    false
    false
    false
    trueThe first call to "test()" calls the Rectangle's test method, as I would have expected. This happens despite the fact that shape is declared as a Shape.
    Here's where I get confused. I would have thought the next four calls to println would have output "true" every time, because shape1 and shape2 are Rectangles, hence, I would have expected that Rectangle's "equals()" method would have been called each time. But apparently it's only being called in the last case, when I cast both shape1 and shape2 to be Rectangles. (Presumably, Object.equals() is being called, and it's appropriately returning "false" because the objects are not the same instance.)
    So this behavior seems inconsistent to me. Why did the first call to "test()" invoke Rectangle.test() even though I declared it as a Shape, yet the succeeding calls to shape1 invoke Shape.equals() rather than Rectangle.equals(), despite the fact that the objects are truly Rectangles?
    Can anyone explain this to me, or point me to a tutorial that would describe this behavior?
    Thanks.

    Case 1 and Case 2 seem analogous to me, yet their
    behaviors are different. (There is one difference
    between the two cases, and that is that in case 1 I'm
    overriding the test() method, while in case 2 I'm
    overloading equals(). Overriding vs. overloading.
    Though clearly these are different concepts, I guess
    it never would have occurred to me that whether a
    method was overridden vs. overloaded made such a
    difference in how invocation worked.)You're right: it's the diffference between overriding and overloading.
    I'll try to formulate it differently:
    At compile-time, the compiler, based on the declared type of the Object the method's called on, and based on the declared types of the arguments, determines which method'll get called (a method is defined by its name and its signature. I don't think the return type matters in this context).
    In the test() case, the compiler looks for a method in class Shape and finds: test().
    In your "third case", the compiler looks for a method named "equals" in class Shape with the argument type: "Rectangle", finds none, so it takes: equals(Object)
    At runtime, the method is looked for in the Object it's invoked on, that is a Rectangle.
    In the test() case, it looks for the method: test(). Since that is declared in the Rectangle class, it takes the overridden method.
    But in the "third case", there's no equals(Object) method, so it takes the super.
    So I apologize if no one can think of a way to make
    this clearer to me, but I still have some subtle
    confusion on the issue.It is a confusing topic. That's why I pointed out itchyscratchy's reply, who made a good point telling to avoid having to rely on overloaded methods generally. Overriding is complicated enough.

  • Overload methods error in web services

    Hi Experts,
    We want to invoke a DotNet web service. The dotnet web service contains overload methods. When I try to invoke this web service from WSNavigator, it shows "WSDL Operation with name search is overloaded (defined twice). Operation overloading is not supported by proxy generator" error. How to solve this issue?
    Best Regards
    Tom

    Hi Tom,
    TO use overloaded methods u have to specify Message Name property.Find the example.
    Here method say() is overloaded
    [webMethod]
    public string say()
        return "hello";
    [web Method]
    public string say(string p_Name)
        return "Hello " + p_Name + "!";
    Adding the Message name property.
    [WebMethod]public string say()
        return "hello";
    [WebMethod (MessageName="WithOneString")]
    public string say(string p_Name)
        return "Hello" + p_Name + "!";
    Regards,
    Sri.
    Edited by: Srikanth Thatipally on Feb 27, 2009 3:33 PM

  • Polymorphism with Overloaded Methods

    I am running into a problem when I try to leverage java��s polymorphism with overloaded Methods. Basically, what I am trying to do is iterate through a generic list of properties and call the correct overloaded method on each one based on the type of containing object.
    Here is the general code (4 classes)
    AbstractCronJob �� EmailCronJob
    BaseProperty �� SubjectLineProperty
    public abstract class BaseProperty implements CronPropertyExecutable{
        public BaseProperty() {
            super();
       public void execute(AbstractCronJob job) {
           System.out.println( "executing on abstract cron job" ) ;
    public class SubjectLineProperty extends BaseProperty {
        public SubjectLineProperty() {
            super();
        public final void execute( EmailCronJob emailCronJob ) {
            System.out.println( "executing on email cron job" ) ;
    public abstract class AbstractCronJob {
        protected int _id ;
        protected PropertyList _propertyList ;
        public AbstractCronJob( int id ) {
            super();
            _id = id ;
            _propertyList = new PropertyList() ;
        protected void createProperties() {
            //fill in with factory crap
            _propertyList.add( new SubjectLineProperty() ) ;
        protected abstract void executeProperties();
        protected abstract void run() ;
        public void execute() {
            createProperties() ;
            executeProperties() ;
            run() ;
    public class EmailCronJob extends AbstractCronJob {
        public EmailCronJob( int id ) {
            super( id ) ;   
        /* (non-Javadoc)
         * @see com.reged.cron.AbstractCronJob#run()
        protected void run() {
            //send email
        protected void executeProperties() {
            //we had this as abstract...unless I'm missing something, we can do this
            //in this class instead of pushing it down
            Iterator iter = _propertyList.iterator() ;
            while ( iter.hasNext() ) {
                //safe cast
                BaseProperty baseProperty = ( BaseProperty ) iter.next() ;
                baseProperty.execute( this ) ;
    }Okay, here is the problem that I am running into. The EmailCronJob knows that it has a list of properties, it doesn't know what type of properties it as. So when it iterates through its property list it upcasts then to the BaseProperty parent class. Then it calls the execute method on each property passing in itself.
    I thought that the execute(EmailCronJob job) method in SubjectLineProperty would be executed since the overloaded method with the mailCronJob parameter lives in that class, instead I am finding that the execute(AbstractCronJob job) method in the BaseProperty class is eing exercised.
    I am confused on why this doesn't work. Does polymorphism work with overloaded methods or just overridden methods?
    Thanks!

    We can think about it based on suppositions, satisfactory explanations, and based on OO design.
    According to the experience from the code above, we can suppose that, at runtime, the virtual machine looks for an exact identical signature of an method to perform the overriding.
    But, why does it work in that way? Is there any good justification, or is it just a implementation decision?
    I think there is a good justification.
    Let me get the Object.equals() method as an example, and let�s make an analogy with the code above. According to our conclusions from the experience above, that we suppose are right and should work, but actually they should not work, in order to use the equals() method, we can simply do this:
    class TheClass {
      private int whatever;
      public TheClass(int param) {
        whatever = param;
      //notice that the param is not Object
      public boolean equals(TheClass param) {
        //we don�t need either to cast to TheClass or
        //verify if the param is an instance of TheClass
        if (this == param) return false;
        if (this.whatever == param.whatever) return true;
        else return false;
    }Apparently, this equals() method above is more efficient, and it does make sense, too, and it would be considered a good and logic implementation of equals() method. Although, these conclusions are wrong, if you consider some OO concepts that are being broken here.
    equals() method is defined in Object class as an contract, like an interface. It says that this method must receive an Object param. And according to this contract, two instances of Object can use this method. You have to obey this contract, because it is Oriented Object Programming.
    If you use equals method without passing Object as an parameter, but passing other different class (like TheClass, in my example), you would not obey the contract, that says that two instances of Object can use this method. Try to do this:
    public static void main(String[] args) {
        TheClass theClass1 = new TheClass(1);
        TheClass theClass2 = new TheClass(1);
        //Good, more or less, because our objective, that is,
        //calling the customized equals(), will be performed.
        System.out.println(theClass1.equals(theClass2));
        String str = "blah";
        //oops! The customized equals() method will not
        //be called this time
        System.out.println(theClass1.equals(str));
        Object obj1 = theClass1;
        Object obj2 = theClass2;
        //Again, the customized equals() method will not
        //be called this time. Thanks God it works in this way!
        //Because if the customized equals() method
        //could be called here, the "OO law"
        //and the "contract" of equals method
        //defined in Object class would be broken
        System.out.println(obj1.equals(obj2));
    }Therefore, I think Java working in this way is good, because it obligates us to "obey the laws", in certain way.

  • Variable arguments and overloading methods

    If I have overloaded methods, say:
    double foo(int... args) and double foo(double... args)
    I can do:
    int[] val = {1,2,3,4,5};
    double dd = foo(val);
    I don't get a compiler error, but if I do:
    int a=1, b=2, c=3, d=4, e=5;
    double dd = foo(a,b,c,d,e);
    java complains that foo(int..) and foo(double...) are ambiguous.
    Why?

    jverd wrote:
    jverd wrote:
    >
    [JLS 15.12.2.4 Phase 3: Identify Applicable Variable Arity Methods|http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.12.2.4]
    and
    [JLS 15.12.2.5 Choosing the Most Specific Method|http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.12.2.5]
    I don't feel like unravelling those in detail right now, but I think it's that an int[] cannot be promoted to a double[], so there's no ambiguity there, but an int can be promoted to a double, so that's ambiguous.Just because two versions apply doesn't make it ambiguous. It's ambiguous when there isn't a "most specific method" demo:
    public class Example {
        static void f(String x, Object y) {} //version 1
        static void f(Object x, String y) {} //version 2
        static void f(Object x, Object y) {} //version 3
        public static void main(String[] args) {
            String s = "string";
            Object o = "object";
            f(s, o);
            f(0, s);
            f(s, s); //ambiguous!
    }I define three versions of f. In the first invocation, versions 1 and 3 apply but 1 is the most specific.
    In the second invocation versions 2 and 3 apply but 2 is the most specific.
    In the third invocation versions 1 and 2 apply but neither is the more specific than the other, so the call is ambiguous.

  • [svn:bz-trunk] 19028: bug fix BLZ-408 MethodMatcher chooses wrong overloaded method

    Revision: 19028
    Revision: 19028
    Author:   [email protected]
    Date:     2010-12-03 13:46:24 -0800 (Fri, 03 Dec 2010)
    Log Message:
    bug fix BLZ-408 MethodMatcher chooses wrong overloaded method
    detected it is an exception case that we did not capture
    fix the exception handling now woring fine
    Checkintests pass
    Ticket Links:
        http://bugs.adobe.com/jira/browse/BLZ-408
    Modified Paths:
        blazeds/trunk/modules/core/src/flex/messaging/util/MethodMatcher.java

  • Overloaded methods in a derived class

    Hello to everyone. I'm starting to learn java with the help of "Thinking in Java". I just want something to make it clearer for me.
    Suppose I have a base class with a method, and a derived class which overloads the method:
    class Base {
      void method() {
        System.out.println("Base method");
    class Derived extends Base {
      void method() {
        System.out.println("Derived method");
    }Now, in another class somewhere I create an instance of Derived:
    Derived dv = new Derived();
    dv.method();There is no way that I can access the method from the Base class, right? The only way I can do that is through
    class Derived extends Base {
      void method() {
        super();
        System.out.println("Derived method");
    }As I said, I'm almost sure that this is correct, I just want a confirmation.

    You can change the class
    class Derived extends Base {
      void method() {
        super.method();
        System.out.println("Derived method");
      // calls Base.method()
      void baseMethod() {
        super.method();
    }

  • How to overload method in web services ?

    hi all !
    how can i overload a web services method ? , i hear about using javax.xml.ws.RequestWrapper , but when i try to use wsimport , it say : error dupplicate method.
    this is the sample from forum :
    package my.ws;
    import javax.jws.WebMethod;
    import javax.jws.WebParam;
    import javax.jws.WebService;
    import javax.xml.ws.RequestWrapper;
    import javax.xml.ws.ResponseWrapper;
    @WebService
    //(name="HelloWS", serviceName="HelloWSService")
    public class Hello {
          * Web service operation
         @WebMethod
         @RequestWrapper(className = "com.veera.Clac.CalculatorRequest", targetNamespace = "http://Calc.veera.com/")
         @ResponseWrapper(className = "com.veera.Clac.CalculatorResponse", targetNamespace = "http://Calc.veera.com/")
         public int add(@WebParam(name = "a")
         int a, @WebParam(name = "b")
         int b) {
              // TODO implement operation
              return 0;
          * Web service operation
         @WebMethod
         @RequestWrapper(className = "com.veera.Clac.CalculatorOverloadRequest", targetNamespace = "http://CalcOverLoad.veera.com/")
         @ResponseWrapper(className = "com.veera.Clac.CalculatorOverloadResponse", targetNamespace = "http://CalcOverLoad.veera.com/")
         public String add(@WebParam(name = "v")
         String v) {
              // TODO implement operation
              return "Veera";
    }thanks

    Hi, Eric,
    Thank you for your quick reply.
    The web service I am trying to develop is basically a generic Data Access Component to bridge between SQL server and a desktop .Net application. The application will have about 3000 users from WAN, therefore we want to have a server side component to handle connection pooling etc. Because of limitation of current servers, we are asked to develop a Java Web Service, instead of MS WS.
    To make the component more reusable, I am thinking to have methods like this in the service:
    RunQueryReturnRS(String Sql, WebRowSet, rs)
    RunQueryReturnInt(String Sql, int NumRecdImpacted)
    RunStoredProcedureReturnRS(….)
    RunStoredProcedureReturnInt(….)
    ……
    You see, I would like to get whole resultset back to client, including both metadata and data in a format of generic resultset. When I paged through the Sun’s document, finding WebRowSet is claimed to be seariable, and ready for Web Service. I thought if I can use WebRowSet that will save me time to write new classes to hold resultset info and pass back to client.
    Could you please tell me if it is a feasible approach?
    Thank you.
    -Qing

  • Subtracting two parameters using overloaded methods.

    Could someone please tell me where I am making my mistakes.
    The idea is to pass the variables to two parameters that then subtracts them regardless of order (larger parameter - smaller parameter) and gives a result.
    Any help is greatly appreciated.
    public class OverLoad{
      public static void main(String[] args){
        int n1 = 25;
        int n2 = 10;
        double d1 = 15.0;
        double d2 = 30.0;
    // This is what the output should look like minus the negative numbers.
    /*System.out.println("Parm1 Type \tParm2 Type 2 \tResult Type");
        System.out.println(n1 + "\t\t" + n2 + "\t\t" +(n1 - n2));
        System.out.println(d1 + "\t\t" + d2 + "\t\t" +(d1 - d2));
        System.out.println(n1 + "\t\t" + d2 + "\t\t" +(n1 - d2));
        System.out.println(d1 + "\t\t" + n2 + "\t\t" +(d1 - n2));
    public static int max(int parm1, int parm2){
        if (parm1 < parm2) {
                 int temp = parm1;
                 parm1 = parm2;
                 parm2 = temp;
    System.out.println(+ parm1, + parm2 = "");
      public static double max(double parm1, double parm2){
        if(parm1 > parm2){
          return parm1;
        return parm2;
      public static double max(int parm1, double parm2){
        if(parm1 > parm2){
          return parm1;
        return parm2;
      public static double max(double parm1, int parm2){
        if(parm1 > parm2){
          return parm1;
        return parm2;
    }

    That's what I have been trying but with no success.
    I have two pieces of code.
    This is what I am looking for except two of the numbers need to be double and it doesn't use enough methods. When I try to do that I get compiling errors.
    public class Overload{
      public static int max(int parm1, int parm2){
        int diff = 0;
        if(parm1 > parm2){
          diff = parm1 - parm2;
        else{
          diff = parm2 - parm1;
        return diff;
      public static void main(String args[]){
        int maxValue = 0;
         int n1 = 5;
         int n2 = 10;
         int d1 = 12; // this should be a double
         int d2 = 20; // this should be a double
         System.out.println("Parm1 Type\tParm2 Type\tResult");
        maxValue = max(n1, n2);
        System.out.println(n1 +"\t\t" + n2 +"\t\t" + maxValue);
        maxValue = max(d1, d2);
        System.out.println(d1 +"\t\t" + d2 +"\t\t" + maxValue);
        maxValue = max(n1, d2);
        System.out.println(n1 +"\t\t" + d2 +"\t\t" + maxValue);
         maxValue = max(d1, n2);
        System.out.println(d1 +"\t\t" + n2 +"\t\t" + maxValue);
    }This is probably closer to what I need and have tried everyone's suggestions but still get compiling errors.
    public class NextOverload {
         public static void main(String[] args) {
              int n1 = 10;
              int n2 = 5;
              double d1 = 10.0;
              double d2 = 5.0;
              int result = 0;
              int k = diff (n1, n2);
              double l = diff (d1, d2);
              double m = diff (n1, d2);
              double n = diff (d1, n2);
              System.out.println("Parm1 Type\tParm2 Type\tResult");
              System.out.println(n1 +"\t\t" + n2 + "\t\t" + k);
              System.out.println(d1 +"\t\t" + d2 + "\t\t" + l);
              System.out.println(n1 +"\t\t" + d2 + "\t\t" + m);
              System.out.println(d1 +"\t\t" + n2 + "\t\t" + n);
    public static int diff(int p1, int p2) {
         int result;
         if (p1 > p2)
              result = p1 - p2;
         else
              result = p2 - p1;
         return result;
    public static double max(double p1, double p2) {
         int result;
         if (p1 > p2)
              result = p1 - p2;
         else
              result = p2 - p1;
         return result;
    public static double max(int p1, double p2) {
         int result;
         if (p1 > p2)
              result = p1 - p2;
         else
              result = p2 - p1;
         return result;
    public static double max(double p1, int p2) {
         int result;
         if (p1 > p2)
              result = p1 - p2;
         else
              result = p2 - p1;
         return result;
    }I haven't given up just quite yet but I know I am getting close, or at least it feels like I am. : )

  • Overloading methods that do logically different things, does this break any major principles?

    This is something that's been bugging me for a bit now. In some cases you see code that is a series of overloads, but when you look at the actual implementation you realize they do logically different things. However writing them as overloads allows the caller
    to ignore this and get the same end result. But would it be more sound to name the methods more explicitly then to write them as overloads?
    public void LoadWords(string filePath)
    var lines = File.ReadAllLines(filePath).ToList();
    LoadWords(lines);
    public void LoadWords(IEnumerable<string> words)
    // loads words into a List<string> based on some filters
    Would these methods better serve future developers to be named as LoadWordsFromFile() and LoadWordsFromEnumerable()?
    It seems unnecessary to me, but if that is better what programming principle would apply here?
    On the flip side it'd make it so you didn't need to read the signatures to see exactly how you can load the words, which as Uncle Bob says would be a double take. But in general is this type of overloading to be avoided then?

    Hi PandoraElite,
    >>Would these methods better serve future developers to be named as LoadWordsFromFile() and LoadWordsFromEnumerable()? It seems unnecessary to me, but if that is better what programming principle would apply here?
    I think you could define a class with many complex behavior, and the behavior has the same method name with different parameters like below:
    //difine the class
    public class LoadClass
    public void LoadWords(string filePath)
    //add method
    MessageBox.Show("string");
    public void LoadWords(IEnumerable<string> words)
    // loads words into a List<string> based on some filters
    MessageBox.Show("IEnumerable<string> words");
    //use the class
    string str = "hello";
    List<string> list = new List<string> { "h","e","l","l"};
    TestClass.LoadClass loadclass = new TestClass.LoadClass();
    loadclass.LoadWords(str);
    loadclass.LoadWords(list);
    >>On the flip side it'd make it so you didn't need to read the signatures to see exactly how you can load the words, which as Uncle Bob says would be a double take. But in general is this type of overloading to be avoided then?
    I think it would be better not to use the “LoadWords(lines)” in the “public void LoadWords(string filePath)”. When you modify the “LoadWords(IEnumerable<string> words”, it would affect the “LoadWords(lines)” method and the function of the “LoadWords(lines)”method
    might be effected.
    Best Regards,
    Edward
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

  • Overloaded method compile error

    i have an inner class which has a method myMethod(boolean). the outer class also has a method of the same name (which the inner class's method overloads) myMethod( String, boolean ). if i try to call the outer class's method from the inner class, the compiler complains:
    myMethod(boolean) in MethodTest.PrivateMethodClass cannot be applied to (java.lang.String,boolean)
    it seems that the compiler doesn't realize that the outer method should be called, and is trying to use the inner one. naturally, if i change the name of the outer method, it works. is this a bug (which it seems like) or some "feature" of java?
    here is the testcase code:
    public class MethodTest
      public boolean myMethod( String s, boolean flag )
        System.out.println( s );
        return flag;
      private class PrivateMethodClass
        boolean value;
        public PrivateMethodClass()
          value = myMethod( false );
        public boolean myMethod( boolean flag )
          return myMethod( new String( "Inner myMethod" ), flag );
    }

    In particular, Java code can directly use all methods
    of all current instances. Class scoping does not
    influence overloading
    The above does not apply since you are not overloading.
    JLS Section 8.5 defines a member class declaration and refers to 6.3 for the scope. Section 8.1.5 says that if you use the same name in an inner class, the name is shadowed. 6.3.1 defines shadow-ing. Section 15.12.1 defines compile-time resolution of methods.
    From these sections, it seems to me that your inner class method is shadowing the outer class method. Shadowing is different from hiding, overriding, or overloading. The compiler is not going to look for a method with a different number of parameters because you are not overloading. The compiler finds the myMethod in the inner class because the name matches.
    A simple example of shadowing. Your code has the same issues with the added complexities of using an inner class and shadowing a method instead of a variable. public class Test  {
         String v = "hello";
         public static void main (String[] args) throws Exception {
              Test t = new Test();
              t.myMethod();
              System.out.println(t.v);
         public char myMethod() {
              int v;
              v = 5;
              return v.charAt(0); //compile time error int can't be dereferenced

  • Overloading methods in interfaces

    Hi,
    I have a class that performs a simple search, using an interface to guarantee the lessThan method in any class that i want to sort. My problem is that i can only search by one variable. ie. i have a students class :
    class Students implements Sortable {
    private String studentNumber;
    private int totalMarks;
    Students(String n, int m) {
    studentNumber = n;
    totalMarks = m;
    public boolean lessThan(Sortable a) {
    Students temp = (Students)a;
    return (studentNumber.compareTo(temp.studentNumber) < 0);
    public String toString() {
    return studentNumber + totalMarks;
    i also want to be able to sort by the total marks.
    is there anyway to provide two lessThan methods in the Students class?
    Thanks
    Alex

    Hi,
    A class can only implement an interface once, so if you need multiple lessThan implementations then you'll need multiple classes for each. Alternatively you can have lessThan compare different things depending on some external flag (i.e. a static variable as mentioned by dforbu), but this is a pretty crude solution.
    If you need to be able to compare using differing criteria you should think about defining a number of Comparators instead (probably as static inner classes):
    public static class StudentNumberComparator
       implements Comparator
       public int compare( Object o1 , Object o2 )
          Students s1 = (Students) o1;
          Students s2 = (Students) o2;
          return s1.studentNumber.compareTo( s2.studentNumber );
    public static class TotalMarksComparator
       implements Comparator
       public int compare( Object o1 , Object o2 )
          Students s1 = (Students) o1;
          Students s2 = (Students) o2;
          return s1.totalMarks - s2.totalMarks;
          }You can then use the methods in the Arrays class to do the sorting and searching, by using these Comparators.
    Ol.

  • Calling overloaded method in parameterized class (Generics)

    Hi all,
    can anybody tell me, why the following method call produces a compilation-error?
    public class Foo<K extends String, V extends Integer> {
        public void bar(V value){
            this.bar(value.toString());
        public void bar(K key){
            System.out.println("Hello World!");
    }Eclipse says:
    "The method bar(V) in the Type Foo<K,V> is not applicable for the arguments (String)"
    Why, doesn't the compiler accept the second method taking the typeparameter subclassing String as argument?

    Thank you for your answer, David. You're totally right. When trying to find a simple example, I made some mistakes. ;-)
    My real problem looks like this:
    public interface IKey {
    public interface IValue {
        public IKey getKey();
    public class MyHashContainer<K extends IKey, V extends IValue> extends MyContainer<V> {
        private Hashtable<K,V> hash;
        // Inherited from MyContainer<V>:
        public void addElement(V value){
            this.addElement(value.getKey(), value);
       public void addElement(K key, V value){
            hash.put(key, value);
    }The error message remains the same.
    The problem is, that I have to inherit the method addElement(V value). How can I create a Container which both is polymorphic and handles Ks and Vs only. I don't want to use IKey and IValue in the method's declaration, because I want to avoid type casts whereever possible.

Maybe you are looking for

  • ADRC updation in Creation of Sales order ( VA01)

    Hi All, I would like to update the Transportation zone(TRANSPZONE) of table ADRC while creating Sales order. I need to change this programatically. (Validation & change as per requirment) Please let me know the user-exit and  internal table i should

  • Batch determination issue in process order Material quantity calculation

    Dear Gurus, We are facing issue in auto batch determination in process order (Material quantity calculation ). eg Material X  is active material 200 KIA used in BOM as 10  X   200  KIA   20  Y   10           Filler 30  Z 40  X   200  KIA 50  Y 60  Z

  • The titles are not saved when i quit

    After quiting FCPX the titles i have made are not saved for next time i open a project. Some titles are saved sometime?

  • My Razr maxx hd keeps dropping calls daily no matter where I am. How can I fix this?

    This phone keeps dropping calls a few minutes in most of the time. I am tempted to tossing this phone out and switching to iPhone but I loved the droids since the beginning. This has been happening for the last year and now I am tired of it. This pho

  • 1080p output possible from iDVD?

    I want to get hi-def output to burn travelogue DVDs of pictures and video clips. I have read that iDVD will only directly burn 720P output. On a large LCD screen, the results at 720 are obvious. Toast with a HD plugin can burn HiDef (and BlueRay), bu