Mixing polymorphism with abstract classes???

Hi,
Can you have polymorhism with abstract superclasses in Java?
For example, say I have a superclass called Pet:
abstract class Pet {
     private String name;
     public String getName() {
          return name;
    public void setName(String petName) {
         name = petName;
    public String speak() {
         return "I am a Pet";
}Now I have a Cat subclass:
public class Cat extends Pet{
    public String speak {
         return "i am a cat";
public class Dog extends Pet {
public String fetch() {
     return "fetching a stick";
}In my test method I have:
public class TestPet {
     public static void main(String[] args) {
          Pet p = new Pet();
          System.out.println(p.speak());
          Pet p = new Dog();
          System.out.println(((Dog)p).fetch());
          Pet p = new Cat();
          System.out.println(p.speak() +" is now a cat");
}So it appears to me that you cannot have polymorphic methods with an abstract superclass - is this right?
Cheers.

cotton.m wrote:
List<Pet> pets = new ArrayList<Pet>();
I was working (more or less) along the same lines...
package forums;
import java.util.List;
import java.util.ArrayList;
abstract class Pet
  private String name;
  public String getName() { return this.name; }
  public void setName(String name) { this.name = name; }
  public String speak() {
    return "I am a Pet";
  public abstract String fetch(); // <<<<< the new bit.
  public String getClassName() {
    final String name = this.getClass().getName();
    return name.substring(name.lastIndexOf('.')+1).toLowerCase();
class Cat extends Pet
  public Cat(String name) {
    setName(name);
  public String speak() {
    return "I am a cat";
  public String fetch() {
    return "No. I am a cat!";
  public String rollOver() {
    return "No. I am a cat!";
class Dog extends Pet
  public Dog(String name) {
    setName(name);
  public String fetch() {
    return "Look boss, I'm fetching the stick.";
  public String sit() {
    return "Look boss, I'm sitting!";
public class PetTest
  public static void main(String[] args) {
    List<Pet> pets = new ArrayList<Pet>();
    pets.add(new Cat("Fungus"));
    pets.add(new Dog("Spike"));
    for ( Pet pet : pets ) {
      System.out.println("\""+pet.speak()+"\" said "+pet.getName()+" the "+pet.getClassName()+".");
      System.out.println("\"Go fetch\" said the master.");
      System.out.println("\""+pet.fetch()+"\" said "+pet.getName()+".");
      System.out.println();
    System.out.println("Therefore we conclude that dogs are much better pets.");
}Both these examples demonstrate that polymorphism is very useful when we have a list of different-type-if-things which have a common interface... i.e. different classes which have (a) a common ancestor; or (b) a common interface... allowing us to treat those different types-of-things as if they where one-type-of-thing, except the-different-types actually do different stuff internally, which is appropriate-to-there-specific-type.
That's the essence of polymorphism... and, of course, this seperation of "type" and "implementation" isn't limited to lists-of-stuff... it can be very useful all over the show.
Cheers. Keith.
Edited by: corlettk on 10/05/2009 11:01 ~~ That's a bit clearer.

Similar Messages

  • Problems with abstract classes

    I'm reading Java Wireless Blueprints and i'm confused with the functionality of abstract classes, especially in the next section:
    public byte[] getPoster() throws ApplicationException {
    if (poster == null) {
    try {
    poster =
    ModelObjectLoader.getInstance().getMoviePoster(primaryKey);
    } catch (ModelException me) {
    throw new ApplicationException();
    return poster;
    This class invoque to the ModelObjectLoader class that is abstract and after invoque getInstance().getMoviePoster(primaryKey); method. The source code of the class is:
    public abstract class ModelObjectLoader {
    private static ModelObjectLoader instance = null;
    protected ModelObjectLoader() {
    instance = this;
    return;
    public static ModelObjectLoader getInstance() {
    return instance;
    public abstract TheaterSchedule getTheaterSchedule(Theater theater)
    throws ModelException, ApplicationException;
    public abstract Movie getMovie(String movieKey)
    throws ModelException, ApplicationException;
    public abstract Movie getMovie(Movie movie)
    throws ModelException, ApplicationException;
    public abstract byte[] getMoviePoster(String movieKey)
    throws ModelException, ApplicationException;
    public abstract int[][] getMovieShowTimes(String theaterKey, String movieKey)
    throws ModelException, ApplicationException;
    public abstract SeatingPlan getSeatingPlan(String theaterKey,
    String movieKey,
    int[] showTime) throws ModelException,
    ApplicationException;
    I don�t find where is the implementation of the getMoviePoster(primaryKey) method.
    Can you help me to understand.
    Thanks

    public abstract byte[] getMoviePoster(String movieKey)It's an abstract method, which means that any concrete class that extends ModelObjectLoader must implement the method. If you really need to know (you might not), then call getInstance() and output the result of getClass().getName() on that object. That will tell you its type, and then you can go look at the source.

  • Dealing with abstract classes and interfaces with XMLBeans

    I'm quite new to XMLBeans and would like some help. I've got things working when
    you are only saving concreate classes as XML, but when it comes to clesses containing
    interfaces I am running into problems.
    I basically have a collection of XY objects (see below) that I want to save as
    XML.
    I want to convert the following java classes to an xml schema:
    public class XY{
    X x;
    Y y;
    public interface X{
    void setA(int a);
    int getA();
    public interface Y{
    void setB(int b);
    int getB();
    public class X1 implements X{
    void setA(int a);
    int getA();
    //other data to save
    public class X2 implements X{
    void setA(int a);
    int getA();
    //other data to save
    public class Y1 implements Y{
    void setB(int b);
    int getB();
    //other data to save
    public class Y2 implements Y{
    void setB(int b);
    int getB();
    //other data to save
    What would be the best way to convert these to XML Schema? I've looked through
    all the XMLBeans documentation, but it doesn't say anything about dealing with
    interfaces/abstract classes. Is there anywhere else to look?
    Thanks in advance,
    Andrew

    Anurag,
    What I really wanted was a work-around to using substiutionGroups as substitution
    groups are not supported in this release.
    I want to convert the following schema:
    <xsd:complexType name="PublicationType">
    <xsd:sequence>
    <xsd:element name="Title" type="xsd:string"/>
    <xsd:element name="Author" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/>
    <xsd:element name="Date" type="xsd:gYear"/>
    </xsd:sequence>
    </xsd:complexType>
    <xsd:complexType name="BookType">
    <xsd:complexContent>
    <xsd:extension base="PublicationType" >
    <xsd:sequence>
    <xsd:element name="ISBN" type="xsd:string"/>
    <xsd:element name="Publisher" type="xsd:string"/>
    </xsd:sequence>
    </xsd:extension>
    </xsd:complexContent>
    </xsd:complexType>
    <xsd:complexType name="MagazineType">
    <xsd:complexContent>
    <xsd:restriction base="PublicationType">
    <xsd:sequence>
    <xsd:element name="Title" type="xsd:string"/>
    <xsd:element name="Date" type="xsd:gYear"/>
    </xsd:sequence>
    </xsd:restriction>
    </xsd:complexContent>
    </xsd:complexType>
    <xsd:element name="Publication" type="PublicationType"/>
    <xsd:element name="Book" substitutionGroup="Publication" type="BookType"/>
    <xsd:element name="Magazine" substitutionGroup="Publication" type="MagazineType"/>
    <xsd:element name="BookStore">
    <xsd:complexType>
    <xsd:sequence>
    <xsd:element ref="Publication" maxOccurs="unbounded"/>
    </xsd:sequence>
    </xsd:complexType>
    </xsd:element>
    to produce an XML file like:
    <?xml version="1.0"?>
    <BookStore ¡Ä>
    <Book>
    <Title>Illusions: The Adventures of a Reluctant Messiah</Title>
    <Author>Richard Bach</Author>
    <Date>1977</Date>
    <ISBN>0-440-34319-4</ISBN>
    <Publisher>Dell Publishing Co.</Publisher>
    </Book>
    <Magazine>
    <Title>Natural Health</Title>
    <Date>1999</Date>
    </Magazine>
    <Book>
    <Title>The First and Last Freedom</Title>
    <Author>J. Krishnamurti</Author>
    <Date>1954</Date>
    <ISBN>0-06-064831-7</ISBN>
    <Publisher>Harper & Row</Publisher>
    </Book>
    </BookStore>
    What is the best way to do this without using substitution types?
    Thanks,
    Andrew
    "Anurag" <[email protected]> wrote:
    Andrew,
    Could you please paste/attach a sample of the code you are using to convert
    Java bean classes to XMLBeans?
    In the current release the goal of XMLBeans technology was to convert
    from
    XML Schemas or XML files to XMLBeans. The focus was not towards conversion
    of Java beans to XMLBeans.
    Regards,
    Anurag
    "Andrew" <[email protected]> wrote in message news:[email protected]...
    I'm quite new to XMLBeans and would like some help. I've got thingsworking when
    you are only saving concreate classes as XML, but when it comes toclesses
    containing
    interfaces I am running into problems.
    I basically have a collection of XY objects (see below) that I wantto
    save as
    XML.
    I want to convert the following java classes to an xml schema:
    public class XY{
    X x;
    Y y;
    public interface X{
    void setA(int a);
    int getA();
    public interface Y{
    void setB(int b);
    int getB();
    public class X1 implements X{
    void setA(int a);
    int getA();
    //other data to save
    public class X2 implements X{
    void setA(int a);
    int getA();
    //other data to save
    public class Y1 implements Y{
    void setB(int b);
    int getB();
    //other data to save
    public class Y2 implements Y{
    void setB(int b);
    int getB();
    //other data to save
    What would be the best way to convert these to XML Schema? I've lookedthrough
    all the XMLBeans documentation, but it doesn't say anything about dealingwith
    interfaces/abstract classes. Is there anywhere else to look?
    Thanks in advance,
    Andrew

  • Help with abstract classes

    Hi All,
    1. I would like to know if an abstract class can contain a main method?
    2.I have a class called KeyTest which is a junit test class and it contains 2 methods called testSymKey() and testAsymKey() which bascially tests for symmetric key generation and assymmetric key generation. My manager has asked me to create an abstract test class for this class and define the methods in the abstract class and then make a subclass of this abstact class. I am not sure how this can be done!! Any help is appreciated.Here is what i have till now
    public class KeyTest extends TestCase implements CSFConstants
    public static void main(String[] args) throws Exception
    junit.textui.TestRunner.run(suite());
    protected void setUp() {
    public static Test suite()
    return(new TestSuite(KeyTest.class));
    public void testSymKey() throws CSFException
    CSFISymKey loSymKey = CSFManager.getInstance().getSymKey();
    loSymKey.init();
    loSymKey.generate();
    assertTrue(loSymKey.save() != null);
    public void testASymKey() throws CSFException
    CSFIAsymKey loAsymKey = CSFManager.getInstance().getAsymKey();
    loAsymKey.init();
    loAsymKey.generate();
    assertTrue(loAsymKey.getPublicKey().toString() != null);
    assertTrue(loAsymKey.getPrivateKey().toString() != null);

    If a class has one or more abstract methods (including if it claims to implement an interface but doesn't provide an implementation for one or more of the interface's methods, which are all implicitly abstract), then the class must be declared abstract.
    However, the converse is not true. An abstract class can have all abstract methods, a mix of abstract and concrete methods, all concrete methods, or no methods at all. You can take any class you want and declare it abstract. (Of course, if you do, any code that does new ThatClass(); will now not compile.)

  • Using common methods with abstract classes

    hello everyone, i wanted to know if it is bad practice (i imagine it is) to place methods which will be used by multiple classes (computational methods) in an abstract class and mark them as static. When i do this they are always project wide utility classes which dont need an instantiation. When using any of these methods which are common to a project i can then just use..
    Type result = ClassName.DoStaticMethod(...);Thanks for any input,
    Dori
    Edited by: Sir_Dori on Dec 8, 2008 2:01 AM

    Depends on what the methods are meant to do, but I wouldn't make the class abstract. I would instead declare it to be final and have a private constructor.
    Kaj
    Ps. Take a look at the java.lang.Match class.

  • Polymorphism and abstract classes

    DYNAMIC BINDING
    I am writing a JAVA(SWING/GUI) program that recognises certain commands.Users will enter command and the program executes the command.I want to be able to add commands in future.I have been able to do it with IF/ELSE statements and would like to do it using polymorhism so as to allow dynamic binding.Part of the code is shown below
    I am open to any suggestions
    private class commandhandler implements ActionListener
    { public void actionPerformed(ActionEvent event)
    for(int start=0;start<end;start++)
    { String read=label2.getText();
    COMMAND (OpCode,Operand);
    public void COMMAND(String COM1,String COM2)
    { if(COM1.equals("01"))
    { String copy1=label.getText();
    else if(opcode.equals("02"))

    Here's one idea, that could do what you want an outlines some points
    1. Build a class with the following methods:
    String[] getFunctions ();
    Object[] getFunctionParams (String function);
    boolean accept(String functioncall,String[] args);
    boolean execute (String funcall, String[] args);
    2. You could then just recompile your class with updates that would be recognizable to your console under this framework, or you could do something like this.
    public static void main (String[] args) {
    MyProjectOperations = class.forName(args[0]).instanceOf();
    }

  • Interfaces, Abstract Classes & Polymorphism

    I have a friend taking a Java course as part of a larger degree program, and she's asked for some help with an assignment. The assignment is as follows:
    This assignment is to write a simple encryption/decryption application.  There will be a single application
    that the user can use to encrypt or decrypt a phrase passed in on the command line, with the user deciding
    which encryption/decryption scheme to use.
    The first scheme is to add 1 to each character that is in the phrase, the other is to subtract 1 from each
    character that is in the phrase.
    To encrypt, you must be able to use the follwing syntax:
    java Crypto encrypt Additive "hello"
    Output:
    "hello" encrypts to: "ifmmmp"
    To decrypt:
    java ca.bcit.cst.comp2256.a###### decrypt Additive "ifmmp"
    Output:
    "ifmmp" decrypts to: "hello"
    Use Additive or Subtractive as the arguments to choose which encryption/decryption to
    use. The problem is, I'm not entirely sure how to use abstract classes and interfaces to do what is being asked. I'm pretty sure I could do the whole program in a single for-loop, but apparently her teacher doesn't want people coming up with their own solutions for the problem. I don't need any code for how to do it, per se, I'm just wondering how one would structure a program like that to include interfaces, polymorphism and abstract classes.
    Anyone have any ideas?

    with the user deciding which encryption/decryption scheme to use.This is the key sentence. encryption/decryption can be done using multiple schemes. The contract for any given scheme can be defined using
    public String encrypt(String input);
    public String decrypt(String input);There can be multiple implementations for these methods, one set for each scheme.
    The contract therefore becomes the interface and each implementation is a concrete implementation of this interface.
    The problem doesn't delve deep into the kind of schemes available. If it does and there is a significant overlap between 2 schemes, an abstract class that takes care of the shared logic among 2 schemes comes into picture.
    Hope this helps!

  • Implementing Comparable in an abstract class

    Hi all,
    I am making my first sortie with abstract classes. I have had a good look around, but would still appreciate some advice with the following problem.
    In my application I have several classes that have many things in common. I have concluded therefore, that if I create and then inherit from an abstract super class, I can reduce and improve my code. I created this abstract class:
    public abstract class YAbstractObject implements Comparable {
        public YAbstractObject(int projectId, YObject object, String objectName) {
            this.projectId = projectId; // Always the same parameters
            this.object = object;
            this.objectName = objectName;
        // This is abstract as it must always be present for sub classes but differant processing will take place
        public abstract void resolveObject();
        // These three methods will always be the same for all sub classes
        public String getName() {
            return objectName;
        public YObject getObject() {
            return object;
        public boolean isValid() {
            return isValid;
    // Overridden and always the same for all sub classes
        public String toString() {
            return objectName;
        // implemented abstract method
        public int compareTo(Object thatObject) {
            // Issue here! I would like something as follows:
            //  return this.getName().compareToIgnoreCase(thatObject.getName());
    // Variable decleration
        private int projectId;
        private YObject object;
        private String objectName;
        private boolean isValid;As I have commented in the compareTo() method, I would like it to be able to use the getName() method for comparison objects and compare them. But it does not like this, as it does not know that "thatObject" is of the same class as this object - I hope that made sense.
    in essence, I want to inherit this method for different classes and have it work with each.
    Is there a way to do this? Generics?
    Any observations, greatly appreciated,
    Steve

    You can use also generics (if applicable: java -version >= 1.5).
    public abstract class Test implements Comparable<Test> {
         String name;
         public Test(String name) {
              this.name = name;
         public String getName() {
              return name;
         public int compareTo(Test obj) {
              return this.getName().compareTo(obj.getName());
    public class Other extends Test {
         public Other(String name) {
              super(name);
    public class Tester extends Test {
         public Tester(String name) {
              super(name);
         public static void main(String[] args) {
              Test t = new Tester("t");
              Test a = new Tester("a");
              Test o = new Other("t");
              System.out.println(t.compareTo(a));
              System.out.println(t.compareTo(new Object())); //compile error
              System.out.println(t.compareTo(o));
    }Without the compile error line it will give the following result:
    19
    0

  • Abstract class Vs interface

    Hi,
    I have to buid a report in ECM with complete details of the engineering as well as production. This include workflow as well as various fucntionality depends upon the criterion and user's event.
    I am implementating in OOPS and I Want to know that when I should use the Abstract class and when interface  ?
    Because as per me both serve the same purpose. Kindly send me the exact difference so that i can efficiently use the same.
    Thanks
    Prince

    When inheriting A Interface We have to inherit all the methods of the Interface there's no other option whereas with abstract classes we can inherit the members that we are in need of.
    Just the interface has to have body of the method and the method is to be used by the classes inheriting it. Whereas in the case of Abstract Class it can have declarations (Other than the abstract method) and it can be further extended in the classes inheriting the Abstract Class.
    Interface contains all abstract methods,all methods compulsory implemented by particular class, interface does not contain Constructor
    abstract classes are designed with implemantion gaps for sub-class to fill in.
    interfaces are sintacticlly similar to classes but they lack insance variables & methods.
    abstract classes can also have both abstract methods & non-abstract methods. where as in interface methods are abstract only, & variables are implicitly static&final
    regards
    Preetesh

  • 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

  • Abstract classes and methods with dollar.decimal not displaying correctly

    Hi, I'm working on a homework assignment and need a little help. I have two classes, 1 abstract class, 1 extends class and 1 program file. When I run the program file, it executes properly, but the stored values are not displaying correctly. I'm trying to get them to display in the dollar format, but it's leaving off the last 0. Can someone please offer some assistance. Here's what I did.
    File 1
    public abstract class Customer//Using the abstract class for the customer info
    private String name;//customer name
    private String acctNo;//customer account number
    private int branchNumber;//The bank branch number
    //The constructor accepts as arguments the name, acctNo, and branchNumber
    public Customer(String n, String acct, int b)
        name = n;
        acctNo = acct;
        branchNumber = b;
    //toString method
    public String toString()
    String str;
        str = "Name: " + name + "\nAccount Number: " + acctNo + "\nBranch Number: " + branchNumber;
        return str;
    //Using the abstract method for the getCurrentBalance class
    public abstract double getCurrentBalance();
    }file 2
    public class AccountTrans extends Customer //
        private final double
        MONTHLY_DEPOSITS = 100,
        COMPANY_MATCH = 10,
        MONTHLY_INTEREST = 1;
        private double monthlyDeposit,
        coMatch,
        monthlyInt;
        //The constructor accepts as arguments the name, acctNo, and branchNumber
        public AccountTrans(String n, String acct, int b)
            super(n, acct, b);
        //The setMonthlyDeposit accepts the value for the monthly deposit amount
        public void setMonthlyDeposit(double deposit)
            monthlyDeposit = deposit;
        //The setCompanyMatch accepts the value for the monthly company match amount
        public void setCompanyMatch(double match)
            coMatch = match;
        //The setMonthlyInterest accepts the value for the monthly interest amount
        public void setMonthlyInterest(double interest)
            monthlyInt = interest;
        //toString method
        public String toString()
            String str;
            str = super.toString() +
            "\nAccount Type: Hybrid Retirement" +
            "\nDeposits: $" + monthlyDeposit +
            "\nCompany Match: $" + coMatch +
            "\nInterest: $" + monthlyInt;
            return str;
        //Using the getter method for the customer.java fields
        public double getCurrentBalance()
            double currentBalance;
            currentBalance = (monthlyDeposit + coMatch + monthlyInt) * (2);
            return currentBalance;
    }File 3
        public static void main(String[] args)
    //Creates the AccountTrans object       
            AccountTrans acctTrans = new AccountTrans("Jane Smith", "A123ZW", 435);
            //Created to store the values for the MonthlyDeposit,
            //CompanyMatch, MonthlyInterest
            acctTrans.setMonthlyDeposit(100);
            acctTrans.setCompanyMatch(10);
            acctTrans.setMonthlyInterest(5);
            DecimalFormat dollar = new DecimalFormat("#,##0.00");
            //This will display the customer's data
            System.out.println(acctTrans);
            //This will display the current balance times 2 since the current
            //month is February.
            System.out.println("Your current balance is $"
                    + dollar.format(acctTrans.getCurrentBalance()));
        }

    Get a hair cut!
    h1. The Ubiquitous Newbie Tips
    * DON'T SHOUT!!!
    * Homework dumps will be flamed mercilessly. [Feelin' lucky, punk? Well, do ya'?|http://www.youtube.com/watch?v=1-0BVT4cqGY]
    * Have a quick scan through the [Forum FAQ's|http://wikis.sun.com/display/SunForums/Forums.sun.com+FAQ].
    h5. Ask a good question
    * Don't forget to actually ask a question. No, The subject line doesn't count.
    * Don't even talk to me until you've:
        (a) [googled it|http://www.google.com.au/] and
        (b) had a squizzy at the [Java Cheat Sheet|http://mindprod.com/jgloss/jcheat.html] and
        (c) looked it up in [Sun's Java Tutorials|http://java.sun.com/docs/books/tutorial/] and
        (d) read the relevant section of the [API Docs|http://java.sun.com/javase/6/docs/api/index-files/index-1.html] and maybe even
        (e) referred to the JLS for "advanced" questions.
    * [Good questions|http://www.catb.org/~esr/faqs/smart-questions.html#intro] get better Answers. It's a fact. Trust me on this one.
        - Lots of regulars on these forums simply don't read badly written questions. It's just too frustrating.
          - FFS spare us the SMS and L33t speak! Pull your pants up, and get a hair cut!
        - Often you discover your own mistake whilst forming a "Good question".
        - Often you discover that you where trying to answer "[the wrong question|http://blog.aisleten.com/2008/11/20/youre-asking-the-wrong-question/]".
        - Many of the regulars on these forums will bend over backwards to help with a "Good question",
          especially to a nuggetty problem, because they're interested in the answer.
    * Improve your chances of getting laid tonight by writing an SSCCE
        - For you normal people, That's a: Short Self-Contained Compilable (Correct) Example.
        - Short is sweet: No-one wants to wade through 5000 lines to find your syntax errors!
        - Often you discover your own mistake whilst writing an SSCCE.
        - Often you solve your own problem whilst preparing the SSCCE.
        - Solving your own problem yields a sense of accomplishment, which makes you smarter ;-)
    h5. Formatting Matters
    * Post your code between a pair of &#123;code} tags
        - That is: &#123;code} ... your code goes here ... &#123;code}
        - This makes your code easier to read by preserving whitespace and highlighting java syntax.
        - Copy&paste your source code directly from your editor. The forum editor basically sucks.
        - The forums tabwidth is 8, as per [the java coding conventions|http://java.sun.com/docs/codeconv/].
          - Indents will go jagged if your tabwidth!=8 and you've mixed tabs and spaces.
          - Indentation is essential to following program code.
          - Long lines (say > 132 chars) should be wrapped.
    * Post your error messages between a pair of &#123;code} tags:
        - That is: &#123;code} ... errors here ... &#123;code}
        - OR: &#91;pre]&#123;noformat} ... errors here ... &#123;noformat}&#91;/pre]
        - To make it easier for us to find, Mark the erroneous line(s) in your source-code. For example:
            System.out.println("Your momma!); // <<<< ERROR 1
        - Note that error messages are rendered basically useless if the code has been
          modified AT ALL since the error message was produced.
        - Here's [How to read a stacktrace|http://www.0xcafefeed.com/2004/06/of-thread-dumps-and-stack-traces/].
    * The forum editor has a "Preview" pane. Use it.
        - If you're new around here you'll probably find the "Rich Text" view is easier to use.
        - WARNING: Swapping from "Plain Text" view to "Rich Text" scrambles the markup!
        - To see how a posted "special effect" is done, click reply then click the quote button.
    If you (the newbie) have covered these bases *you deserve, and can therefore expect, GOOD answers!*
    h1. The pledge!
    We the New To Java regulars do hereby pledge to refrain from flaming anybody, no matter how gumbyish the question, if the OP has demonstrably tried to cover these bases. The rest are fair game.

  • 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

  • When to use abstract classes instead of interfaces with extension methods in C#?

    "Abstract class" and "interface" are similar concepts, with interface being the more abstract of the two. One differentiating factor is that abstract classes provide method implementations for derived classes when needed. In C#, however,
    this differentiating factor has been reduced by the recent introduction of extension methods, which enable implementations to be provided for interface methods. Another differentiating factor is that a class can inherit only one abstract class (i.e., there
    is no multiple inheritance), but it can implement multiple interfaces. This makes interfaces less restrictive and more flexible. So, in C#, when should we use abstract classes
    instead of interfaces with extension methods?
    A notable example of the interface + extension method model is LINQ, where query functionality is provided for any type that implements IEnumerable via
    a multitude of extension methods.

    Hi
    Well I believe Interfaces have more uses in software design. You could decouple your component implementing against interfaces so that
    you have more flexibility on changing your code with less risk. Like Inversion of Control patterns where you can use interfaces and then when you decide you can change the concrete implementation that you want to use. Or other uses for interfaces is you could
    use Interceptors using interfaces (Unity
    Interceptor) to do different things where not all of these is feasible or at least as straightforward using abstract classes.
    Regards
    Aram

  • 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

  • Problems with extension of generic abstract class

    Hello,
    I'm having some problems with the extension of a generic abstract class. The compiler tells me I have not implemented an abstract method but I think I have. I have defined the following interface/class hierarchy:
    public interface Mutator<T extends Individual<S>, S> {
         public void apply( T<S> ind );
    public abstract class AbstractMutator<T extends Individual<S>, S> implements Mutator<T, S> {
         public abstract void apply( T<S> ind );
    }Now I implement AbstractMutator as such:
    public class BinaryMutator extends AbstractMutator<StringIndividual<Integer>, Integer> {
         public void apply( StringIndividual<Integer> ind ) { ... }
    }The compiler says:
    BinaryMutator.java:3: ga.BinaryMutator is not abstract and does not override abstract method apply(ga.Individual<java.lang.Integer>) in ga.AbstractMutator
    Why does it say the signature of the abstract method is apply(Individual<Integer>) if I have typed the superclass as StringIndividual<Integer>?
    Thanks.

    Yes, but the abstract method takes an arg of type <T extends Individual>. So it takes an Individual or a subclass thereof, depending on how I parameterise the class, right? StringIndividual is a subclass of Individual. So if I specify T to be StringIndividual, doesn't the method then take an arg of type StringIndividual?

Maybe you are looking for

  • Consumer/producer fast AI and AO.

    I made a routine for fast DAQmx (PXIe-6124) acquisition in two while loop (consumer and producer). Currently it can be run by pushing run-button.  But, I would like to one more while loop (totally 3) for user-friendly interface and integrating sub-pr

  • PDF link does not open in IE, but will open in Firefox and Safari.

    Dreamweaver code: <li><a href="javascript:; "         onClick="MM_openBrWindow('resources/facultyresources/SAFunctionalFramework.pdf','toolbar= yes,menubar=yes,scrollbars=yes,resizable=yes,width=550,height=450')">Eliciting and Assessing Performances

  • Color corrections

    OLA!!! been a while since I have been on the forum.. Right.... just going through the advanced technique apple certified manual, and going through the color correction chapters. This post is really to get confirmed of a trick I have in mind. You have

  • Moving a set of tables and related procedures

    Hi, I have created a set of tables, procedures, functions, and triggers for a particular application on a db at home. Now.. I need to move it to the university. However, the university does not allow us to run sqlldr or imp.. As such, how would I be

  • About Host Credential

    I've installed oracle 10g on Windows 2003. For some special tasks oracle requires host credential; Previously I provided correct username and password of the server (Host) but I got a message which was saying the password was not correct for the user