Abstract class in Java

后端 未结 14 1268
孤独总比滥情好
孤独总比滥情好 2020-11-22 12:32

What is an \"abstract class\" in Java?

相关标签:
14条回答
  • 2020-11-22 13:03

    A Java class becomes abstract under the following conditions:

    1. At least one of the methods is marked as abstract:

    public abstract void myMethod()
    

    In that case the compiler forces you to mark the whole class as abstract.

    2. The class is marked as abstract:

    abstract class MyClass
    

    As already said: If you have an abstract method the compiler forces you to mark the whole class as abstract. But even if you don't have any abstract method you can still mark the class as abstract.

    Common use:

    A common use of abstract classes is to provide an outline of a class similar like an interface does. But unlike an interface it can already provide functionality, i.e. some parts of the class are implemented and some parts are just outlined with a method declaration. ("abstract")

    An abstract class cannot be instantiated, but you can create a concrete class based on an abstract class, which then can be instantiated. To do so you have to inherit from the abstract class and override the abstract methods, i.e. implement them.

    0 讨论(0)
  • 2020-11-22 13:05

    An abstract class is one that isn't fully implemented but provides something of a blueprint for subclasses. It may be partially implemented in that it contains fully-defined concrete methods, but it can also hold abstract methods. These are methods with a signature but no method body. Any subclass must define a body for each abstract method, otherwise it too must be declared abstract. Because abstract classes cannot be instantiated, they must be extended by at least one subclass in order to be utilized. Think of the abstract class as the generic class, and the subclasses are there to fill in the missing information.

    0 讨论(0)
  • 2020-11-22 13:08

    Simply speaking, you can think of an abstract class as like an Interface with a bit more capabilities.

    You cannot instantiate an Interface, which also holds for an abstract class.

    On your interface you can just define the method headers and ALL of the implementers are forced to implement all of them. On an abstract class you can also define your method headers but here - to the difference of the interface - you can also define the body (usually a default implementation) of the method. Moreover when other classes extend (note, not implement and therefore you can also have just one abstract class per child class) your abstract class, they are not forced to implement all of your methods of your abstract class, unless you specified an abstract method (in such case it works like for interfaces, you cannot define the method body).

    public abstract class MyAbstractClass{
      public abstract void DoSomething();
    }
    

    Otherwise for normal methods of an abstract class, the "inheriters" can either just use the default behavior or override it, as usual.

    Example:

    public abstract class MyAbstractClass{
    
      public int CalculateCost(int amount){
         //do some default calculations
         //this can be overriden by subclasses if needed
      }
    
      //this MUST be implemented by subclasses
      public abstract void DoSomething();
    }
    
    0 讨论(0)
  • 2020-11-22 13:09

    An abstract class can not be directly instantiated, but must be derived from to be usable. A class MUST be abstract if it contains abstract methods: either directly

    abstract class Foo {
        abstract void someMethod();
    }
    

    or indirectly

    interface IFoo {
        void someMethod();
    }
    
    abstract class Foo2 implements IFoo {
    }
    

    However, a class can be abstract without containing abstract methods. Its a way to prevent direct instantation, e.g.

    abstract class Foo3 {
    }
    
    class Bar extends Foo3 {
    
    }
    
    Foo3 myVar = new Foo3(); // illegal! class is abstract
    Foo3 myVar = new Bar(); // allowed!
    

    The latter style of abstract classes may be used to create "interface-like" classes. Unlike interfaces an abstract class is allowed to contain non-abstract methods and instance variables. You can use this to provide some base functionality to extending classes.

    Another frequent pattern is to implement the main functionality in the abstract class and define part of the algorithm in an abstract method to be implemented by an extending class. Stupid example:

    abstract class Processor {
        protected abstract int[] filterInput(int[] unfiltered);
    
        public int process(int[] values) {
            int[] filtered = filterInput(values);
            // do something with filtered input
        }
    }
    
    class EvenValues extends Processor {
        protected int[] filterInput(int[] unfiltered) {
            // remove odd numbers
        }
    }
    
    class OddValues extends Processor {
        protected int[] filterInput(int[] unfiltered) {
            // remove even numbers
        }
    }
    
    0 讨论(0)
  • 2020-11-22 13:09

    It do nothing, just provide a common template that will be shared for it's subclass

    0 讨论(0)
  • 2020-11-22 13:13

    A class that is declared using the abstract keyword is known as abstract class. Abstraction is a process of hiding the data implementation details, and showing only functionality to the user. Abstraction lets you focus on what the object does instead of how it does it.

    Main things of abstract class

    • An abstract class may or may not contain abstract methods.There can be non abstract methods.

      An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:

      ex : abstract void moveTo(double deltaX, double deltaY);

    • If a class has at least one abstract method then that class must be abstract

    • Abstract classes may not be instantiated (You are not allowed to create object of Abstract class)

    • To use an abstract class, you have to inherit it from another class. Provide implementations to all the abstract methods in it.

    • If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.

    Declare abstract class Specifying abstract keyword before the class during declaration makes it abstract. Have a look at the code below:

    abstract class AbstractDemo{ }
    

    Declare abstract method Specifying abstract keyword before the method during declaration makes it abstract. Have a look at the code below,

    abstract void moveTo();//no body
    

    Why we need to abstract classes

    In an object-oriented drawing application, you can draw circles, rectangles, lines, Bezier curves, and many other graphic objects. These objects all have certain states (for ex -: position, orientation, line color, fill color) and behaviors (for ex -: moveTo, rotate, resize, draw) in common. Some of these states and behaviors are the same for all graphic objects (for ex : fill color, position, and moveTo). Others require different implementation(for ex: resize or draw). All graphic objects must be able to draw or resize themselves, they just differ in how they do it.

    This is a perfect situation for an abstract superclass. You can take advantage of the similarities, and declare all the graphic objects to inherit from the same abstract parent object (for ex : GraphicObject) as shown in the following figure.

    First, you declare an abstract class, GraphicObject, to provide member variables and methods that are wholly shared by all subclasses, such as the current position and the moveTo method. GraphicObject also declared abstract methods, such as draw or resize, that need to be a implemented by all subclasses but must be implemented in different ways. The GraphicObject class can look something like this:

    abstract class GraphicObject {
    
      void moveTo(int x, int y) {
        // Inside this method we have to change the position of the graphic 
        // object according to x,y     
        // This is the same in every GraphicObject. Then we can implement here. 
      }
    
      abstract void draw(); // But every GraphicObject drawing case is 
                            // unique, not common. Then we have to create that 
                            // case inside each class. Then create these    
                            // methods as abstract 
      abstract void resize();
    }
    

    Usage of abstract method in sub classes Each non abstract subclasses of GraphicObject, such as Circle and Rectangle, must provide implementations for the draw and resize methods.

    class Circle extends GraphicObject {
      void draw() {
        //Add to some implementation here
      }
      void resize() {
        //Add to some implementation here   
      }
    }
    class Rectangle extends GraphicObject {
      void draw() {
        //Add to some implementation here
      }
      void resize() {
        //Add to some implementation here
      }
    }
    

    Inside the main method you can call all methods like this:

    public static void main(String args[]){
       GraphicObject c = new Circle();
       c.draw();
       c.resize();
       c.moveTo(4,5);   
    }
    

    Ways to achieve abstraction in Java

    There are two ways to achieve abstraction in java

    • Abstract class (0 to 100%)
    • Interface (100%)

    Abstract class with constructors, data members, methods, etc

    abstract class GraphicObject {
    
      GraphicObject (){
        System.out.println("GraphicObject  is created");
      }
      void moveTo(int y, int x) {
           System.out.println("Change position according to "+ x+ " and " + y);
      }
      abstract void draw();
    }
    
    class Circle extends GraphicObject {
      void draw() {
        System.out.println("Draw the Circle");
      }
    }
    
    class TestAbstract {  
     public static void main(String args[]){
    
       GraphicObject  grObj = new Circle ();
       grObj.draw();
       grObj.moveTo(4,6);
     }
    }
    

    Output:

    GraphicObject  is created
    Draw the Circle
    Change position according to 6 and 4
    

    Remember two rules:

    • If the class has few abstract methods and few concrete methods, declare it as an abstract class.

    • If the class has only abstract methods, declare it as an interface.

    References:

    • TutorialsPoint - Java Abstraction
    • BeginnersBook - Java Abstract Class Method
    • Java Docs - Abstract Methods and Classes
    • JavaPoint - Abstract Class in Java
    0 讨论(0)
提交回复
热议问题