Abstract class methods

I'm confused. Is this true or false.
The great thing about polymorphism is that you can call one method. If the subclass inherited that method, it will be customized and perform a different duty. That way, the action it performs will depend on 1>whether or not it's a sub or super class and also 2>if the method was overridden if it was a subclass.
Now, my confusion. If an object reference is to a Super-abstract-class... how do the method calls and properties go?? well let me let you answer for me. Thanks so much in advance for this clarification.

Yes. You are - pretty much.
The abstract class, as such, can never be instantiated. BUT a class derived from the superclass IS an instance of the superclass.
Silly example:
abstract public class Animal {
   public Animal() {
   public abstract int getNumberOfLegs();
}That's our animal class, and we know that anything that's an animal has a number of legs - but we can't just create a "generic" animal.
public class Cat extends Animal {
   public Cat() {
      super();
   public int getNumberOfLegs() {
      return legCount;
   public void maim(int legsToRemove) {
      legCount -= legsToRemove;
      if(legCount < 0 ) legCount = 0;
   private int legCount = 4;
}A Cat is a specific type of animal, so we can find out how many legs it has (usually 4). Note again that a cat IS an animal, so Cat IS an instance of Animal.
Java even provides a special operator to test this:
Cat cat = new Cat();
System.out.println("A cat is a cat: " + (cat instanceof Cat));
System.out.println("A cat is an animal: " + (cat instanceof Animal));The term used to describe the "Guarantee" that a subclass of an abstract class (or an implementation of an interface) is usually and technically a "contract", but I prefer to think of it as a "Promise" since you can break the promise by messing with the bytecode - at which point the JVM will spot the lie and complain !
D.

Similar Messages

  • Abstract class/ method calls

    Hi, in an
    abstract class Report
    private int mat
    private string add
    private int mat
    private double creduced = 0.125;
    private double sreduced = 0.25;
    public Property(String location, int material)
    add = location;
    mat = material;
    public double getActualPrice()
    double base = getPrice();
    double money = base;
    if (mat == 1)
    money -= base * creduced;
    return money;
    etc and two abstract classes called getPrice() , and getInsurance()- which i have both coded in the extended class
    in a class called "class Info extends Report" I want to use the getActualPrice() method since it will anyway cause of inheritence but i want to add a new if line to it. How do I do this and code it in the extended class?
    Can i super call the instance variables and local variables ? I have tried super calls on the instance variables but since none of them are included in any of the constructors it wont work.

    public double getActualPrice()
    double actual=super.getActuelPrice();
    if ( something )
       actual=dosomethingwith(actual){
    return actual;
    }

  • Abstract class method returning unknown class

    Hi
    I have created an abstract class having one of the method returning an object of a class which is not present at the compiletime. surprisingly the compiler didn't check the availability of the returning class at compilation time. it gave exception of classnotfound when I tried to rum it.
    is there any explanation of it??

    Thanks for the replay. I got the reason.
    actually evenif I did not compile to class file, but I have kept my java file in the same directory. while compiling the abstract class the compiler automatically compiled the reffered class and generated the required class file.
    I got the error when I moved the java file to another dir
    the code is like
    <code>
    abstract class AbstractTest{
         CompleteClass method1(){
              System.out.println("inside method1 of abstract class");
              return new CompleteClass();
         ExtraClass method2(){
                   System.out.println("inside method2 of abstract class");
                   return new ExtraClass(); // this class was not compiled before
         } // only java file is there in the dir
         abstract void demoMethod();
    </code>

  • Abstract class method polymorphically using constructors?

    how can i have a method defined in an abstract superclass call a constructor of the actual class running the method?
    abstract class A {
    public List getMultple() {
    List l = new ArrayList();
    for (short i=0;i<4;i++) {
    l.add(this());//<obviously this breaks
    return l
    or something like that. A won't run this method, but its children will...and they can call their constructors, but what do i put here to do that?
    i've tried a call back. an abstract method getOne() in the superclass forces each child to define that method and in each of those i return the results of a constructor. that works fine.
    the problem is i want to abstract this method out of each of these children classes cause its the exact same in each one, just using a different constructor to get multiple of each in a list. so if i use this callback method, then i am not saving the number of methods in each class, so why bother at all?
    any ideas?

    I still say you are coming at it from the wrong angle. A super class is not the way to go. What you are doing sounds like something very similar to something I did not too long ago.
    My requirement was that I had tab delimited text files filed with data that I had to parse. Each line would be used to instantiate one object, so a particular file could be used to instantiate, for example, a thousand objects of the same class. There were different types of files corresponding to different classes to instantiate instances of.
    Here is the design I ended up using.
    An object of class DataTextFileReader is instantiated to parse the text file and generate objects. It includes code for going line by line, handling bad lines and generating objects and reports. The constructor:
    public DataTextFileReader(File inputFile, LineParser<T> theLineParser)LineParser is an interface with one method:
    public T read(String line);When you call a load() method of the DataTextFileReader, it does its thing with the aid of the LineParser's read method, to which each line is passed, and stores the generated objects in an ArrayList. This can be returned by using another method. There are other methods for getting the reports, etc.
    Obviously, the LineParser chosen needs to have code appropriate for parsing the lines in question, so you have to choose and instantiate the right one.
    I find this design to work well. I arrived at it after spending hours giving myself headaches trying to come up with a design where there was a superclass roughly equivalent to the DataTextFileReader mentioned above, and classes extending this that fulfilled the duty of the LineParsers mentioned above... rather like what you are trying to do now.
    I did not care for the solution at first because it did not give me the "Ah, I am clever!" sensation I was expecting when I finally cracked the problem using inheritance, but I quickly came to think that it was much better OOD anyway.
    The LineParsers mentioned above are essentially embodiments of the Factory pattern, and I would recommend you do something similar in your case. Obviously your "constructors" all have to be different, so you should make a separate class for each of those. Then you can put the code that performs the query and loops to create loads of objects in another class called something like DatabaseDepopulator, using appropriate generics as in my example. Really it is the same problem, now that I look at it.
    This will also result in better separation of concepts, if you ask me. Why should the class constructor know how to parse a database result query, much less perform the query? It has nothing to do with databases (I presume). That is the job of an interpreter object.
    As a final note, remember... 95% of the time you feel like the language won't let you do what you want, it is because you shouldn't anyway.
    Drake

  • Using Abstract Class Methods

    I just want to know that in how many ways can we use the non abstract methods of the class without extending the class(dont want to implement all abstract methods of the parent class).One way is that if the methods are static then we can use CLASSNAME.METHODNAME().Is their any other way of doing it

    none at all. not a single one. by definition, a non-static method has to be invoked on a particular instance of a class, and an abstract class cannot be instantiated. somebody is probably going to say you can do this:
    abstract class AbstractClass {
      abstract void minceAbout();
      void talkRubbish() {
         // do stuff
    new AbstractClass() {
        void minceAbout() {}
    }.talkRubbish();but that is extending the AbstractClass, no matter what their argument. why d'you ask, anyway? why not implement the methods? sounds like a design smell

  • What are abstract classes/methods and what are they for?

    Hi,
    I've just heard about abstract classes and methods and I'm just wondering what exactly they're used for, and why are they there for the Graphics class for example?
    Cheers.

    raggy wrote:
    bastones_ wrote:
    Hi,
    I've just heard about abstract classes and methods and I'm just wondering what exactly they're used for, and why are they there for the Graphics class for example?
    Cheers.Hey bro, I'll try to solve your problemYou have to know two important concepts for this part. 1 is Abstract classes and the other is Interface classes. Depends on the nature of the project, you need to set certain level of standards and rules that the other developers must follow. This is where Abstract classes and Interface classes come into picture.
    Abstract classes are usually used on small time projects, where it can have code implementation like general classes and also declare Abstract methods (empty methods that require implementation from the sub-classes).Wrong, they are used equally among big and small projects alike.
    Here are the rules of an Abstract class and method:
    1. Abstract classes cannot be instantiatedRight.
    2. Abstract class can extend an abstract class and implement several interface classesRight, but the same is true for non-abstract classes, so nothing special here.
    3. Abstract class cannot extend a general class or an interfaceWrong. Abstract classes can extend non-abstract ones. Best example: Object is non-abstract. How would you write an abstract class that doesn't extend Object (directly or indirectly)?
    4. If a class contains Abstract method, the class has to be declared Abstract classRight.
    5. An Abstract class may or may not contain an Abstract methodRight, and an important point to realize. A class need not have abstract methods to be an abstract class, although usually it will.
    6. Abstract method should not have any code implementations, the sub-classes must override it (sub-class must give the code implementations). An abstract method must not have any implementation code code. It's more than a suggestion.
    7. If a sub-class of an Abstract class does not override the Abstract methods of its super-class, than the sub-class should be declared Abstract also.This follows from point 4.
    9. Abstract classes can only be declared with public and default access modifiers.That's the same for abstract and non-abstract classes.

  • Abstract Class and polymorphism - class diagram

    Hi,
    ]Im trying to draw a class diagram for my overall system but im not too sure how to deal with classes derived from abstract classes. I'll explain my problem using the classic shape inheritance senario...
    myClass has a member of type Shape, but when the program is running shape gets instantiated to a circle, square or triangle for example -
    Shape s = new circle();
    since they are shapes. But at no stage is the class Shape instantiated.
    I then call things like s.Area();
    On my class diagram should there be any lines going from myClass directly to circle or triangle, or should a line just be joining myClass to Shape class?
    BTW - is s.Area() polymorphism?
    Thanks,
    Conor.

    Sorry, my drawing did not display very well.
    If you have MyClass, and it has a class variable of type Shape, and the class is responsible for creating MyClass, use Composition on your UML diagram to link Shape and MyClass.
    If you have MyClass, and it has a class variable of type Shape, and the class is created elsewhere, use Aggregation on your UML diagram to link Shape and MyClass.
    If you have MyClass, and it is used in method signatures, but it is not a class variable, use Depedency on your UML diagram to link Shape and MyClass. The arrow will point to Shape.
    Shape and instances of Circle, Triangle, Square, etc. will be linked using a Generalization on your UML diagram. The arrow will always point to Shape.
    Anything that is abstract (class, method, variable, etc.) should be italicized. Concrete items (same list) should be formatted normally.
    BTW, the distinction between Composition, Aggregation and Dependency will vary from project to project or class to class. It's a gray area. Just be consistent or follow whatever guidelines have been established.
    - Saish

  • From abstract class to public class

    I am developing a editor base application...wondering that how to cancel the abstract class and put all the abstract class methods into the public class..?? thanks

    Is this a C++ question? If so, you should post it in the C++ forum. If it is a Java question, post in the Java forum.
    In either case, please make your question more specific. It sounds like all you have to do is copy the functions from the abstract class to the derived class, remove the dependency on the abstract class, and delete the abstract class from the source code. Presumably that is not what you are asking.

  • Abstract class with set and get methods

    hi
    how to write set and get methods(plain methods) in an abstartc class
    ex: setUsername(String)
    String getUsername()
    and one class is extending this abstract class and same methods existing in that sub class also..... how to write......plz provide some ideas
    am new to programming....
    asap
    thnx in advance

    yes... as i told u.... i am new to coding......
    and my problem is ..... i have 2 classes one is abstract class without abstract methods.. and another class is extending abstract class.....
    in abstract class i have 2 methods...one is setusername(string) and getusername() ..... how to write these two methods.... in abstract class i have private variables username...... when user logins ..... i need to catch the user name and i need to validate with my oracle database and i need to identify the role of that user and based on role of that user i need to direct him to appropriate jsp page.......
    for that now i am writing business process classes..... the above mentioned two classes are from business process.....
    could u help me now
    thnx in advance

  • Calling a super.ssuper.method but your super is a abstract class.

    Dear guys,
    Is that possible to invoke your super's super's method but your super is a abstract class?
    like:
    class GO {   public void draw() { } }
    abstract class GORunner extends GO {}
    class GOCounter extends GORunner {
    public void draw() {
    super.super.draw();
    I want to do this because I would like to take advantages of the abstract as an layer to achieve some polymorphism programming Therefore, in the later stage of the programming some code may only refer to GORunner but actually it is holding a GOCounter object.
    Thank!!

    BTW you don't need to write this
    public void draw() {
       super.draw();
    }It works but its basically the same as not having it at all.

  • Calling a method from an abstract class in a seperate class

    I am trying to call the getID() method from the Chat class in the getIDs() method in the Outputter class. I would usually instantiate with a normal class but I know you cant instantiate the method when using abstract classes. I've been going over and over my theory and have just become more confused??
    Package Chatroom
    public abstract class Chat
       private String id;
       public String getID()
          return id;
       protected void setId(String s)
          id = s;
       public abstract void sendMessageToUser(String msg);
    Package Chatroom
    public class Outputter
    public String[] getIDs()
         // This is where I get confused. I know you can't instantiate the object like:
            Chat users=new Chat();
            users.getID();
    I have the two classes in the package and you need to that to be able to use a class' methods in another class.
    Please help me :(                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    I have just looked over my program and realised my class names are not the most discriptive, so I have renamed them to give you a clearer picture.
    package Chatroom
    public abstract class Chatter
    private String id;
    public String getID()
    return id;
    protected void setId(String s)
    id = s;
    I am trying to slowly build a chatroom on my own. The Chatter class is a class that will be used to represent a single logged in user and the user is given an ID when he logs in through the setId and getID() methods.
    package Chatroom;
    import java.util.Vector;
    public class Broadcaster
    private Vector<Chatter> chatters = new Vector<Chatter>();
    public String[] getIDs()
    // code here
    The Broadcaster class will keep a list of all logged-in users keeps a list of all the chats representing logged-in users, which it stores in a Vector.I am trying to use the getIDs() method to return an array of Strings comprising the IDs of all logged-in users, which is why im trying to use the getID() method from the Chat class.
    I apologise if I come across as clueless, it's just I have been going through books for about 4 hours now and I have just totally lossed all my bearings

  • Abstract method called in an abstract class

    Hello,
    I am writing some code that I'd like to be as generic as possible.
    I created an abstract class called Chromozome. This abstract class has a protected abstract method called initialize().
    I also created an abstract class called Algorithm which contains a protected ArrayList<Chromozome>.
    I would like to create a non abstract method (called initializePopulation()) which would create instances of Chromozome, call their method initialize() and full the ArrayList with them.
    In a practical matter, only subclass of Algorithm will be used, using an ArrayList of a subclass of Chromozome implementing their own version of initialize.
    I have been thinking of that and concluded it was impossible to do. But I'd like to ask more talented peaple before forgetting it !
    Thanks,
    Vincent

    Ok, let's it is not impossible, juste that I had no idea of how doing it :-)
    The difficulty is that Algorithm will never have to deal with Chromozome itself, but always with subclass of Chromozome. This is usually not an issue, but in that case, Algorithm is required to create instances of the desired subclass of Chromozome, but without knowing in advance wich subclass will be used (I hope what I say makes any sense).
    Actually I may have found a way in the meantime, but maybe not the best one.
    I created in Algorithm an abstract method :
    protected abstract Chromozome createChromozome()The method initializePopulation will call createChromozome instead of calling directly the constructor and the initialize() method of Chromozome.
    Then subclass of Algorithm will implement the method createChromozome using the desired subclass of Chromozome.

  • Casting & abstract class & final method

    what is casting abstract class & final method  in ABAP Objects  give   some scenario where  actually  use these.

    Hi Sri,
    I'm not sure we can be any more clear.
    An Abstract class can not be instantiated. It can only be used as the superclass for it's subclasses. In other words it <b>can only be inherited</b>.
    A Final class cannot be the superclass for a subclass. In other words <b>it cannot be inherited.</b>
    I recommend the book <a href="http://www.sappress.com/product.cfm?account=&product=H1934">ABAP Objects: ABAP Programming in SAP NetWeaver</a>
    Cheers
    Graham

  • 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

  • "Abstract" method in a non-abstract class

    Hi all.
    I have a class "SuperClass" from which other class are extended...
    I'd like to "force" some methods (method1(), method2, ...) to be implemented in the inherited classes.
    I know I can accomplish this just implementing the superclass method body in order to throw an exception when it's directly called:
    void method1(){
    throw new UnsupportedOperationException();
    }...but I was wondering if there's another (better) way...
    It's like I would like to declare some abstract methods in a non-abstract class...
    Any ideas?

    The superclass just models the information held by
    the subclasses.
    The information is taken from the database, by
    accessing the proper table (one for each subclass).??
    What do you mean by "models the information"?
    You should use inheritance (of implementation) only when the class satisfies the following criteria:
    1) "Is a special kind of," not "is a role played by a";
    2) Never needs to transmute to be an object in some other class;
    3) Extends rather than overrides or nullifies superclass;
    4) Does not subclass what is merely a utility class (useful functionality you'd like to reuse); and
    5) Within PD: expresses special kinds of roles, transactions, or things.
    Why are you trying to force these mystery methodsfrom the superclass?
    It's not mandatory for me to do it... I 'd see it
    just like a further way to check that the subclasses
    implements these methods, as they have to do.That's not a good idea. If the superclass has no relation to the database, it shouldn't contain methods (abstract or otherwise) related to database transactions.
    The subclasses are the classes that handle db
    transaction.
    They are designed as a binding to a db table.And how is the superclass designed to handle db transactions? My guess (based on your description) is that it isn't. That should tell you right away that the subclasses should not extend your superclass.

Maybe you are looking for

  • Itunes folder shared when tried to download 7.4.1

    I received a dialogue box to update my iTunes last night. While it was uploading, it showed that my music files were being shared with someone I do not know, and I cannot remove the shared folder because I obviously do not have their password. I was

  • MacBook 2nd Monitor

    Hello, I have a White 13" MacBook 2Ghz, 2GB RAM, Intel Core Duo running 10.5.7 Under normal conditions, the fans run at approximately 1700 - 2000 rpm. As soon as I connect an external Monitor via the Mini DVI port (mini DVI to adaptor) the fans ramp

  • Sound just stopped working!

    Ok, so I opened imovie 08 today for the first time on my macbook pro today. I imported about 6 movies, and went to work on editing them, which was i pain because i was used to the last version, I worked for nearly 2 hours, finished the quick project

  • Apple TV 3rd Gen - iTunes Movies Not Showing Up???

    I have Apple TV 3rd Gen (latest) but for some reason my previously purchased itunes movies are not showing up anywhere on the system.  The content was purchased on my previous Apple TV 1 and stored in a connected itunes library via my iMac.  The TV s

  • "Blocked Plug-In."  What to do?

    Got a message saying Adobe Flash Player needs updating.  When I tried to activate the process, I got a message that says "Blocked Plug-In."  What is this and what can i do?  Many thanks.