Virtual methods- abstract methods

Hi, I need to get this clear in my head.
In C++ you had virtual methods()
If a method was virtual this made the enclosing class abstract.
There is no such thing as abstract methods in C++?
In java, if you have an abstract method your enclosing class becomes abstract.
There is no such thing as a virtual method in java.
is all the above correct?
Thanks ... J

Hi, I need to get this clear in my head.
In C++ you had virtual methods()
If a method was virtual this made the enclosing class abstract.
There is no such thing as abstract methods in C++?Incorrect.
Abstract methods have no implementation. You can have those in C++. If I remember correctly, they'd look something like this:
public void foo() = 0;
In java, if you have an abstract method your
enclosing class becomes abstract.
There is no such thing as a virtual method in java.Incorrect.
All methods in Java are virtual by default. Every method is fair game to be overridden by a subclass. You mark them with the final keyword to prohibit overriding.
All methods in C++ are final by default. You can't override any method in a subclass unless you mark it with the virtual keyword. (This was keeping the Bjarne's philosophy of "only pay for what you use".)
%

Similar Messages

  • Token resolution of virtual method in javacard

    Please help me out how to map the token value of virtual method in the case of internal class reference.

    Hi chandufo,
    I'm agree with safamer, context is only an identifier.
    It's structure may be like this:
    context{
    u1 context_id
    u2 package_addr;
    u2 applet_instance_addr;
    ** if context is JCRE context, all above entry may be *0xFF*. Otherwises, context_id is increment
    Switching context can implement PUSH, POP.
    So that, in your structure of FRAME must be included context_id field like this:
    typedef struct frame {
    u1 last_pc;
    u2 *lvars;
    u2 *ostack;
    method_info *mi;
    class_info *ci;
    struct frame *prev;
    u1 context_id;
    } Frame;
    hi @Shane, do you agree with me?
    Edited by: hoaibaotre on Jul 1, 2011 5:26 PM

  • Is every method of java a Virtual method ?

    Hi,
    Is every method of java a Virtual method ? Can any methods be overridden ? Is that making use of double pointer ?
    Edited by: shyam1 on Sep 22, 2010 10:44 PM

    shyam1 wrote:
    jverd wrote:
    shyam1 wrote:
    Hi,
    Is every method of java a Virtual method ?Every non-final, non-private, non-static method can be considered "virtual," although Java doesn't use that term as far as I know.
    Can any methods be overridden ? Every non-final, non-private, non-static method can be overridden. Any method that is private, static, or final, cannot be.
    Is that making use of double pointer ?
    And I am telling you that it is not defined and not relevant.
    >>
    That is not specified, and is an irrelevant implementation detail.i am asking that, to make every method ( non-final, non-private, non-static method) overridable does java is using any concept called double pointer ?
    IT. IS. NOT. DEFINED. An implementation is free to do it however it wants.
    Why do you care? Why do you think it matters?

  • A non abstract child class must implement all pure virtual function of  parent abstract class in c++

    Hi,
    In Indesign SDK there is a class  IActionComponent having two pure virtual functions:
    virtual void
    UpdateActionStates(IActiveContext* ac, IActionStateList *listToUpdateGSysPoint mousePoint = kInvalidMousePoint, IPMUnknown* widget = nil) = 0;
    virtual void
    DoAction(IActiveContext* ac, ActionID actionID, GSysPoint mousePoint = kInvalidMousePoint, IPMUnknown* widget = nil)= 0;
    But, the child class
    class WIDGET_DECL CActionComponent : public IActionComponent
    implements only UpdateActionStates function and not DoAction function.
    There is no compilation error and the code is running fine..HOW
    Can some one please explain me?

    Oops!!! there is a small correction in my C++ program. The JunkMethod is being called from the constructor...like the following code.
    #include <iostream.h>
    #include <stdlib.h>
    class Base
        public:
            Base()
                cout<<"In Base Class constructor..."<<endl;
                JunkMethod();
            void JunkMethod()
                TestAbsFunc();
            virtual void TestAbsFunc()= 0;
    class TestAbstract:public Base
        public:
            TestAbstract()
                cout<<"In Extend Class constructor..."<<endl;
            void TestAbsFunc()
                cout<<"In TestAbsFunc...."<<endl;
    int main()
          TestAbstract test;
          return 0;
    }You can see the change in the constructor of the Base class. JunkMethod is being called, just to bluff the compiler to call the virtual method (so that it won't crib saying that abstract method cannot be called from the constructor). When Java is supporting this functionality without giving any errors, C++ gives errors when you call an abstract method from the constructor or fails to execute when I do some work around like this. Isn't it a drawback of abstract funcationality supported by C++ (I'm not sure if it's a drawback or not)
    Regards,
    Kalyan.

  • 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

  • Redefine static method?

    It seems that I cannot redefine a static method in a subclass in ABAP OO, right?
    Is there a reason for that? Is this like this in other languages as well?

    That's true. You cannot redefine static methods in ABAP OO.
    I can add that a class that defines a public or protected static attribute shares this
    attribute with all its subclasses.
    Overriding static methods is possible for example in Java.
    This simple piece of code illustrates this:
    public class Super {
        public static String getNum(){
            return "I'm super";
         public static void main(String[] args) {
             System.out.println("Super: " + Super.getNum());
             System.out.println("Sub: " + Sub.getNum());
    public class Sub extends Super{
        public static String getNum(){
            return "I'm not";
    The output is:
    Super: I'm super
    Sub: I'm not
    When overriding methods in Java you must remember that an instance method cannot override a static method, and a static method cannot hide an instance method.
    In C# a static member can't be marked as 'override', 'virtual' or 'abstract'. But it it is possible to hide a base class static method in a sub-class by using the keyword 'new':
    public class Super
      public static void myMethod()
    public class Sub: Super
      public new static void myMethod()

  • Access to Class information from a static method

    There does not appear to be anyway to access the Class object from instead a static method.
    e.g. How could I convert the following code so that it works ?
    class test {
    static void printClassName() {
    System.out.println( getClass().getName() );

    The idea was to have a static method that could be
    used to make a lookup based on the classname. Being
    able to access the class name would mean that I would
    not have to reimplement for every subclass !!!!!Hmm.. what are you trying to look up? Some kind of class-specific constant information maybe?
    In general your best bet is to define an abstract method in your parent class for return of the constant value, then define a specific method in each sub-class that overrides it, retrurning the appropriate value.
    Then you're common processing just gets the value with that method.
    Using some kind of lookup on the basis of class name is much clumsier, and more inclined to run time errors. Better to use the built in virtual methods table.
    Another approach is to have the value as a parameter of the constructor of the parent class and use "super(value)" in the child classes to store
    it.

  • Singleton bottleneck with static methods?

    A discussion came up at work today. If a class is created as a Singleton and only provides static methods and only final static data members (just for storing read only info like a connection string), will this create a bottleneck? Someone was suggesting that sharing the Singleton would cause each thread accessing the code to have to obtain the monitor on the class before being able to execute the method. Is this the case? None of the methods are synchronized, but they all perform atomic functionality. Anyone have any input on this?

    Currenlty, it is implemented as a Singleton, part of
    the discussion was moving everything into static
    methods. Aside from that, the question is still
    whether having a single location to run methods from
    will become a bottleneckWho came up with the idea that this would create some sort of bottleneck? Never pay attention to them again.
    Static methods are (slightly) faster than ordinary instance methods because there is no virtual method lookup. The only way there would be some sort of performance implication is if the methods are synchronized. In that case performance will be essentially the same as synchronized instance methods of a singleton.

  • Static Methods, the case of HashMap

        static int hash(Object x) {
            int h = x.hashCode();
            h += ~(h << 9);
            h ^=  (h >>> 14);
            h +=  (h << 4);
            h ^=  (h >>> 10);
            return h;I was cruising the HashMap class. And I noticed right away that all non interface methods were static package methods. Now isn't that bad OOP practice? Right. It breaks the inheritance relationship.
    It means I cannot make a subclass of HashMap and re-write that hash function. Was that intentional?
    on a OOP perspective or
    on a down to earth matter,
    Are static method more performant in speed? Or memory ( i guess yes here)? or what?

    I was cruising the HashMap class. And I noticed right
    away that all non interface methods were static
    package methods. Now isn't that bad OOP practice?
    Right. It breaks the inheritance relationship.
    It means I cannot make a subclass of HashMap and
    re-write that hash function. Was that intentional?If they are package-private, I take it for granted they didn't want application developers to redefine these methods.
    If they are static, they are also preventing themselves (Javasoft) to override them in subclasses that would be included in the JDK.
    I'd say in both cases, that it is intentional, since, at least in the case of the hash function, the intent is to disperse hash results even for low-dispersing custom hash functions, as was explained in another thread in ALT (wasn't it you already? ;-).
    This is maybe questionable, but defendable, that they didn't want any subclass to mess with these "optimizations".
    You can regard this as poor OO practice, but this is no more hampering you that if they had declared the method as private.
    I acknowledge that declaring the method private has the advantage of making explicit that they don't want anyone to override it.
    But by declaring it static package, they ensure no-one can override it, so the other methods in HashMap relying on this method are guaranteed that no subclass can mess with it, but other classes in the same package (say, WeakHashMap, HashSet,...), can call it. all the same
    Are static method more performant in speed? Or memory
    ( i guess yes here)? or what?Static methods are not faster in themselves, but invoking them may be, since they can be "statically" resolved.
    When the calling class is loaded in memory, the callee is loaded too, and the interpreter or JIT or HotSpot is free to inline the static method's body (no indirection).
    Even if it doesn't, invoking the static method implies to moving the program counter or pointer, or whatever, to an adress that has already been resolved once and for all (one indirection),
    whereas invoking a virtual method implies a double indirection, looking up the address in some kind of dynamic table (one per class, determined by the target object's leaf class).
    There are indeed two different bytecodes for these two situations!

  • Does hotspot inline methods ?

    hotspot (in earlier versions only hotspot server) avoids dynamic binding for virtual method calls as long as there is no subclass has been loaded with overriding methods. But does it inline the method calls wherever possible at runtime?
    Lets say, we have a bean Foo with a getName method.
    class Foo {
    private String name;
    public String getName() {
    return name;
    Now as long as there is no subclass of Foo have been loaded hotspot will not use dynamic binding. But when a class does something like
    Foo f = new Foo(); //watch that both the type and runtime type is Foo
    f.getName();
    Will hotspot inline the method call?
    Thanks.

    My understanding is that Hotspot may inline a method. I think that there is a threshold as well as other factors, such as being final, private, etc...... See:
    http://developer.java.sun.com/developer/technicalArticles/Networking/HotSpot/inlining.html
    "Inlining is based on a form of global analysis. Dynamic
    loading significantly complicates inlining, because it
    changes the global relationships in a program. A new
    class may contain new methods that need to be inlined in
    the appropriate places. So the Java HotSpot performance
    engine must be able to dynamically deoptimize (and then
    reoptimize if necessary) previously optimized hot spots,
    even during the execution of the code for the hot spot.
    Without this capability, general inlining cannot be safely
    performed on Java technology-based programs."
    from: http://java.sun.com/products/hotspot/whitepaper.html
    BTW, these were the first two hits when I searched for 'inlining with hotspot' up in the top right corner. This is slightly different, but may be of interest:
    http://forum.java.sun.com/thread.jsp?forum=4&thread=260074
    hth,
    m

  • Overriding Inherited methods

    why cant we override the inherited methods with more secure access modifier (private)..... while if we do the apposite ie override with more non secure access modifiers , java is able to distinguish them and call the appropriate method or pop up the syntax error.. i am not able to understand the concept ... if any one could give a practical example it would helpful to me to understand...

    rajeshrocks25 wrote:
    Hey, correct me i am wrong.
    When we inherit Java loads all the members of the super class and we override or hide them then it simply ignores the superclass members ri8???
    thats what happening in the above code?I strongly suggest rereading the tutorial for Polymorphism or searching Google for alternative explanations for "Java Polymorphism", it doesn't sound like the concept has fully sunk in yet. As for a direct answer, at the bottom of the polymorphism tutorial I linked earlier they mention:
    The Java virtual machine (JVM) calls the appropriate method for the object that is referred to in each variable. It does not call the method that is defined by the variable's type. This behavior is referred to as virtual method invocation and demonstrates an aspect of the important polymorphism features in the Java language.To add, if the object being referred to does not contain the appropriate method, then the JVM will look for an appropriate method in the superclass, and the superclass of the superclass until the appropriate method is found.
    Also to clarify your confusion earlier, if a subclass A extends a class B, then A is considered a B so there is no use in casting A to B. In a more practical sense, imagine a [Boy] extending a [Man]. The [Boy] is of course a [Boy] because that is what we have defined him as. But the [Boy] is also a [Man] because he extends the [Man]. Therefore casting a [Boy] into a [Man] is pointless, because he already is indeed a [Man], just a subclass in the form of a [Boy].
    Furthermore if we declare a [Man] and instantiate him with a [Boy] then invoking a method talk(), [Boy] is inspected for the appropriate method talk(), if it has not been overridden then the JVM will look in [Man] and calls the appropriate method. Alternatively if we declare a [Man] and instantiate him as a [Man] then invoking the method talk(), [Man] is inspected for the appropriate method. It might also be of worth to note the instantiated [Man] cannot be cast into a [Boy], because a [Boy] is a subclass of [Man] and may contain properties or methods undefined by [Man].
    Mel

  • Clarification about Overriding methods

    When i invoke a overridden method from within the base class, it always calls the method present in the derived class.
    Further I'm presenting you a sample code to describe the same.
    Confuse.java
    class Base {
    int i;
    Base() {
    add(1);
    void add(int v) {
    System.out.println("\nBASE() = "+v);
    class Extension extends Base {
    Extension() {
    add(2);
    void add(int v) {
    System.out.println("\nEXTENSION() = "+v);
    public class Confuse {
    public static void main(String[] args) {
    bogo(new Extension());
    static void bogo(Base b) {
    b.add(8);
    OUTPUT :
    EXTENSION() = 1
    EXTENSION() = 2
    EXTENSION() = 8
    Could you please clarify me on the same ?
    Thanks

    Hi Vikas,
    First, note that this forum is devoted to Sun Java Studio Creator IDE. General Java questions can be asked on forums here: http://forum.java.sun.com/
    Second, your code works as designed. Let's see what happens when you call
    new Extension();
    1) constructor method Extension() called
    2) constructor of parent method Base() called
    3) constructor of parent method java.lang.Object() called
    4) virtual methods table is created for newly created object of Extension class
    5) return to Base() method
    6) add(1) is called via virtual methods table; it's Extension.add(1)
    7) return to Extension() method
    8) add(2) is called via virtual methods table; it's Extension.add(2)
    So all is OK. If you call bogo(new Base()), you'll get output BASE()=...
    Thanks, Misha
    (Creator team)

  • Equivelant of "virtual function" from C++ in Java?

    I have a Java class which implements a network protocol. There are certain types of packets that my Java class will handle internally. Then again there are other types of packets my Java class needs to pass on to the Java MIDlet that is running this code (importing the package which implements the network protocol and using the class). In C++ I would make this all one class which has a virtual function OnReceive(). Then the C++ application using the class would provide their own implementation for OnReceive and every packet that my network code didn't know what to do with would be passed on to the new OnReceive. How can I do the same in Java? I would like to be able to create a new project, import my package which has the networking code in it. And code up a method that is specific to the application using the networking package. That way I only code one method to handle the packets that my networking code does not care about. I hope someone understands what I am getting at here, it is not so easy to explain.

    Make your class abstract, define the pure virtual methods you want subclasseses to provide implementation for (using the abstract keyword in their definition) and you should be good.
    public abstract class MyClass {
        public void concreteInitThing() {
            // your code here
        public abstract void specificImplementation();
    public class ConcreteImplementationOfMyClass extends MyClass {
        public void specificImplementation() {
            // Your code here
    }I hope that helped
    Lee

  • When should I use abstract classes and when should I use interfaces?

    Can any body tell me in which scenario we use /we go for Interface and which scenario we go for abstract class, because as per my knowledge what ever thing we can do by using Interface that thing can also done through abstract class i mean to say that the
    behavior of the two class.
    And other thing i also want to know that which concept comes first into the programming abstract class or Interface.
    S.K Nayak

    The main differences between an abstract class and an interface:
    Abstract
    An abstract class can contain actual working code (default functionality), and can have either virtual or abstract method.
    An abstract class must be sub-classed and only the sub-classes can be instantiated. Abstract methods must be implemented in the sub-class. Virtual methods may be overridden in the sub-class (although virtual methods typically contain code, you still may
    need/want to override them). A good use for an abstract class is if you want to implement the majority of the functionality that a class will need, but individual sub-classes may need slightly different additional functioality.
    Interface
    An interface only contains the method signatures (method name and parameters), there is no code and it is not a class.
    An interface must be implemented by a class. An interface is not a class and so it cannot be sub-classed. It can only be implemented by a class. When a class implements an interface, it must have code in it for each method in the interface's definition.
    I have a blog post about interfaces:
    http://geek-goddess-bonnie.blogspot.com/2010/06/program-to-interface.html
    (sorry, I have no blog posts specific to abstract classes)
    ~~Bonnie DeWitt [C# MVP]
    http://geek-goddess-bonnie.blogspot.com

  • Virtual class vs. interface

    hi,
    i want to know the difference between virtual clas and interface ? I know that in Java we have virtual methods.but is there any virtual class kind of concept(like C++)?

    1) don't post beginner question in the Java Programming forum. There's a {forum:id=921} forum for that purpose.
    2) You should start by reading the Java tutorial; see for example this section: http://download.oracle.com/javase/tutorial/java/javaOO/index.html
    is there any virtual class kind of concept3) Yes there is, those are called abstract classes
    EDIT: should have closed my big gob, it looks like C++ virtual base classes are a specific construct meant for multiple inheritance. So no, Java hasn't this concept. But given the confusion of terms, as pointed out by ejp, I thought you meant classes which do allow "pure virtual methods", for which Java's closest equivalent are, definitely, astract classes .
    EDIT: well, Java also has interfaces , which only allow declaring abstract (pure virtual) methods, so my reply is getting all the more fuzzy...
    Going ejp's way now, can you rephrase the question, with a more accurate wording?
    Regards,
    J.
    Edited by: jduprez on May 13, 2011 9:58 AM
    Oops, corrected link to NTJ forum

Maybe you are looking for

  • How can I add a website to a 'block' list so that Mozilla will not display it as a selection in a Google search?

    I search for images with no filtering using Google and receive a bunch of sites that are known for installing Trojans or other malware. One of them ends with brstsecond.net. 'brstsecond" seems to be bad in any web address. In fact, any website with m

  • How to combine records using function

    Hi, all I have an oracle 10g running on a RH linux e3 server. I have two tables like this: CREATE TABLE "IMMUNODATA"."DEMOGRAPHICS" ( "SUBJECTID" INTEGER NOT NULL, "WORKID" INTEGER, "OMRFHISTORYNUMBER" INTEGER, "OTHERID" INTEGER, "BARCODE" INTEGER, "

  • Multiple R/3 clients to one BI System

    Hello, 1.We have two R/3 clients 010 and 020. Client 010 will be used for devotement and configuration, and client 020 will be used for unit testing. All the dataSources creation and enchantments will be done in 010 and then tested in client 020. 2.C

  • Help! cant hear audio for .mpg's all of a sudden??!?!

    the video plays, but no audio. ive tried multiple files, wmv's and avi's work fine. but the audio isnt playing for .mpg files in qt?!?!? HELP!

  • IMac RAM issue...

    I purchased my iMac about a month ago, and decided to just start out with 1 GB of ram. I wanted to monitor how much of that RAM I was using, so I got a widget that tells me how much free RAM I currently have. My knowledge of RAM is pretty limited, bu