开发者

How and when to use an abstract class

开发者 https://www.devze.com 2023-03-06 12:38 出处:网络
This is my test program in Java. I want to know how much abstract class is more important here and why we use abstract class for this.

This is my test program in Java. I want to know how much abstract class is more important here and why we use abstract class for this.

Is it a mandatory or is it best method; if so how?

class Shape1 {
    int i = 1;
    void draw() {
        System.ou开发者_C百科t.println("this is shape:" + i);
    }
}

class Shape2 {
    int i = 4;
    void draw() {
        System.out.println("this is shape2:" + i);
    }
}


class Shape {
    public static void main(String args[]) {
        Shape1 s1 = new Shape1();
        s1.draw();

        Shape2 s2 = new Shape2();
        s2.draw();
    }
}


You'd use an abstract class or interface here in order to make a common base class/interface that provides the void draw() method, e.g.

abstract class Shape() {
  void draw();
}

class Circle extends Shape {
   void draw() { ... }
}

...

Shape s = new Circle();
s.draw();

I'd generally use an interface. However you might use an abstract class if:

  1. You need/want to provide common functionality or class members (e.g. the int i member in your case).
  2. Your abstract methods have anything other than public access (which is the only access type allowed for interfaces), e.g. in my example, void draw() would have package visibility.


An abstract class is a class, which has at least one method not implemented, or the keyword abstract. For example, an abstract method may look like this:

public abstract String myMethod(String input);

(note that the method ends with a semi-colon).

And a class may look like this:

public abstract class MyClass {

    public abstract String myMethod(String input);

    public String anotherMethod(String input) {
        return intput + " additional text";
    }
}

An abstract class cannot be instantiated. Abstract classes require a subclass to implement the missing behaviour so that it can be instantiated.

The main goal of an abstract class is to provide shared implementation of common behaviour - promoting the reuse of code.

In Java the same effect can be achieve by using a composition of classes instead of inheritance from broadly defined abstract classes. This allows more modular, function specific classes promoting code reuse, that in turn increase maintainability.

My advice would be to use abstract class only when strictly necessary, and in particular avoid using it as a trick bag full of all sorts of functionality.

In Scala one would use traits, which are an elegant way to solve this. It does however, require a lot of attention to get it right through.

Edit: Starting Java 8, default methods in interface are another way to add common behavior.


An abstract class has an "is-a" type relationship with your subclasses. So for instance, you could have an abstract class Shape which has stuff any shape has (like a draw function), and then a class SquareShape. Every squareshape is a shape, but not all shapes are squareshapes.

In you example you have 2 shape-types, and a class that has 2 instances of these. That is not a relationship you should define with abstract I think.

You might want to do something with your names though, because this is a rather small example, it's hard to see the real implications of the files, and how they should work.


Common things + Uncommon things = Abstract class

When to use?

An abstract class is best suited for the scenarios where there is a lot of reusable code which you don't want to write again and again + There are few things which are specific to each class.

Example?

Ceremony:

Common things: Sing Anthem, Hoist Flag etc
Specific things: Indian Flag, Indian anthem(For India), China Flag, China anthem(For China) etc.

How and when to use an abstract class

How to use it?

1) Create an abstract class
2) Put everything in public methods which are common
3) Put everything in abstract methods which are specific to child classes

Where is the sample code?

Base class:

public abstract class BaseCeremony{

    Flag natonalFlag;
    Anthem anthem;

    //**** Common Task ******//
    public void startCeremony(){
        configure();
        hoistFlag();
        singAnthem();
    }

    public void hoistFlag(){
        natonalFlag.hoist();                       
    }

    public void singAnthem(){
        anthem.anthem();                       
    }

    private void configure(){
        natonalFlag = provideFlag();
        anthem = provideAnthem();
    }

    //**** Differs in all part ******//
    public abstract Flag provideFlag();
    public abstract Anthem provideAnthem();

}

In the child class, you just have to provide the implementation of the uncommon part.
ChildClass

public class IndianCeremony extends BaseCeremony{

       public Flag provideFlag(){
            return new IndianFlag();
       }

       public Anthem provideAnthem(){
            return new IndianAnthem();
       }
}

Bonus

  • An abstract class is an incomplete class that is why you can not create its objects.
  • An abstract class should have at least one abstract method to qualify as an abstract class
  • Example of abstract class implementation in Android


sample example for using abstract class in java.

package use_of_abstract;

abstract class Shapes 
{
   int i=1;

   abstract void draw();
   abstract void color(String mycolor);

   //not an abstract method
   void fill()
   {
      System.out.println("Non-Abstract Method -> Fill"); 
   }

   //not an abstract method
   String anotherMethod(String input) 
   {
       return input + " additional text";
   }

}

package use_of_abstract;

public class Shape_One extends Shapes 
{
    int i=1;

    @Override
    void draw() 
    {
        System.out.println("This is Shape One:"+i);
    }

    @Override
    void color(String mycolor) 
    {
        System.out.println("This is Shape One:"+mycolor);

    }

    @Override
    String anotherMethod(String anotherMethod) 
    {
        System.out.println("This is Shape One:"+anotherMethod);
        return anotherMethod;

    }

}

package use_of_abstract;

public class Shape_Two extends Shapes
{
    int i=2;

    @Override
    void draw() 
    {
        System.out.println("This is Shape Two :"+i);
    }

    @Override
    void color(String mycolor) 
    {
        System.out.println("This is Shape Two Color:"+mycolor);
    }

    @Override
    String anotherMethod(String anotherMethod) 
    {
        System.out.println("This is Shape Two:"+anotherMethod);
        return anotherMethod;

    }

}

package use_of_abstract;

import java.awt.Color;

public class Shape_Main 
{

    public static void main(String args[])
    {
        Shape_One s1;
        Shape_Two s2;

        s1=new Shape_One();
        s2= new Shape_Two();

        s1.draw();
        s2.draw();

        s1.fill();
        s2.fill();

        s1.color("Blue");
        s2.color("Green");


        s1.anotherMethod("HELLO..............Its Another Method 1");
        s2.anotherMethod("HELLO..............Its Another Method 2");


    }   
}


Abstract class, as its name suggest is abstract.

Abstract class doesn't talk about the implementation part. In fact, we extend the abstract class to provide the implementation for its abstract methods. It can also have non-abstract methods.

Check here : Use of Abstract Class in Java

EDIT :

Sample Code :

abstract class Shapes {

 int i=1;
 abstract void draw(); 

 // Remember : Non-abstract methods are also allowed 
 void fill() {
     System.out.println("Non abstract method - fill");
 }
}

class Shape1 extends Shapes {

 int i=1;
 void draw(){
 System.out.println("This is Shape 1:"+i);
 }
}

class Shape2 extends Shapes {
    int i=2;
    void draw() {
        System.out.println("This is Shape 2:"+i);
    }
}

class Shape {

public static void main(String args[])
       {
        Shape1 s1 = new Shape1();
        s1.draw();                     // Prints This is Shape 1:1

        Shape2 s2 = new Shape2();
        s2.draw();                     // Prints This is Shape 2:2
       }
  }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号