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

Similar Messages

  • Implements interface method at the derived class

    Hi all.
    I have a class (Derived) that extends another class (Base).
    In the base class (Base) there is a method f() with its implementation.
    In the interface (C) there is also f() method exactlly like in the base class (Base).
    The derived class (Derived) is implements the interface (C).
    My question is:
    Do i have to implement the method f() in the derived class (Derived) ?

    My guess is that you probably have to, even if it's just to call the parent's method.
    This all sounds pretty sketchy. Why don't you just make the BASE class implement your interface?

  • Base class vs derived class

    We have entity classes that we use to access our database. We have subclasses derived from these entity classes that apply business rules. For instance, the base class AddressEntity has a
    setAddress2(string) that AddressEntity.select() uses to set a class variable with data retrieved from the database. The derived class Address also has a setAddress2(string) method that puts restrictions on the length of the data. I want the AddressEntity.select() method to use the base class method AddressEntity.setAddress2(). I've tried using this.setAddress2() in AddressEntity.select() but the derived class method is still used. Any suggestions?
    Thanks,
    Joe

    If you need to call some methods on the base class sometimes and some methods on the derived class other times, but using the same object, then yes dubwai is right you should revisit your Object hierarchy.
    One simple way to do what you are asking is to have your method(s) look like this:
    void setAddress2(String sAddress) { setAddress2(sAddress, true); }
    void setAddress2(String sAddress, boolean bRestrictLength) {
      // real method
    }then you could just look at the variable bRestrictLength to see if you need to restrict the length, and have it default to true. In this way you can use overloading to solve your problem.

  • Can i call non -abstract method in abstract class into a derived class?

    Hi all,
    Is it possible in java to call a non-abstract method in a abstact class from a class derived from it or this is not possible in java.
    The following example will explain this Ques. in detail.
    abstract class A
    void amethod()
    System.out.println(" I am in Base Class");
    public class B extends A
    void amethod()
    System.out.println(" I am in Derived Class");
    public static void main (String args[])
    // How i code this part to call a method amathod() which will print "I am in Base Class
    }

    Ok, if you want to call a non-static method from a
    static method, then you have to provide an object. In
    this case it does not matter whether the method is in
    an abstract base class or whatever. You simply cannot
    (in any object oriented language, including C++ and
    JAVA) call a nonstatic method without providing an
    object, on which you will call the method.
    To my solution with reflection: It also only works,
    if you have an object. And: if you use
    getDeclaredMethod, then invoke should not call B's
    method, but A's. if you would use getMethod, then the
    Method object returned would reflect to B's method.
    The process of resolving overloaded methods is
    performed during the getMethod call, not during the
    invoke (at least AFAIK, please tell me, if I'm wrong).You are wrong....
    class A {
        public void dummy() {
             System.out.println("Dymmy in A");
    class B extends A {
         public void dummy() {
              System.out.println("Dymmy in B");
         public static void main(String[] args) throws Exception {
              A tmp = new B();
              Class clazz = A.class;
              Method method = clazz.getDeclaredMethod("dummy", null);
              method.invoke(tmp, null);
    }Prints:
    Dymmy in B
    /Kaj

  • Invoking Derived Class Method

    Hi pls go through the below code, can any one give me solution how to access the Derived class method in this Point.
    Note: In the below code , only in runtime we will come to know which Derived class method is going to invoke(So in runtime we will get Derived class name in the form of String). So Iam trying to Use Class.forName("Clas name") to create the instance of the Derived class and then type casting to base class.
    Why iam casting to base class is , since only in the run time we are geting the Derived class name.
    Result : iam geting the compiletime error says that no valid method fond in Mybase though it contains the reference of derived.
    abstract class MyBase
    public void display(int i)
    System.out.println(" Base class Method");
    class MyDerived extends MyBase
    public void display(String str)
    System.out.println("Derived class Mthode");
    class MyMain
    public static void main(String arg[])
    String DrivObj=arg[0];
    MyBase baseObj=(MyBase) Class.forName("DrivObj").newInstance();
    baseObj.display("SomeString"); }
    }

    The problem is, can not have subclass reference bcoz
    iam geting the subclass name only in the runtime and
    one more thing is cant touch my base and subclass to
    do changes as u said Your design is then definately very bad.
    , is there any other way to do
    it.Yes, you can use reflection to invoke the method.
    Kaj

  • Force Derived Class to Implement Static Method C#

    So the situation is like, I have few classes, all of which have a standard CRUD methods but static. I want to create a base class which will be inherited so that it can force to implement this CRUD methods. But the problem is, the CRUD methods are static. So
    I'm unable to create virtual methods with static (for obvious reasons). Is there anyway I can implement this without compromising on static.
    Also, the signature of these CRUD methods are similar.
    E.g. ClassA will have CRUD methods with these type of Signatures
    public static List<ClassA> Get()
    public static ClassA Get(int ID)
    public static bool Insert(ClassA objA)
    public static bool Update(int ID)
    public static bool Delete(int ID)
    ClassB will have CRUD signatures like
    public static List<ClassB> Get()
    public static ClassB Get(int ID)
    public static bool Insert(ClassB objB)
    public static bool Update(int ID)
    public static bool Delete(int ID)
    So I want to create a base class with exact similar signature, so that inherited derived methods will implement their own version.
    For E.g. BaseClass will have CRUD methods like
    public virtual static List<BaseClass> Get()
    public virtual static BaseClassGet(int ID)
    public virtual static bool Insert(BaseClass objBase)
    public virtual static bool Update(int ID)
    public virtual static bool Delete(int ID)
    But the problem is I can't use virtual and static due to it's ovbious logic which will fail and have no meaning.
    So is there any way out?
    Also, I have few common variables (constants) which I want to declare in that base class so that I don't need to declare them on each derived class. That's why i can't go with interface also.
    Anything that can be done with Abstract class?

    Hi,
    With static methods, this is absolutely useless.
    Instead, you could use the "Singleton" pattern which restrict a class to have only one instance at a time.
    To implement a class which has the singleton pattern principle, you make a sealed class with a private constructor, and the main instance which is to be accessed is a readonly static member.
    For example :
    sealed class Singleton
    //Some methods
    void Method1() { }
    int Method2() { return 5; }
    //The private constructor
    private Singleton() { }
    //And, most importantly, the only instance to be accessed
    private static readonly _instance = new Singleton();
    //The corresponding property for public access
    public static Instance { get { return _instance; } }
    And then you can access it this way :
    Singleton.Instance.Method1();
    Now, to have a "mold" for this, you could make an interface with the methods you want, and then implement it in a singleton class :
    interface ICRUD<BaseClass>
    List<BaseClass> GetList();
    BaseClass Get(int ID);
    bool Insert(BaseClass objB);
    bool Update(int ID);
    bool Delete(int ID);
    And then an example of singleton class :
    sealed class CRUDClassA : ICRUD<ClassA>
    public List<ClassA> GetList()
    //Make your own impl.
    throw new NotImplementedException();
    public ClassA Get(int ID)
    //Make your own impl.
    throw new NotImplementedException();
    public bool Insert(ClassA objA)
    //Make your own impl.
    throw new NotImplementedException();
    public bool Update(int ID)
    //Make your own impl.
    throw new NotImplementedException();
    public bool Delete(int ID)
    //Make your own impl.
    throw new NotImplementedException();
    private CRUDClassA() { }
    private static readonly _instance = new CRUDClassA();
    public static Instance { get { return _instance; } }
    That should solve your problem, I think...
    Philippe

  • Is it possible to OVERLOAD a super-class method in a sub-class?

    Hi all,
    I have a query that
    Is it possible to OVERLOAD a super-class method in a sub-class?
    If it is possible, please give me an example.
    Thanks,
    Hari

    Hi,
    Is the method int Display(int a){} overloading
    the super-class's void Display() method? If
    possible, please clarify this and how it would be
    method overloading?
    hanks,
    Hari
    Hi Hari,
    Yes, it is possible. Look at this piece of code:
    class Senior
         void Display()
              System.out.println("Super class method");
    class Junior extends Senior
         int Display(int a)
              System.out.println("Subclass method: "+a);
              return(a+10);
         }> }
    class example
         public static void main(String args[])
              Junior j = new Junior();
              j.Display();
    System.out.println("Subclass method
    od "+j.Display(5));
    Is this what you were asking? Hope this helped.Hi,
    I guess you guys are confused here...
    Overloading is achieved by methods in the same class...
    Overriding is across a superclass subclass methds.

  • My derived class suddenly doesn't recognize the parent class

    I had my assignment coded, debugged, working and ready to go. So I bring my flash drive upstairs to play around with it on my other computer. When I compile the base class it compiles fine, but now when I try to compile the derived class, and the test class with the main method, I'm coming up with errors.
    They have something to do with the base class not being recognized, because I can't instantiate any objects of the class now, and i get an error when attempting to compile the derived class to the effect of "cannot find symbol; symbol: class BaseClass". i get this error throughout the derived class, from the initial declaration of the class (public class DerivedClass extends BaseClass), to any references made toward methods of the parent class.
    My base class compiles with no problem, but it's like nothing else is able to "use" it. I'm not sure if it has something to do with the PC im using now, and I can't confirm this at the moment because the PC I used to write the code is down (waiting on an upgrade).
    ehhh.....help.
    Message was edited by:
    asphaltninja
    null

    It's not the fault of the computer hardware.
    It's not the fault of the operating system.
    It's not the fault of the JDK.
    So don't go rebooting or reinstalling anything. The problem is that you didn't set up things on the new computer in the same way they were set up on the old computer.
    In particular the compiling problem is that the compiled version of BaseClass isn't in the classpath when you try to compile DerivedClass. I can't tell why from your description.

  • How to load function from derived class from dll

    Dear all,
    how to access extra function from derived class.
    for Example
    //==========================MyIShape.h
    class CMyIShape
    public:
    CMyIShape(){};
    virtual ~CMyIShape(){};
    virtual void Fn_DrawMe(){};
    // =========== this is ShapRectangle.dll
    //==========================ShapRectangle .h
    #include "MyIShape.h"
    class DLL_API ShapRectangle :public CMyIShape
    public:
    ShapRectangle(){};
    virtual ~ShapRectangle(){};
    virtual void Fn_DrawMe(){/*something here */};
    virtual void Fn_ChangeMe(){/*something here */};
    __declspec (dllexport) CMyIShape* CreateShape()
    // call the constructor of the actual implementation
    CMyIShape * m_Obj = new ShapRectangle();
    // return the created function
    return m_Obj;
    // =========== this is ShapCircle .dll
    //==========================ShapCircle .h
    #include "MyIShape.h"
    class DLL_API ShapCircle :public CMyIShape
    public:
    ShapCircle(){};
    virtual ~ShapCircle(){};
    virtual void Fn_DrawMe(){/*something here */};
    virtual void Fn_GetRadious(){/*something here */};
    __declspec (dllexport) CMyIShape* CreateShape()
    // call the constructor of the actual implementation
    CMyIShape * m_Obj = new ShapCircle();
    // return the created function
    return m_Obj;
    in exe there is no include header of of ShapCircle and ShapRectangle 
    and from the exe i use LoadLibrary and GetProcAddress .
    typedef CMyIShape* (*CREATE_OBJECT) ();
    CMyIShape*xCls ;
    //===================== from ShapeCircle.Dll
    pReg=  (CREATE_OBJECT)GetProcAddress (hInst ,"CreateShape");
    xCls = pReg();
    now xCls give all access of base class. but how to get pointer of funciton Fn_GetRadious() or how to get access.
    thanks in advance.

    could you please tell me in detail. why so. or any reference for it. i love to read.
    i don't know this is bad way.. but how? i would like to know.
    I indicated in the second sentence. Classes can be implemented differently by different compilers. For example, the alignment of member variables may differ. Also there is the pitfall that a class may be allocated within the DLL but deallocated in the client
    code. But the allocation/deallocation algorithms may differ across different compilers, and certainly between DEBUG and RELEASE mode. This means that you must ensure that if the DLL is compiled in Visual Studio 2010 / Debug mode, that the client code is also
    compiled in Visual Studio 2010 / Debug mode. Otherwise your program will be subject to mysterious crashes.
    is there any other way to archive same goal?
    Of course. DLL functionality should be exposed as a set of functions that accept and return POD data types. "POD" means "plain-ole-data" such as long, wchar_t*, bool, etc. Don't pass pointers to classes. 
    Obviously classes can be implemented within the DLL but they should be kept completely contained within the DLL. You might, for example, expose a function to allocate a class internally to the DLL and another function that can be called by the client code
    to free the class. And of course you can define other functions that can be used by the client code to indirectly call the class's methods.
    and why i need to give header file of ShapCircle and shapRectangle class, even i am not using in exe too. i though it is enough to give only MyIShape.h so with this any one can make new object.
    Indeed you don't have to, if you only want to call the public properties and methods that are defined within MyIShape.h.

  • How to call derived class to base class

    Hello everybody,
    I create a GUi application in java swing. Now i want to navigate between the screen but the timing between the screen is very slow bcoz i imported the class from package to another package. Now i want to extends one package to another package to reduce the navigation time but it saying error bcoz i cant able to call my derived class to base class. if anyone know the answer for this please answer this immediately.
    If any other method is there to optimise the navigation time please tell me
    by
    (kamal)

    Sorry, I've got major difficulties understanding your query:
    I create a GUi application in java
    ication in java swing. ok
    Now i want to navigate between
    the screenwhat? switch screens? display a different dialog?
    but the timing between the screen is very
    slowtiming? do you mean the time it takes to display a different dialog?
    bcoz i imported the class from package to
    another package.how did you come to the conclusion that that is the reason for the slowness? Did you do any profiling or is this just guess-work?

  • Set fields of derived class in base class constructor via reflection?

    Does the Java Language Specification explicitly allow setting of fields of a derived class from within the base class' constructor via reflection? The following test case runs green, but I would really like to know if this Java code is compatible among different VM implementations.
    Many thanks for your feedback!
    Norman
    public class DerivedClassReflectionWorksInBaseClassConstructorTest extends TestCase {
    abstract static class A {
        A() {
            try {
                getClass().getDeclaredField("x").setInt(this, 42);
            } catch (Exception e) {
                throw new RuntimeException(e);
    static class B extends A {
        int x;
        B() {
        B(int x) {
            this.x = x;
    public void testThatItWorks() {
        assertEquals(42, new B().x);
        assertEquals(99, new B(99).x);
    }

    why not just put a method in the superclass that the subclasses can call to initialize the subclass member variable?In derived classes (which are plug-ins), clients can use a field annotation which provides some parameter metadata such as validators and the default value. The framework must set the default value of fields, before the class' initializer or constructors are called. If the framework would do this after derived class' initializer or constructors are called, they would be overwritten:
    Framework:
    public abstract class Operator {
        public abstract void initialize();
    }Plug-In:
    public class SomeOperator extends Operator {
        @Parameter(defaultValue="42", interval="[0,100)")
        double threshold;
        @Parameter(defaultValue="C", valueSet="A,B,C")
        String mode;
        public void setThreshold(double threshold) {this.threshold = threshold;}
        public void setMode(String mode) {this.mode = mode;}
        // called by the framework after default values have been set
        public void initialize() {
    }On the other hand, the default values and other metadata are also used to create GUIs and XML I/O for the derived operator class, without having it instantiated. So we cannot use the initial instance field values for that, because we don't have an instance.

  • Base class/Derived class

    Hi all,
    I have
    class Base {
    int a;
    class Derived{
    int b;
    now if i do
    Base X = new Base();
    Derived D = new Derived();
    It Doesn't allow me to do D=X
    But it does allow me to do X=D.
    whats the reason behind it. And what actually happens when i do X=D , does the copy constructor gets called ?
    Thanx

    Manthana wrote:
    Hi, u said
    the value of X becomes the reference to the instance of Derived that you created when you called "new Derived()".
    So now i can access attributes of derived class from the reference X right X.b
    But i cant do X.b
    Why?Please spell out words like "you". It makes things easier to read. :)
    With Derived extending Base, you could say:
    X = D;
    X.a = 5;Because the compiler and runtime see X as a reference to a Base object, you can only access variables/methods defined in Base. Since X is declared as being a reference to Base, you always know that 'a' is defined. 'b' wouldn't be defined for X if you said:
    X = new Base();
    X.b = 52;So, in order to access the b, you'd have to access it with something declared as a reference to Derived, such as 'D':
    D.b = 10;You could say:
    X = D; // Line 1
    Derived d2 = (Derived)X;
    d2.b = 10;But, then you'll get a ClassCastException if X is only referring to a Base object [e.g., if Line 1 was "X = new Base();"], not to a Derived object.

  • Variable in derived class more public

    Hello,
    I thought variables in a derived class could not be more public than the variables they hide (in the base class) e.g. the "var" variable in "DerivedDemo" could not be more public than the "var" variable in Demo. (which would be the opposite to methods) Am I right?
    class Demo {
    private int var;
    class DerivedDemo extends Demo{
    public int var;
    }Thanks in advance,
    Balteo.

    actually, you'll find you get to variables:
    class abc extends z {
         public int k = 20;
         public abc(){
              System.out.println("k from abc: " + k);
         public static void main(String[] args){
              abc z = new abc();
              System.out.println("mm: " + z.k);
              System.out.println("mm: " + z.getK());
              z.test();
    class z {
         private int k = 2;
         public void test(){
              System.out.println("k from z: " + k);
         public int getK(){ return k; }
    };)

  • Flex/AS3 Best way to construct a derived class instance from an existing base class instance?

    What is the best way to handle the instantiation of a derived class from an existing base class.
    I have a base class which is being created via remote_object [RemoteClass alias] from the server.   I have other specialized classes that are derived from this baseclass, but serialization with the server always happens with the base class.     The base class has meta data that defines what the derived class is, for example
    [RemoteClass (alias="com.myco...')]
    public Class Base
         public var derivedType:String;
         public function Base()
    public Class Derived extends Base
         public "some other data"
         public function Derived()
    In my Cairgorm command which retrieves this object from ther server I want to do this:
    public function result (event: Object):void
        var baseInstance:Base = event.result;
         if (baseInstance.derivedType = "derived")
              var derivedInstance:Derived = new Derived( baseInstance );
    What is the most efficient way of doing this?   It appears to me that doing a deep-copy/clone and instantiation of the derived class is pretty inefficient as far as memory allocation and data movement via the copy.

    Thanks for the assistance.  Let me try to clarify.
    MY UI requires a number of composite classes.    The individual components of the composite classes are being transfered to/from the server at different times depending upone which component has changed state.    The construction of the composite classes from the base class happens in my clients business logic.
    Composition happens in a derived class; but server syncronization happens using the base class.    When I recieve the object from Blazeds through the remote object event, it is in the form of the base class.  I then need to instantiate the derived class and copy the elements of the base class into it (for later composite construction).   And likewise when sending the base class back to the server, I need to upcast the derived class to its base class.   But in this case just a mere upcast does not work.  I actually need to create a new base class and copy the attrbutes into it.  I believe this is limitation of how remoting works on Flex/AS3.
    My question is, what is the best way to turn my base class into it's derived class so further composite construction can take place.   The way I am currently doing it is to create a  load method on the base class, that takes the base class as on argument.  The load function, copies all of the instance attribute references from the base class to the target class.
    public Class Base
         public function Base()
         public function load(fromClass:Base)
        {  //  copy the references for all of the instance attributes from the fromClass to this class }
    Then,  after I recieve the base class from the server.   I create a new derived class and pass the base class into the load function like this:
                for (var i:int=0; i < event.result.length; i++) {
                    var derived:Derived = new Derived();
                    derived.load(event.result[i]);
    The drawbacks of this approach is that it now requires 2 extra instance creations per object serialization.   One on recieving the object from the server and one sending it to the server.    I assume copying references are pretty efficient.  But, there is probably some GC issues.     The worst of it is in code maintenance.   The load function now has to be manually maintained and kept in sync with the server class.
    It would be interesting to hear how others have solved this problem.      The server side is an existing application with around 2M LOC, so changing the code on the server is a non-starter.
    Thanks for your help.

  • Derived class also implements interface?

    Hi guys,
    If a base class A implements an interface (e.g. Comparable), does a derived class of A also implement this interface (or is of this type e.g Comparable, if this is a more correct way to say it)??
    If so, would it be wrong to write "public class B extends A implements Comparable", because class A already implements it?
    I am aware of that class B will inherit methods from class B and that way have "compareTo()" method. But can objects of class B be plugged in for method parameter of Comparable ( someMethod(Comparable obj) )?

    LencoTB wrote:
    Hi guys,
    If a base class A implements an interface (e.g. Comparable), does a derived class of A also implement this interface (or is of this type e.g Comparable, if this is a more correct way to say it)??Yes. The way you said it is fine, although another way to say it is "Comparable is a base interface(or class) of derived class B"
    >
    >
    If so, would it be wrong to write "public class B extends A implements Comparable", because class A already implements it?Not necessarily, but it is unnecessary. The only reason you would do this is to specifically document that the class is changing the implementation of compareTo.
    >
    I am aware of that class B will inherit methods from class B and that way have "compareTo()" method. But can objects of class B be plugged in for method parameter of Comparable ( someMethod(Comparable obj) )?use "implements Comparable<B>"

Maybe you are looking for

  • ITunes 9 install issues, now iTunes won't install at all. (Vista 64-bit)

    I tried to upgrade to iTunes 9 today but it failed to install using the auto-update tool, so as the tool suggested, I tried going manual. It installed, but gave me the "iTunes requires a newer version of Apple Mobile Device Support." error every time

  • Settlement of Investment Order - Auto creation of Sub asset for settlement

    < MODERATOR:  Message locked.  Please post this in the [ERP Financials - Asset Accounting|SAP ERP Financials  - Asset Accounting;. > Dear experts Request your help on Investment orders settlement. We are doing settlement of Investment orders to sub a

  • What touch-based API or modules you use for Android?

    I had ported my web-based flex application to android. During porting, I need to code different type of touch-based UI components from ground up. Apparently this is not very efficient and I also need to perform a lot more testing as a result. Do you

  • WAD:  Missing Items in 0ADHOC Web Template

    In the Web Application Designer, when I open the 0ADHOC Web Template, it comes up with several missing items.  Specifically, SAP_BW_TEXT_!llD_119, SAP_BW_TEXT_!llD_129, SAP_BW_TEXT_!llD_132.  Also, for some Web Items the image is missing.  The web it

  • Premiere Pro Crash every time I quit the program

    This has been a constant problem over the last several months. Sometimes it's harmless, but I believe it's leading to corrupt files in certain cases and I'm losing work and time because of it. This is the problem: 1. I working in PP and I save my pro