如何定义抽象类

时间:2011-12-02 07:49:16

标签: java

我们如何在java中定义抽象类?

用于它的原型是什么?

请提供一个示例,为清楚起见,我是java的新手。

感谢。

4 个答案:

答案 0 :(得分:2)

abstract class AbstractTestClass { 
    protected String myString; 

    public String getMyString() { 
        return myString; 
    } 

    public abstract string anyAbstractFunction();
}

有关详细信息,请参阅link

答案 1 :(得分:0)

请参阅以下示例,它可以帮助您

import java.util.*;

// Provider framework sketch
public abstract class Foo {
    // Maps String key to corresponding Class object
    private static Map implementations = null;

    // Initializes implementations map the first time it's called
    private static synchronized void initMapIfNecessary() {
        if (implementations == null) {
            implementations = new HashMap();

            // Load implementation class names and keys from
            // Properties file, translate names into Class
            // objects using Class.forName and store mappings.
            // ...
        }
    }

    public static Foo getInstance(String key) {
        initMapIfNecessary();
        Class c = (Class) implementations.get(key);
        if (c == null)
            return new DefaultFoo();

        try {
            return (Foo) c.newInstance();
        } catch (Exception e) {
            return new DefaultFoo();
        }
    }

    public static void main(String[] args) {
        System.out.println(getInstance("NonexistentFoo"));
    }
}

class DefaultFoo extends Foo {
}

答案 2 :(得分:0)

一般来说:

public abstract class SomeClass
{
    // A pure virtual function
    public abstract void PureVirtual();

    // A regular \ virtual function
    public String SomeFunction(String arg)
    {
        return arg;
    }
}

答案 3 :(得分:0)

public abstract class AbstractMyClass {

    // declare fields
    int part1 = 4;
    int part2 = 5;

    //declare non abstract mehots with some code
    @Override
    public String toString() {
        return part1.toString() + part2.toString();
    }


    //declare abstract methods without code (like in an interface)
    abstract void compute();
}

这是如何设置抽象类的示例。有关详细信息,请访问:http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html