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