課程
/后端開發
/Java
/Java入門第二季 升級版
可以吧構造方法和主函數寫在一個類中嗎?
2017-02-23
源自:Java入門第二季 升級版 8-6
正在回答
可以。
例子:
public class Example{
int example1; ? ? ? ? ? ? ?//成員變量
String example2; ? ? ? ?//成員變量
Example(int a,String b){ ? ? ?//構造方法給兩個成員變量賦值
example1 = a;
example2 = b;
}
public void show(){ ? ? ? ? ? ?//普通的公有方法展示出兩個成員變量的值
System.out.println("example1:"+example1);
System.out.println("example2:"+example2);
public static void main(String args[]){ ? ? ? ? ? ? ? ? ? ? ? //主函數
Example one = new Example(1,"This is a Example"); ? ? ? ? ? //調用了Example這個類的構造方法
one.show();
在例子中我的主函數就是和構造方法放在同一個類里面,不過我在主函數里面生成了這個類的對象,所以系統自動調用了構造方法。
可以啊
piblic class Animal(){
public int age ; ? ?
public Animal(int a){
????age = a;
public static void main(String []args){
????Animal dog = new Animal(12);
主函數就是一種靜態方法,所以構造方法和靜態方法可以放在一個類中的
???
舉報
課程升級!以終為始告別枯燥,在開發和重構中體會Java面向對象編程的奧妙
4 回答構造方法的使用
3 回答構造方法的使用
5 回答構造方法的構造
2 回答構造方法的作用
3 回答怎樣選擇使用一般方法或構造方法
Copyright ? 2025 imooc.com All Rights Reserved | 京ICP備12003892號-11 京公網安備11010802030151號
購課補貼聯系客服咨詢優惠詳情
慕課網APP您的移動學習伙伴
掃描二維碼關注慕課網微信公眾號
2017-02-23
可以。
例子:
public class Example{
int example1; ? ? ? ? ? ? ?//成員變量
String example2; ? ? ? ?//成員變量
Example(int a,String b){ ? ? ?//構造方法給兩個成員變量賦值
example1 = a;
example2 = b;
}
public void show(){ ? ? ? ? ? ?//普通的公有方法展示出兩個成員變量的值
System.out.println("example1:"+example1);
System.out.println("example2:"+example2);
}
public static void main(String args[]){ ? ? ? ? ? ? ? ? ? ? ? //主函數
Example one = new Example(1,"This is a Example"); ? ? ? ? ? //調用了Example這個類的構造方法
one.show();
}
}
在例子中我的主函數就是和構造方法放在同一個類里面,不過我在主函數里面生成了這個類的對象,所以系統自動調用了構造方法。
2017-02-23
可以啊
piblic class Animal(){
public int age ; ? ?
public Animal(int a){
????age = a;
}
public static void main(String []args){
????Animal dog = new Animal(12);
}
}
2017-02-23
主函數就是一種靜態方法,所以構造方法和靜態方法可以放在一個類中的
2017-02-23
???
2017-02-23
可以。