怎樣寫main函數并求出結果?
package stty;
public class imooc1{
??? String name="愛慕課";
??? static String hobby="imooc";
??? public static void print(){
?? ??? ?imooc1 Hy=new imooc1();
?? ??? ?System.out.println("歡迎您"+Hy.name);
?? ??? ?System.out.println("愛好"+hobby);
?? }
??? public void print1(){
?? ??? ?System.out.println("歡迎您"+name);
?? ??? ?System.out.println("愛好"+hobby);
??? }
}
2017-04-16
因為print方法是靜態(tài)方法,所以可以不用創(chuàng)建對象,直接用類名就可以訪問這個靜態(tài)方法。
靜態(tài)方法不能直接訪問非靜態(tài)變量,需要通過創(chuàng)建對象訪問(這是對我自己說的)
2017-04-16
package com.imooc;
public class imooc{
? ?String name="愛慕課";
? ?static String hobby="imooc";
? ?public static void print(){
? ? ? ?imooc Hy=new imooc();
? ? ? ?System.out.println("static歡迎您"+Hy.name);
? ? ? ?System.out.println("static愛好"+hobby);
? ?}
? ?public void print1(){
? ? ? ?System.out.println("歡迎您"+name);
? ? ? ?System.out.println("愛好"+hobby);
? ?}
? ?public static void main(String args[]){
? ? ? ?// call the static method
? ? ? ?imooc.print();
? ? ? ?imooc myImooc = new imooc();
? ? ? ?myImooc.print1();
? ?}
}
2017-04-16
package com.imooc;
public class Imooc1 {
? ?String name="愛慕課";
? ?static String hobby="imooc";
? ?public static void print(){
? ? ? ?Imooc1 Hy=new Imooc1();
? ? ? ?System.out.println("歡迎您"+Hy.name);
? ? ? ?System.out.println("愛好"+hobby);
? }
? ?public void print1(){
? ? ? ?System.out.println("歡迎您"+name);
? ? ? ?System.out.println("愛好"+hobby);
? ?}
? ?public static void main(String[] args) {
? ? ? ?
? ? ? ?// 創(chuàng)建對象
? ? Imooc1 Hy=new Imooc1();
// 調用對象的show方法
? ? ? ?Hy.print();
? ? ? ?Hy.print1();
}
}
2017-04-16
第五行開始是寫靜態(tài)方法,接下來三行錯了,方法里面只能有變量聲明和方法定義,那三行就是main方法里要寫的。