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)

Similar Messages

  • 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.

  • 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 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

  • A question about Object Class

    I got a question about Object class in AS3 recently.
    I typed some testing codes as following:
    var cls:Class = Object;
    var cst:* = Object.prototype.constructor;
    trace( cls === cst); // true
    so cls & cst are the same thing ( the Object ).
    var obj:Object = new Object();
    var cst2:* = obj.constructor.constructor;
    var cst3:* = obj.constructor.constructor.c.constructor;
    var cst5:* = Object.prototype.constructoronstructor;
    var cst4:* = Object.prototype.constructor.constructor.constructor;
    var cst6:* = cls.constructor;
    trace(cst2 === cst3 && cst3 === cst4 && cst4 === cst5 && cst5 === cst6); //true
    trace( cst == cst2) // false
    I debugged into these codes and found that cst & cst2 had the same content but not the same object,
    so why cst & cst2 don't point to the same object?
    Also, I can create an object by
    " var obj:Object = new cst();"
    but
    " var obj:Object = new cst2();"
    throws an exception said that cst2 is not a constructor.
    Anyone can help? many thanks!

    I used "describeType" and found that "cst2" is actually "Class" class.
    So,
    trace(cst2 === Class); // true
    That's what I want to know, Thank you.

  • 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.

  • A qestion about abstract class

    Dear friends!
    I have follow simple code:
    abstract class Aclass {
    abstract void method1();     
    class Bclass extends Aclass {
    public void method1(String s){
    // implementation
    As I understand I can overload the method "method1" but I got an error.
    So what should I do?
    Thanks

    As I understand I can overload the method "method1"
    but I got an error.
    So what should I do?First of all, whenever you are getting an error and you ask a question here about that error, you should tell us what the error is - most of the tim, you won't get a useful answer if we have to guess what your problem is. Also, when posting code, please use the forum's [code]...[[b]code] formatting tags (see the "special tokens" link when posting a message - you are much more likely to get a useful response if we can read your code - many people will just ignore your question if it is not easy to read.
    Having said that, I'll hazard a guess that the error you are getting is somewhere along the lines of "Class Bclass must implement the inherited abstract method method1()". If so, then that is what you should do - implement amethod called method1 in class Bclass, that takes no arguments.
    Yes, you can overload method1, but you have then implemented an entirely different method - you must supply a no-args version as well.

  • 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.

  • Newbie question about abstract methods

    hey, I'm working on a web application that I was given and I'm a little confused about
    some of the code in some of the classes. These are some methods in this abstract class. I don't understand
    how this post method works if the method it's calling is declared abstract. Could someone please tell me how this works?
        public final Representation post(Representation entity, Variant variant) throws ResourceException {
            prePostAuthorization(entity);
            if (!authorizeGet()) {
                return doUnauthenticatedGet(variant);
            } else {
                return doAuthenticatedPost(entity, variant);
    protected abstract boolean authorizeGet();Thanks
    Edited by: saru88 on Aug 10, 2010 8:09 PM

    Abstract Methods specify the requirements, but to Implement the functionality later.
    So with abstract methods or classes it is possible to seperate the design from the implementation in a software project.
    Abstract methods are always used together with extended classes, so I am pretty sure that you are using another class.
    Btw: Please post the Code Keyword in these brackets:                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    

  • Question about inner class - help please

    hi all
    i have a question about the inner class. i need to create some kind of object inside a process class. the reason for the creation of object is because i need to get some values from database and store them in an array:
    name, value, indexNum, flag
    i need to create an array of objects to hold those values and do some process in the process class. the object is only for the process class that contains it. i am not really certain how to create this inner class. i tried it with the following:
    public class process{
    class MyObject{}
    List l = new ArrayList();
    l.add(new MyObject(....));
    or should i create the object as static? what is the benifit of creating this way or static way? thanks for you help.

    for this case, i do need to create a new instance of
    this MyObject each time the process is running with a
    new message - xml. but i will be dealing with the case
    where i will need a static object to hold some
    property values for all the instances. so i suppose i
    will be using static inner class for that case.The two situations are not the same. You know the difference between instance variables and static variables, of course (although you make the usual sloppy error and call them static objects). But the meaning of "static" in the definition of an inner class is this: if you don't declare an inner class static, then an instance of that inner class must belong to an instance of its containing class. If you do declare the inner class static, then an instance of the inner class can exist on its own without any corresponding instance of the containing class. Obviously this has nothing to do with the meaning of "static" with respect to variables.

  • About  "abstract class cannot have be instantiated"

    in java coding it means
    ========
    abstract  class X
      public X();
    }========
    no {} is allowed to public X
    or i can not write a invoke as
    ========
    X x=new X();========
    or both of them are forbidden by abstract class?
    why body{} is related to instantiated?
    why a abstract class can not has a static method?

    in java coding it means
    ========
    abstract class X
    public X();
    ========
    no {} is allowed to public X???
    You must include the braces for the constructor. The code you have posted won't compile.
    or i can not write a invoke as
    ========
    X x=new X();
    ========Correct. You need to provide the implementation first, which can be as simple as "X x = new X() { };".
    why body{} is related to instantiated?It's not.
    why a abstract class can not has a static method?It can. Try writing some of your own tests to validate your (incorrect) assumptions.
    Example:abstract class X
      public X() { };
      static void foo() {};
    }

  • About Abstract class

    Hi All,
    I m inherting from abstract class . So is it mandatory for me to provide implemenation for all methods that r defined in abstract class
    i m getting error like this:
    subclass class is not abstract ,does not override abstract method "methodname" in superclass
    Thanks in advance
    Waiting for replies
    Amar

    - you need to override all methods from your abstract
    superclass.....You don't have to override anything unless you want to, but you have to supply implementation for all abstract classes. If you don't you will have to declare the subclass abstract and let another subclass down the hierarchy finish the job. Eventually all abstract classes must be implemented otherwise objects cannot be instantiated. For that a class must be fully concrete.

  • 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.

  • About abstract classes

    What's the usefulness of declaring methods in an abstract class if they cannot have body?

    Abstract classes are useful if you have a class where it makes no sense to create an instance of that class, but that would make a good class to
    inherit from. For instance, a class called Shape. Nothing is only a shape, but circles, squares, and triangles are all types of shapes.
    If some of the shape methods are generic enough that it makes sense to implement them in the shape class, then the shape class should be made abstract. If all the methods are specific and should only be implemented in the inherited classes then the shape class should be an interface. For example:
    abstract class Shape {
    abstract void draw(); /*each shape is drawn differently */
    void erase(){ /* code for erase method */ }
    abstract int getSize(); /*size calculated diffently for each shape*/
    class Circle extends Shape{
    void draw() { /*code for draw method*/ }
    int getSize() { /*code for getSize method*/ }
    class Square extends Shape{
    void draw() { /*code for draw method*/ }
    int getSize() { /*code for getSize method*/ }
    draw() and getSize() are implemented differently in each derived class, but erase() is the same for every class, so it only needs to be implemented once in Shape. When you have alot of methods that only need to be implemented once for a group of classes, this can save alot of typing.
    Another use of abstract and interface is that they let the user of a class know what to expect from that class. For instance, the Cloneable
    interface has no methods, but a class that implements it is expected to support some type of cloning.
    There is alot more to abstract classes and interfaces. These are just some simple examples. They are basically used to provide a common interface to work with a group of related classes.

Maybe you are looking for