如何以及何时使用抽象类

发布于 2024-11-06 23:41:32 字数 500 浏览 4 评论 0原文

这是我用Java编写的测试程序。我想知道抽象类在这里有多重要以及为什么我们为此使用抽象类。

这是强制性的还是最好的方法;如果是这样怎么办?

class Shape1 {
    int i = 1;
    void draw() {
        System.out.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();
    }
}

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.out.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();
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

转瞬即逝 2024-11-13 23:41:32

您可以在此处使用抽象类或接口,以便创建提供 void draw() 方法的公共基类/接口,例如

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

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

...

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

我通常会使用接口。但是,如果满足以下条件,您可以使用抽象类:

  1. 您需要/想要提供通用功能或类成员(例如,您的情况下的 int i 成员)。
  2. 您的抽象方法具有除公共访问(这是接口允许的唯一访问类型)之外的任何内容,例如,在我的示例中,void 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.
水波映月 2024-11-13 23:41:32

抽象类是至少有一个未实现的方法或关键字abstract 的类。例如,一个抽象方法可能如下所示:

public abstract String myMethod(String input);

(注意该方法以分号结尾)。

以及一个类可能看起来像这样:

public abstract class MyClass {

    public abstract String myMethod(String input);

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

抽象类无法实例化。抽象类需要一个子类来实现缺失的行为,以便可以实例化它。

抽象类的主要目标是提供公共行为的共享实现 - 促进代码的重用。

在 Java 中,通过使用类的组合而不是从广泛定义的抽象继承,可以实现相同的效果类。这允许更多模块化、功能特定的类促进代码重用,从而提高可维护性。

我的建议是仅在绝对必要时才使用抽象类,特别是避免将其用作充满各种功能的技巧包。

在 Scala 中,人们会使用特征,这是解决这个问题的一种优雅的方式。然而,它确实需要大量的关注才能顺利通过。

编辑:从 Java 8 开始,接口中的默认方法是添加常见行为的另一种方法。

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.

梦冥 2024-11-13 23:41:32

抽象类与您的子类具有“is-a”类型关系。例如,您可以有一个抽象类 Shape,其中包含任何形状所具有的内容(如绘图函数),然后是一个类 SquareShape。每个正方形都是一个形状,但并非所有形状都是正方形。

在您的示例中,您有 2 个形状类型,以及一个具有 2 个实例的类。我认为这不是你应该用abstract定义的关系。

不过,您可能想对您的名字做一些事情,因为这是一个相当小的示例,很难看出这些文件的真正含义以及它们应该如何工作。

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.

淡墨 2024-11-13 23:41:32

常见的东西+不常见的东西=抽象类

什么时候使用?

抽象类最适合有大量可重用代码的场景,您不想一次又一次地编写这些代码+每个类都有一些特定的内容。

例子?

仪式:

常见的事情:唱国歌、升旗等
具体内容:印度国旗、印度国歌(印度)、中国国旗、中国国歌(中国)等

在此处输入图像描述

如何使用?

1)创建抽象类
2)将所有内容放在常用的公共方法中
3)将所有内容放入特定于子类的抽象方法中

示例代码在哪里?

基类

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

}

在子类中,您只需提供不常见部分的实现即可。
ChildClass

public class IndianCeremony extends BaseCeremony{

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

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

优点

  • 抽象类是一个不完整的类,这就是为什么你不能创建它的对象。
  • 抽象类应该至少有一个抽象方法才有资格成为抽象类
  • Android

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.

enter image description here

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
相守太难 2024-11-13 23:41:32

在 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");


    }   
}

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


    }   
}
霞映澄塘 2024-11-13 23:41:32

抽象类,顾名思义就是抽象的。

抽象类不讲实现部分。事实上,我们扩展了抽象类以提供其抽象方法的实现。它也可以有非抽象方法。

检查此处:在 Java 中使用抽象类

编辑:

示例代码:

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

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
       }
  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文