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.

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.

  • 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

  • Question overloading method

    Hi, thanks for reading this message.
    Here is my problem.
    The context is Servlet and Jsp.
    I am developping and environnement for JSP developpers. This way I defined superclass for JSP pages that give people a basic behavior like getting access to the current user and some usefull methods to access session's parameters.
    This way I developpe a first abstract class with the fallowing method :
    protected void preProcessRequest(HttpServletRequest request, HttpServletResponse response) { ... }
    Now I have to subclass this method in a concreate class. This one will load the current user but, during this operation, an exception can be raised. This is normal. So the signature is now :
    protected void preProcessRequest(HttpServletRequest request, HttpServletResponse response) throws TinyException { ... } ;
    I andrestand why it can't be compiled but don't know how to do this an other way.
    Thank you

    But it's a more general question. When you define a
    framework, you don't know how it will be used. And
    what append if you subclass a method of a framework
    and your implementation throws an exception that
    was not in the abstract classes. Then the framework was badly designed. It needs to be loose enough to allow all sorts of implementations but strict enough to be useful.
    Have you ever wondered why the read & write of the abstract classes InputStream and InputStream throw IOException? Because otherwise it'd be impossible to declare to throw them in the subclasses, that's the way Java goes...
    So blame those who made the abstract class - you cannot declare to throw a totally unexpected exception from the subclass.
    But do note that while you cannot declare to throw the exception, nothing stops you from actually throwing it...

  • For Loop and Void Method Questions

    Question 1: How would I write a for loop that repeats the according to the number entered, to prompt the user to enter a number (double) between 1 and 100. If the number is outside this range it is not accepted.
    Question: 2 Also how would I write a for loop to do sum and find the average of the array numbers in a seperate void method( does not return anything to the main method)?
    Question: 3 (first code snippet) With my for loop that is used to process each number in the array and square it and cube it and display the results to 2 decimal places. How do I make it so say I want the array to allow me to enter 2 numbers (so I enter 2 numbers) then it asks me to enter a number between 1 -100 (which will prompt 2 times) that it shows me the results for the entered numbers between 1-100 after one another instead of number then result number then result like I how it now.
    for (int index = 0; index < howNum; index++) // process each number in the array
              enterYourNumbers = JOptionPane.showInputDialog   
                            ("Enter a number between 1 and 100");                       
              numArray = new double[howNum]; 
            try
                numArray[index] = Double.parseDouble(enterYourNumbers);
            catch (NumberFormatException e)
                    enterYourNumbers = JOptionPane.showInputDialog
                              ("Enter a number between 1 and 100");                          
                DecimalFormat fmt = new DecimalFormat ("###,###.00");
                JOptionPane.showMessageDialog(null, enterYourNumbers + " "  + "squared is "  + fmt.format(calcSquare(numArray[index]))
                                              + "\n" + enterYourNumbers + " " +  "cubed is " + fmt.format(calcCube(numArray[index])));                                                                           
                wantToContinue = JOptionPane.showInputDialog ("Do you want to continue(y/n)? ");
      while (wantToContinue.equalsIgnoreCase("y"));
    import javax.swing.*;
    import java.text.DecimalFormat;
    public class Array
        public static void main(String[] args)
            int howNum = 0;
            int whichNum = 0;     
            double[] numArray;
            boolean invalidInput = true;
            String howManyNumbers, enterYourNumbers, wantToContinue;
      do // repeat program while "y"
          do // repeat if invalid input
            howManyNumbers = JOptionPane.showInputDialog
                        ("How many numbers do you want to enter");                     
            try
                 howNum = Integer.parseInt(howManyNumbers);
                 invalidInput =  false;
            catch (NumberFormatException e )
                howManyNumbers = JOptionPane.showInputDialog
                            ("How many numbers do you want to enter");
          while (invalidInput);
          for (int index = 0; index < howNum; index++) // process each number in the array
              enterYourNumbers = JOptionPane.showInputDialog   
                            ("Enter a number between 1 and 100");                       
              numArray = new double[howNum]; 
            try
                numArray[index] = Double.parseDouble(enterYourNumbers);
            catch (NumberFormatException e)
                    enterYourNumbers = JOptionPane.showInputDialog
                              ("Enter a number between 1 and 100");                          
                DecimalFormat fmt = new DecimalFormat ("###,###.00");
                JOptionPane.showMessageDialog(null, enterYourNumbers + " "  + "squared is "  + fmt.format(calcSquare(numArray[index]))
                                              + "\n" + enterYourNumbers + " " +  "cubed is " + fmt.format(calcCube(numArray[index])));                                                                           
                wantToContinue = JOptionPane.showInputDialog ("Do you want to continue(y/n)? ");
      while (wantToContinue.equalsIgnoreCase("y"));
        public static double calcSquare(double yourNumberSquared)
            return yourNumberSquared * yourNumberSquared;       
        public static double calcCube(double yourNumberCubed)
           return yourNumberCubed * yourNumberCubed * yourNumberCubed;              
        public static void calcAverage(double yourNumberAverage)
    }

    DeafBox wrote:
    Question 1: How would I write a for loop that repeats the according to the number entered, to prompt the user to enter a number (double) between 1 and 100. If the number is outside this range it is not accepted. Use a while loop instead.
    Question: 2 Also how would I write a for loop to do sum and find the average of the array numbers in a seperate void method( does not return anything to the main method)? Why would you want to use 2 methods. Use the loop to sum the numbers. Then after the loop a single line of code calculates the average.
    Question: 3 (first code snippet) With my for loop that is used to process each number in the array and square it and cube it and display the results to 2 decimal places. How do I make it so say I want the array to allow me to enter 2 numbers (so I enter 2 numbers) then it asks me to enter a number between 1 -100 (which will prompt 2 times) that it shows me the results for the entered numbers between 1-100 after one another instead of number then result number then result like I how it now. If I understand you correctly, use 2 loops. One gathers user inputs and stores them in an array/List. The second loop iterates over the array/List and does calculations.

  • 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();
    }

  • Java programming language main method question?

    Hello everyone I am quite new to the Java programming language and I have a question here concerning my main method. As you can see I am calling 4 others methods with my main method. What does the null mean after I call the method? I really don't understand is significance, what else could go there besides null?
    public static void main(String[] args)
              int cansPerPack = 6;
              System.out.println(cansPerPack);
              int cansPerCrate = 4* cansPerPack;
              System.out.println(cansPerCrate);
              have_fun(null);
              user_input(null);
              more_java(null);
              string_work(null);
         }Edited by: phantomswordsmen on Jul 25, 2010 4:29 PM

    phantomswordsmen wrote:
    ..As you can see I am calling 4 others methods with my main method. 'Your' main method? Your questions indicate that you did not write the code, who did?
    ..What does the null mean after I call the method?.. 'null' is being passed as an argument to the method, so there is no 'after the method' about it.
    ..I really don't understand is significance, what else could go there besides null? That would depend on the method signatures that are not shown in the code snippet posted. This is one of many reasons that I recommend people to post an SSCCE *(<- link).*
    BTW - method names like have_fun() do not follow the common nomenclature, and are not good code for a newbie to study. The code should be put to the pointy end of your sword.

  • Namespace, static method questions

    The really useful script here is
    Sephiroth's
    Actionscript 3 PHP Unserializer. I have used the old AS2
    version many times and it's totally rad. With it you can create
    really complex data objects in php,
    serialize() them, and then
    unserialize them with this code in Flash. It dramatically reduces
    the amount of code you have to write to share complex data between
    PHP and Flash.
    The problem I'm having is that the new Actionscript 3 version
    was apparently written for Flex. When I try to use it in flash, I
    get an error:
    1004: Namespace was not found or is not a compile-time
    constant.. This error refers to this line of code:
    use namespace mx_internal;
    I know next to nothing about namespaces in Flash, but best I
    can tell, that namespace constant is apparently to be found in
    mx.core.
    At any rate, if I remove all references to mx_internal
    namespace and mx.core, I can get the script working. This brings me
    to my first questions:
    QUESTION 1: What does the use of that namespace stuff
    accomplish?
    QUESTION 2: Am I likely to suffer any unpredictable consequences
    by removing that namespace stuff?
    Also, I get an error (1061: Call to a possibly undefined
    method serialize through a reference with static type
    org.sepy.io:Serializer.) when I try to call the static methods of
    the Serialize class by instantiating it and calling the methods via
    the instance like this:
    var oSerializer:Serializer = new Serializer();
    var str = oSerializer.serialize(obj);
    That's my third question:
    QUESTION 3: Is it impossible to call a static method of a class
    from an instance of the class? Do we have to reference the class
    name instead?
    Any help would be much appreciated

    nikkj wrote:
    static methods are really class messages, that is, methods that act upon an entire classification of objects not just one instance. it is an elegant means by which to send messages to all instances or rather the class itself
    Static method calls are determined at compile time,not at run time, so it is not possible for the invocation to be polymorphic.(i.e can't be overridden)
    Because the language is defined that way - via the JLS.
    There is no technological reason that precludes a language from doing it. Smalltalk does exactly that.

  • Classes and Methods question

    Hi
    I have a class called Users that i would like to use .... well to store users in the db, i would like to be able to call form the servlet:
    users.addUser(user); or users.deleteUser etc ...
    My question is:
    Do i need a new class eg. addUser that implements TransactionWorker for each method? Or can I do that directly from a method call?
    Regards
    ALex

    HI Alex,
    If you are storing a single record, normally you don't need to use a TransactionWorker, since auto-commit will be used implicitly.
    If you are storing multiple records per transaction, then the TransactionWorker will be at a higher level and will call multiple methods to add/modify/delete records.
    In any case, a TransactionWorker class per method is not normally the right approach.
    --mark                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • 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

Maybe you are looking for