如何运行此代码?

时间:2013-03-18 00:35:26

标签: java

我试图运行此代码(在3个不同的类 - A,B和C中)并且它没有运行。我不知道为什么不。有人可以帮忙吗?

public class A {    

    private int number;
    protected String name;
    public double price;

    public A ( ) {
        System.out.println ( "A( ) called"); }

    private void foo1( ) {
        System.out.println( "A version of foo1( ) called"); }

    protected int foo2( ){
        System.out.println( "A version of foo2( ) called");
        return number; }

    public String foo3( ){
        System.out.println( "A version of foo3() called"); 
        return "Hi";            
    }
}

public class B extends A {

    private char service;

    public B ( ) {
        super( );

        System.out.println( "B( ) called"); }

    public void foo1 ( ) {
        System.out.println( "B version of foo1( ) called"); }

    protected int foo2 ( ){
        int n = super.foo2( );
        System.out.println( "B version of foo2( ) called");
        return ( n+5 ); }

    public String foo3 ( ) {
        String temp = super.foo3 ( );
        System.out.println( "B version of foo3( )");
        return ( temp + " foo3" ); } }

public class C extends B {

    public C( ){
        super( );
        System.out.println( "C( ) called"); }

    public void foo1 ( ) {
        System.out.println( "C version of foo1( ) called" );
    }
}

3 个答案:

答案 0 :(得分:2)

您没有main方法来指定程序的开头。您需要在其中一个类中使用以下签名创建main方法:

public static void main(String[] args)

答案 1 :(得分:2)

这样的事情应该允许你的程序运行

public static void main(String[] args)
{
    A a = new A();
    a.foo2();
    a.foo3();

    //same for B and C
}

答案 2 :(得分:0)

在同一个包中再添加一个类。例如,我创建了一个名为Application的类,如下所示:

  public class Application{
         public static void main(String []args){
                A a = new A();
                a.foo3();
                B b = new B();
                b.foo1();
                C c = new C();
                c.foo1();
         }
  }

然后,请尝试再次运行...