如何编写包含此代码的main函数的类?

时间:2014-02-20 13:47:05

标签: java

public class Soldier
{
     private String soldierName;              
     public void setSoldierName( String name )      
     {                                             
        SoldierName = name;
     }
     public String getSoldierName()        
     {                                    
        return soldierName;                
     }
     public void displayMessage()
     {
        System.out.printf( "The name of \n%s!\n",
           getSoldierName() );
     }
}

1 个答案:

答案 0 :(得分:2)

如果您只想让课程采用main方法,只需将其添加到任何其他课程中即可:

public class Soldier
{
     private String soldierName;              
     public void setSoldierName( String name )      
     {                                             
        SoldierName = name;
     }
     public String getSoldierName()        
     {                                    
        return soldierName;                
     }
     public void displayMessage()
     {
        System.out.printf( "The name of \n%s!\n",
           getSoldierName() );
     }
     public static void main(String args[]) {
     }

}

要在main中实际执行有用的操作,您可能需要在其中创建类的实例,设置士兵名称,然后调用displayMessage()方法。像这样:

     public static void main(String args[]) {
         Soldier soldier = new Soldier();
         soldier.setSoldierName("John");
         soldier.displayMessage();
     }