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.

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

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

  • I want to make sure about abstract classes issue

    Hello,
    I have an interface with two methods.
    interface call{
    void trial (int p);
    void show();
    And an abstract class that implements that interface with overriding only one method of the two.
    abstract class client implements call {
    public void trial(int num) { System.out.println(num);}
    In the main method, I wanted to instantiate the implementing class in order to make use of the one method it overrides, but I received an error that the class as abstract, cannot be instantiated.
    class test{
    public static void main(String args[]) {
    //creating object reference to the implementing class
    client c = new client(); //the error is here
    c.trial(5);
    //creating an interface reference
    call m = new client(); //also doesn't work
    m.trial(5);
    So does I understand from this that if a class does not provide full implementation of an interface (i.e. abstract class), it cannot be used inside my program?
    Thanks!

    Please use code tags (see CODE button above posting box). Also, please use standard Java conventions of using a capital letter to start a class name.
    You are getting that error message because you didn't define show, and the interface requires it. You have to extend the Client abstract class to define show.
    You can make an anonymous class that defines show:
    Call m = new Client() {
       public void show() {
          System.out.println("Do something.");
    m.trial(5);Or, you can make a non-anonymous class that defines show:
    class MyClient extends Client {
       public void show() {
    }In this example, "show" doesn't actually do anything, but it does satisfy the interface. You can put the same "show" as I put in my anonymous class, or you can do whatever you want in "show".
    Then, in your "main", you'd have:
    MyClient client = new MyClient();
    client.trial(5);
    //or
    Call anotherClient = new MyClient();
    anotherClient.trial(6);
    //or
    Client yetAnotherClient = new MyClient();
    yetAnotherClient.trial(7);

  • 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

  • Why use an Abstract Class ?

    I am new to Java and for some reason I can't get my head around why to use an abstract class. I understand that an abstract class is something like:
    public abstract class Food{ // abstract class
    public void eat(){
    // stub
    public class Apple extends Food{
    public void eat(){
    // Eat an apple code
    }So basically the idea above is that you can eat an "apple" but you can't eat "food" because you can't instantiate an abstract class.
    I understand what an abstract class is and how to write one. What I don't understand is why you would use it? It looks to me like I could have just created a normal class called "Food" and just not instantiated it. What are the benefits of using an abstract class?

    807479 wrote:
    I am new to Java and for some reason I can't get my head around why to use an abstract class.One of the first books I ever read about Object-Oriented design contained the following quote from [url http://en.wikipedia.org/wiki/Lucius_Cary,_2nd_Viscount_Falkland]Lord Falkland:
    "When it is not necessary to make a decision, it is necessary +not+ to make a decision."
    It took me quite a while to understand, but it's all about flexibility: As soon as you cast something in stone, you lose the ability to change it later on if something better/more appropriate comes along. Interfaces and abstract classes are all about delaying that decision.
    As jverd said, interfaces allow you to specify what is required without defining the how; and as ErasP said, abstract classes are usually incomplete: ie, they define some of the 'how', but not all of it.
    What is most important about abstract classes though is that they cannot exist on their own: They must be extended by a concrete class that completes the 'how' before they can be instantiated and, as such, they declare the intent of the designer.
    One of the most important uses of abstract classes is as "skeleton implementations" of interfaces, and there are a lot of examples of these in the Java Collections hierarchy. My favourite is probably AbstractList, which contains a skeleton implementation of a List. Because it exists, I can create a class that wraps an array as a List with very little code, viz:public final class ArrayAsList<T>()
       extends AbstractList<T>
       private final T[] values;
       public ArrayAsList(T... values) {
          this.values = values;
       @Override
       public T get(int index) {
          return values[index];
       @Override
       public T set(int index, T element) {
          T value = get(index);
          values[index] = element;
          return value;
       @Override
       public int size() {
          return values.length;
    };and somewhere else, I can use it:   List<String> letters =
          new ArrayAsList<String>("a", "b", "c");or perhaps, more practically:   List<String> words = new ArrayAsList<String>(
          bigTextString.split(" +") );Now that may not seem like a big deal to you, but given all that Lists can do, it's actually a very powerful bit of code. The above example is from "Effective Java" (p.95).
    HIH
    Winston

  • Extending Abstract Classes & Program Entry Point

    I have the following classes:
    CopServlet - which extends PercServlet
    PercServlet - abstract class which extends HttpServlet
    HttpServlet is the base class. I'm using Visual Age with a web.xml file that points to CopSerlet as the controller servlet. So my question is... When CopServlet gets called, where is my program entry point? My CopServlet class does NOT have a main method.

    When CopServlet gets loaded, its init() method is called. And when it is called via an HTTP request, either its doGet() or its doPost() method is called, depending on whether it was a GET or a POST request. That's how servlets work. The business about abstract classes is irrelevant to that.

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

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

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

  • About abstract method read() in class InputStream

    I would like to know if behind the method
    public abstract int read() throws IOException
    in the abstract class InputStream there is some code that
    is called when I have to read a stream. In this case where can I find
    something about this code and, if is written in other languages, why
    is not present the key word native?
    Thanks for yours answers and sorry for my bad english.

    Ciao Matteo.
    Scusa se ti rispondo in ritardo... ma ero in pausa pranzo.
    Chiedimi pure qualcosa di pi? specifico e se posso darti una mano ti rispondo.
    Le classi astratte sono utilizzate per fornire un comportamento standard lasciando per? uno o pi? metodi non implementati... liberi per le necessit? implementative degli utilizzatori.
    Nel caso specifico la classe InputStream ? una classe astratta che lascia non implementato il metodo read(). Tu nel tuo codice non utilizzerai mai questa classe come oggetto, ma nel caso specifico una sua sottoclasse che ha implementato il metodo read().
    Se vai nelle api di InputStream vedrai che ci sono diverse sottoclassi che estendono InputStream. Guarda ad esempio il codice di ByteArrayInputStream: in questa classe il metodo read() non ? nativo ma restituisce un byte appartenente al suo array interno.
    I metodi nativi (ad esempio il metodo read() della classe FileInputStream) non hanno implementazione java ma fanno invece riferimento a delle chiamate dirette al sistema operativo.
    Per quanto riguarda la classe FilterInputStream di cui parlavi: essa nel suo costruttore riceve un InputStream. Questo significa che si deve passare nel costruttore non la classe InputStream (che ? astratta) ma una classe che la estende e che quindi non sia astratta. Il motivo per il quale FilterInputStream faccia riferimento a una classe di tipo InputStream al suo interno, ? che in java gli stream di input e di output possono essere composti l'uno sopra l'altro per formare una "catena" (a tal proposito vedi per maggiori dettagli uno dei tani articoli che si trovano in rete.... ad esempio ti indico questo http://java.sun.com/developer/technicalArticles/Streams/ProgIOStreams/). Comunque per dirla in due parole: tu puoi voler usare un FileInputStream per leggere un file, ma se hai bisogno di effettuare una lettura pi? efficiente (quindi bufferizzata) puoi aggiungere in catena al FileInputStream un oggetto di tipo FilterInputStream (nel caso specifico un BufferedInputStream che non ? altro che una sottoclasse di FilterInputStream).
    Spero di aver chiarito qualche tuo dubbio!
    Ciao
    Diego

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

Maybe you are looking for

  • ERROR MESSAGE AMT : CANNOT DELETE TOKEN AFTER IT WAS ASSIGNED TO A ROLE

    We are working on the setup in our sandbox environment and we have noticed that we are unable to delete tokens and remove the protection on BO's. the following message appears : "CANNOT DELETE TOKEN AFTER IT WAS ASSIGNED TO A ROLE" There is no Token

  • Animations in 1080 x 1920 HD resolutions

    Hi, I am trying to create an animation in flex using AS 3.0 Tweener class in 1080 x 1920 resolution, but the animation seems to be flickering. Is there any solution to overcome the flickering. I have tried increasing the frame rate but the animation

  • How does the JFileChooser "readOnly" property work?

    The "normal" behaviour for a file chooser usiing the UIManager "FileChooser.readOnly" default value of Boolean.FALSE is: 1) A "New Folder" button is displayed 2) When a File in the list is selected you can use the F2 key to rename the file 3) Or, if

  • Can you turn the screen totally upside down on iPhone?

    I would really like to be able to totally turn my iPhones screen upside down so that the home button is on the top and I can use it as normal or even lock it in that position. Is this feature already available? If so, how can I activate it. If not, t

  • Downloaded Adobe Download Assistant to download CS6 Master Collection but wont run

    I tried saving it in my downloads folder and my desktop. Whenever I try to run the program  AdobeDownloadAssistant, a loading bar appears that says "Installing Adobe Download Assistant. Please wait." and the bar never moves and it stays like that ind