Question on abstract classes

I just need to make sure that I have a concept right. I know that interface declarations can have fields, but they must be initialized and constant. In an abstract class though, can they also have fields, since it can acept both abstract and concrete methods? If so, do they have the same requirements as an interface? Thanks!

Yes, abstract classes can have fields.
No, it does not have the same requirements as an interface.
It is a class, and so can do everything a concrete class can do, except be instantiated.
It depends on the visibility of the field you define.
Defining a field private means that it can't even be used by its subclasses. Sometimes you might want that, sometimes not.

Similar Messages

  • A question about Abstract Classes

    Hello
    Can someone please help me with the following question.
    Going through Brian's tutorials he defines in one of his exercises an  'abstract' class as follows
    <ClassType ID="MyMP.MyComputerRoleBase" Base="Windows!Microsoft.Windows.ComputerRole" Accessibility="Internal" Abstract="true" Hosted="true" Singleton="false">
    Now I am new to authoring but get the general concepts, and on the surface of it, it appears odd to have an 'abstract' class that is also 'hosted' I understand and abstract class to be a template with one or more properties defined which is then used
    as the base class for one or more concrete classes. Therefore you do not have to keep defining the properties on these concrete classes over and over as they inherit the properties from their parent abstract class, is this correct so far?
    if the above is correct then it seems odd that the abstract class would be hosted, unless (and this is the only way it makes sense to me) that ultimately (apart from singleton classes) any class that is going to end up being discovered and
    thereby an instance of said class instigated in the database must ultimately be hosted somewhere, is that correct?
    in other words if you has an abstract class, which acts as the base class for one or more concrete classes (by which I mean ones for which you are going to create lets say WMI discoveries ), if this parent abstract class is not ultimately
    hosted to a concrete class of its own then these child concrete classes (once discovered) will never actually create instances in the database.
    Is that how it is?
    Any advise most welcome, thanks
    AAnotherUser__
    AAnotherUser__

    Hi,
    Hosting is the only relationship type that doesn't require you to discover it with a discovery rule. OpsMgr will create a relationship instance automatically for you using a 'hosted' properties 'chain' in a class\model definition. In an abstract class definition
    you need to have this property set to 'true' or you will 'brake' a hosting 'chain'.
    http://OpsMgr.ru/

  • Question about Abstract Classes and Class Inheritance

    The semester is winding down, and the assignments are getting more complicated....
    Prof has given us a project involving both an interface and an abstract class. There's a class Person, then an abstract class Employee that extends Person, and two types of Employees (Hourly and Salaried) that extend Employee. The finished assignment is a type of payroll program that's supposed to be able to store both types of Employees and related info (name, salary, etc). One thing the prof suggested was to store both HourlyEmployees and SalariedEmployees in an array of Employees. But you can't instantiate an array of Employees directly, of course, since it's an abstract class.
    So is it possible to create an array of Persons, cast either HourlyEmployees or SalariedEmployees into Employee objects, and then store the Employee objects in the Person array? And if I do that, can I still use methods particular to the SalariedEmployees and/or HourlyEmployees once they are in the Person array? Or can I store SalariedEmployee and HourlyEmployee directly in an array of Persons, without having to cast them into anything else? (In that case, I'm not sure what the point of having the abstract Employee class is, though). Do they become just generic "Persons" if I do this?
    Thanks for any help!

    But you
    can't instantiate an array of Employees directly, of
    course, since it's an abstract class.Sure you can. You just can't instantiate Employee (the abstact class itself, as opposed to its subclasses) objects.
    Employee[] employees = new Employee[20];
    employees[0] = new HourlyEmployee();That should work.
    So is it possible to create an array of Persons, cast
    either HourlyEmployees or SalariedEmployees into
    Employee objects, and then store the Employee objects
    in the Person array?You could do that as well, but you shouldn't need to cast it.
    Given the type hierarchy you describe, an HourlyEmployee is a Person, so you should be able to assign an HourlyEmployee directly to a Person-valued variable.
    And if I do that, can I still use
    methods particular to the SalariedEmployees and/or
    HourlyEmployees once they are in the Person array?No. If the method doesn't exist in Person, then you can't call it on a Person variable, even if the method does exist in the class implementing Person.
    But if the method exists in Person, but is implemented and possibly overridden in HourlyEmployee, you can still invoke it, by just invoking the Person method.
    public interface Person {
      public void feed();
    public abstract class Employee implements Person {
      public abstract void hire();
    public class HourlyEmployee extends Employee {
    // then:
    Person persons = new Person[20];
    // add HourlyEmployees or SalariedEmployees to persons array...
    persons[0].feed(); // OK!
    persons[0].hire(); // NOT OK!

  • Question about abstract classes

    abstract class Animal
    abstract boolean alive();
    class Dog extends Animal
    public int age;
    class Test
    public void main(String args[])
    Animal a = new Dog();
    a.age = 2; // <== Doesn't work, why?
    }

    abstract class Animal
    abstract boolean alive();
    class Dog extends Animal
    public int age;
    class Test
    public void main(String args[])
    Animal a = new Dog();
    a.age = 2; // <== Doesn't work, why?
    }because a is an "Animal" and you didn't specify that all "Animal"s have an "age" - only that "Dog"s do. So of course you would have had to do:
    Dog a = new Dog();
    a.age = 2;
    (It still wouldn't have compiled anyway however, because you didn't implement the "alive" method in Dog)

  • Question about abstract classes and instances

    I have just read about abstract classes and have learned that they cannot be instantiated.
    I am doing some exercises and have done a class named "Person" and an abstract class named "Animal".
    I want to create a method in "Person" that makes it possible to set more animals to Person objects.
    So I wrote this method in class Person and compiled it and did not get any errors, but will this work later when I run the main-method?
    public void addAnimal(Animal newAnimal)
         animal.add(newAnimal);
    }Is newAnimal not an instance?

    Roxxor wrote:
    Ok, but why is it necessary with constructors in abstract classes if we don�t use them (because what I have understand, constructors are used to create objects)?Constructors don't create objects. The new operator creates objects. An object's c'tor is invoked after the object has already been created. The c'tors job is to initialize the newly-created object to a valid state. Whenever a child object is created, the parent's c'tor is run before the child's c'tor, so that by the time we're inside the child's c'tor, setting up the child's state, we know that the parent (or rather the "parent part" of the object we're initializing) is in a valid state.
    Constructor rules:
    1) Every class has at least one ctor.
    1.1) If you do not define an explicit constructor for your class, the compiler provides a implicit constructor that takes no args and simply calls super().
    1.2) If you do define one or more explicit constructors, regardless of whether they take args, then the compiler no longer provides the implicit no-arg ctor. In this case, you must explicitly define a public MyClass() {...} if you want one.
    1.3) Constructors are not inherited.
    2) The first statement in the body of any ctor is either a call to a superclass ctor super(...) or a call to another ctor of this class this(...) 2.1) If you do not explicitly put a call to super(...) or this(...) as the first statement in a ctor that you define, then the compiler implicitly inserts a call to super's no-arg ctor super() as the first call. The implicitly called ctor is always super's no-arg ctor, regardless of whether the currently running ctor takes args.
    2.2) There is always exactly one call to either super(...) or this(...) in each constructor, and it is always the first call. You can't put in more than one, and if you put one in, the compiler's implicitly provided one is removed.

  • Question about abstract class

    Hi,
    I am doing some junit tests with given class.
    However, i cannot touch the original class(or even create any new class).
    All i can do is to create JUnit test class
    This class is abstract and has only one public void method.
    Also, this class is extended by several child classes which are either
    abstract / or public but methods are private/protected.
    So i cannot even create an object of this class by using
    ParentClass pc = new ChildClass();
    Is there any method to test this class without using mock-objectm, and without touching the original class?
    Thanks in advance

    Hi,
    I am doing some junit tests with given class.
    However, i cannot touch the original class(or even
    create any new class).
    All i can do is to create JUnit test class
    This class is abstract and has only one public void
    method.
    Also, this class is extended by several child classes
    which are either
    abstract / or public but methods are
    private/protected.What is meant by abstract / or public.
    However the public method in the base class cannot be
    overidden to be private or protected.
    >
    So i cannot even create an object of this class by
    using
    ParentClass pc = new ChildClass();
    Is there any method to test this class without using
    mock-objectm, and without touching the original
    class?
    Thanks in advance

  • Geting subclass info from abstract class

    Does ne one know how i can retreive informtion from the subclasses of an abstract class by creatinig an instance of the abstract class.
    are Methods such as getClass used?

    Does ne one know how i can retreive informtion from
    the subclasses of an abstract class by creatinig an
    instance of the abstract class.You can never create an instance of the abstract class. That is why they are called abstract.
    >
    are Methods such as getClass used?
    Coming to your actual question, a superclass will not know anything about its children. So you will have to do something else get that information.
    Maybe inspecting all the classes in a classloader and checking its parent will be an option. I do not think this is possible, because ClassLoader does not provide a mechanism to get all the classes.
    Somebody else might give you a better answer. I am just trying to answer one part of your question concerning abstract classes.

  • EJB question: How to use abstract class in writing a session bean?

    I had written an abstract class which implements the session bean as follow:
    public abstract class LoggingSessionBean implements SessionBean {
    protected SessionContext ctx;
    protected abstract Object editRecord(Object obj) throws Exception;
    public LoggingSessionBean()
    super();
    private final String getBeforeUpdateImage(Object obj) throws Exception {
    // implement the details of extracting the backup image ...
    public void setSessionContext(SessionContext ctx)
    this.ctx = ctx;
    private final void writeThisImageToDatabase(String aStr) {
    // connect to database to write the record ...
    public final Object update(final Object obj) {
    try {
    final String aStr = getBeforeUpdateImage(obj);
    writeThisImageToDatabase(aStr);
    editRecord(obj);
    } catch (Exception e) {
    ctx.setRollbackOnly();
    This abstract class is to write the backup image to the database so that other session beans extending it only need to implement the details in editRecord(Object Obj) and they do not need to take care of the operation of making the backup image.
    However, some several questions for me are:
    1. If I write a class ScheduleSessionBean extending the above abstract class and the according 2 interfaces ScheduleSession and ScheduleSessionHome for this session bean (void update(Object obj); defined in ScheduleSession), do I still need to write the interfaces for LoggingSession and LoggingSessionHome?
    2. If I wrote the interface LoggingSession extending EJBObject where it defined the abstract methods "void update(Object obj);" and "void setSessionContext(SessionContext ctx);", that this meant I needed to write the ScheduleSession to implement the Logging Session?
    3. I used OC4J 9.0.4. How can I define the ejb-jar.xml in this case?

    Hi Maggie,
    1. do I still need to write
    the interfaces for LoggingSession and
    LoggingSessionHome?"LoggingSessionBean" can't be a session bean, because it's an abstract class. Therefore there's no point in thinking about the 'home' and 'remote' interfaces.
    2. this
    meant I needed to write the ScheduleSession to
    implement the Logging Session?Again, not really a question worth considering, since "LoggingSessionBean" can't be an EJB.
    3. I used OC4J 9.0.4. How can I define the
    ejb-jar.xml in this case?Same as you define it for any version of OC4J and for any EJB container, for that matter, since the "ejb-jar.xml" file is defined by the EJB specification.
    Let me suggest that you create a "Logging" class as a regular java class, and give your "ScheduleSessionBean" a member that is an instance of the "Logging" class.
    Alternatively, the "ScheduleSessionBean" can extend the "Logging" class and implement the "SessionBean" interface.
    Good Luck,
    Avi.

  • Weird Abstract Class Question

    First off, I hope I'm posting in the correct section of the forum, apologies if I'm not.
    I have a bit a of a weird query more so than a question.
    I have recently been given the challenge of developing a mobile application. So as one does when one gets a job, they sit down and have a think about how to best use Java inheritance to make my their design nice and neat.
    So anyway to do some of the GPS stuff for my app I am using the JSF-179, an API specification for location info. So this JSF API is implemented by a number of providers, nokia, samsung, sony ericsson, etc..
    So as all implementations stick to the API, the code should remain the same for each platform, the only change will be where the code is imported from.
    So for example each class will have:
    import com.nokia.jsf-179
    import com.sony.jsf-179
    import com.samsung.jsf-179And this import info will be the only code that will change.
    I had a number of ideas:
    1 - Create an Interface with methods each concrete class can implement, but with this approach a code re-write is required. Also each sub class will conform to the java is-a rule so it really should extend an abstract class as opposed to implement an Interface.
    2 - Extend Abstract class, we still have the code re-write issue.
    So how then do I keep the code the same but only change the import info all nice and neat like? Is there some kind of abstract marker for imports?

    kajbj wrote:
    @Op. I don't know if you question is more of a design question, or if you have a question that is related to Java ME, or development on mobile phones. I'm however moving this thread from the Generics forum (since the question isn't related to Generics).given that [Joahim's answer|http://forums.sun.com/thread.jspa?messageID=10806927#10806927] satisfied OP, this topic better matches Java ME than design. Suggest to move it to CLDC and MIDP forum for closer toipic alignment

  • Abstract class, a question

    i have an abstract class called shape with default constructor (double y1, double y2);
    with an abstract method area.
    now i have a circle class which extends it, but i want its constructor to have ONE radius (as its pi radius*radius)
    at the moment this is how my circle looks like, and as you can see that there is really no need for second radius how can i modify circle class without modifying shape class?
    class circle extends Shape{
    circle(double radius, double radius1) {
         super(radius, radius);
    double area() {
    return (3.14*x1*x1);
    }

    the answer from the test class in above case will be
    0!Yes, because 3.14 * 0 * 0 is 0.
    but if i change the x3 above to x1, it would work, You honestly don't see why? It's staring you right in the face. What does area() use? How does that field get set?
    the
    reason i decided to use x3 is so that ppl dont get
    confuse! Here's what's confusing:
    * field names x1, x2, x3. What do those mean? They sound like 3 x coordinates.
    * two fields that are used by certain subclasses, but not others, and a third field that's used only by the subclasses that don't use the first two.
    * that third field meaning "the single value that applies to what both of the other two fields mean" instead of just setting both fields to the same value.
    * having any of those fields in there at all in the first place when they're not used by the abstract class and not used consistently by subclasses.
    but shouldnt it work because i have done the
    same thing i did to x1 and x2??

  • Question  about Abstract,Final Class

    when we are using final keyword along with class definition .we are making that class final, means we can’t extend that class. The same thing happens when we make our constructors private. From usability perspective both are same ? or is there any difference?
    Secondly accounting to java syntax a class can be either final or abstract and not both .Then why language specification doesn't impose any restriction on making abstract classes constructor private. We can create an Abstract class with private Constructor (Basically utility class with all methods are static) ,to make this class Singleton .This situation is equal to abstract final class ?
    Thanks,
    Paul.

    EJP wrote:
    when we are using final keyword along with class definition .we are making that class final, means we can’t extend that class. The same thing happens when we make our constructors private.No it doesn't.
    Secondly accounting to java syntax a class can be either final or abstract and not both.Correct.
    Then why language specification doesn't impose any restriction on making abstract classes constructor private.Why should it? That proposition doesn't follow from your previous sentence.I think OP is asking about this case
    public abstract class WTF {
      private WTF() {}
      private WTF(...) {}
    }where the class is abstract and all the c'tors are final. It's an abstract class that cannot be extended, much like a final abstract class would be if it were allowed. So, since purpose of abstract classes is to be extended, the OP seems to be asking, "Why can we, in this fashion, create an abstract class that cannot be extended?"
    I don't know the answer to that, but I would guess that, while final is an explicit syntactical element for the purpose of making a class non-extensible, in the all-private-c'tors case, the non-extensibility is simply a side effect, and probably enough of a corner case that it wasn't worth the effort to explicitly forbid it in the spec.
    I also think it's something not worth thinking much about. It was certainly not a key point of some grand design.

  • Generics/Abstract class question

    I'm not sure exactly what my problem is here. I am creating an abstract class for a number of other data types that I am creating. The purpose of this class is to track changes so that the GUI can prompt the user to save changes if they try to exit without saving. I want to do this by storing a reference of the original object and then making changes on a new object. I am running into problems though. Right now I am trying to define the clone method in that class and am getting an error.
    public abstract class ChangeableDataType<T extends ChangeableDataType>{
        protected T old;
        public Object clone(){
            T t = new T(); // Error occurs here
            //Stuff
        }The error I get is unexpected type on the line where I try to call a new T(). Is this not something that I can do? I have tried to put any code in that I thought might have the problem.

    No, that isn't something you can do. I'm sure it's discussed in more (and better) detail in [the Generics FAQ|http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html] though.

  • Question about Classes, Abstract  Classes and Interfaces.

    I have been experimenting with Classes, Abstract Classes and Interfaces and wonder if anyone can explain this to me.
    I was looking for a way to assign a value to a variable and then keep it fixed for the session and have devised this.
    First I create an abstract class like this:
    public abstract class DatabaseConnection {
    private static String ServerName = null;
    public static void setServerName(String serverName) {
              ServerName = serverName;
         public static String getServerName() {
              return ServerName;
    }and then I created an interface
    public interface DatabaseAccess {
         String servername = DatabaseConnection.getServerName();
    }And finally the class itself with some test lines in it so I could see what was going on:
    public class CreateDatabase extends DatabaseConnection implements DatabaseAccess {
         public static void main (String args[]){
              new CreateDatabase();
         public CreateDatabase(){     
              setServerName("Server Name 1");
              System.out.println ("Before update ");
              System.out.println ("ServerName from Interface           = " + servername);
              System.out.println ("ServerName from Abstract Class = " + getServerName());
              System.out.println ("After update ");
              setServerName("Server Name 2");
              System.out.println ("ServerName from Interface           = " + servername);
              System.out.println ("ServerName from Abstract Class = " + getServerName());
              System.out.println ("==========================");
    }The output I get from the above is:
    Before update
    ServerName from Interface           = Server Name 1
    ServerName from Abstract Class = Server Name 1
    After update
    ServerName from Interface           = Server Name 1
    ServerName from Abstract Class = Server Name 2
    ==========================I also tried this in another class which calls the above class to see if I get the same effect
    public class CheckDatabaseAccess {
         public static void main (String args[]){
              new CreateDatabase();
              CreateDatabase.setServerName("Server 3");
              System.out.println("CreateDatabase "+CreateDatabase.servername);
              CreateDatabase.setServerName("Server 4");
              System.out.println("CreateDatabase "+CreateDatabase.servername);
              CreateDatabase.setServerName("Server 5");
              System.out.println("CreateDatabase "+CreateDatabase.servername);
    }The output of which is this:
    Before update
    ServerName from Interface           = Server Name 1
    ServerName from Abstract Class = Server Name 1
    After update
    ServerName from Interface           = Server Name 1
    ServerName from Abstract Class = Server Name 2
    ==========================
    CreateDatabase Server Name 1
    CreateDatabase Server Name 1
    CreateDatabase Server Name 1Can anyone explain why I appear to only be able to change or set the ServerName only the once?
    Is this the correct way to do it? If it is it's exactly what I am looking for, a way to set the value of variable once in a session and then prevent it being changed.
    Or is there a better way of doing this.
    What I want to use this for is for example, storing the accesses to a database on a server. I won't know what server the database will be stored on nor what the database is called so I create an INI file which stores this information in encrypted format, which is set by the database administrator. It occurs to me I can use this method to then retrieve that data once and once only from the INI file and use that throughout the life of the session to access the database.
    Any help appreciated
    Regards
    John

    Not gonna read all of it, but this jumps out:
    public abstract class DatabaseConnection {
    private static String ServerName = null;
    public interface DatabaseAccess {
         String servername = DatabaseConnection.getServerName();
    }You have two completely separate variables (with two different names, for that matter, since you were inconsistent in your capitalization, but it wouldn't make a difference if they did have the same name with the same case). And the one in the interface is implicitly public, static, and final.
    Anytime you refer to "servername" through a reference of type DatabaseAccess, it refers to the one declared in the interface.
    Anytime you refer to "ServerName" inside the DatabaseConnection class, it refers to the one declared in that class.

  • A Singleton variable in an Abstract Class

    Hello there people
    I have a quick question. I have made an abstract class in which I want to put an identifier (ID) int to be incremented whenever I make any of the concrete class instances that extend this abstract class.
    whould that declairation be as follows?:
    public static int IDAdditionally, I have a quick question about abstract constructors. If constructors are defined in the concrete classes, are their declairations needed in the abstract class?
    and finally, if I wanted to use the int ID (as mentioned above) then would I have to use constructor from the abstract class?
    thanks in advance for the help

    I think the OP would want a constructor in the abstract class to update that variable. Otherwise, he'd have to remember to update it in the constructor for all concrete classes. But, you don't declare constructors for the concrete class in the abstract class. You only declare constructors for the abstract class in the abstract class.

  • A question about calling classes

    Hi,
    I have a question regarding software design so that each class is independent of other.
    public class A
        public void methodA()
                 B m_B=new B();
              String strA=m_B.getBString();
              System.out.println(strA);
    public class B
       public String getBString()
                      return "someString";
    }My question: Is it possible to call the method in class B from class A without creating an instance of class B in method of class A ?
    I am trying to figure out if this can be done using interfaces and abstract classes.
    I am waiting for some suggestions and if you have completely different suggestion then I am open for it too.
    thanks in advance,
    @debug.

    interface I {
        String getString();
    class B implements I {
        public String getString() { return "someString";}
    class A {
        private I foo;
        public void setFoo(I foo) {this.foo = foo;}
        public I getFoo() {return foo;}
        public void methodA() {
          System.out.println(getFoo().getString());
    public class Main {
        public static void main(String[] args) {
            A a = new A();
            a.setFoo(new B());
            a.methodA();
    }There's one problem with decoupling A and B in this case - A's method creates an instance of B. The above is one solution. There are many others.

Maybe you are looking for

  • I bought the wrong version (clean/explict) is there a way to transfer?

    When I bought a song in the app store I bought the wrong one is there a way I could exchange it for the correct one?

  • HELP - Modify user group by bulk un CUCM 8.6

    Hi guys, I am having problem by update/modify user group on CUCM. There are already some users within user group with admin privileges. That should be changed, so I created a group with some privileges and then I tried to change the usergroup by bulk

  • IMac G3 OS 9.2.2 with DHCP problems

    I'm totally new to Macs, so I apologize in advance if I don't know the correct things to mention in this post. I just received two nearly identical iMac G3's (the only difference is one is 350MHz, the other is 400MHz) and wanted to get them onto my h

  • PI 7.1 File & JMS Adapter stops polling at random times

    Hi All, IN PI 7.1, at random times, the File Adapter stops polling. But status is green in RWB. It starts working after the restart of File Service. Any idea why this happens? (We don't use FTP Protocol)

  • Why is Grapher playing my videos, not Quicktime?

    I have downloaded Quicktime twice, but my laptop keeps ignoring it and using grapher to play my videos, not very well, it's very frustrating. How can I disable Grapher and make Quicktime my default again? Thanks