我的Java包中有四个类。只有一个类具有main()
方法。
当我运行main()
方法时,如何在类中运行四个类中的所有方法?
以下是我的课程:
Cat1.java
package test;
public class Cat1 {
public Cat1() {
System.out.println("100");
}
public Cat1(int i ){
i = 10;
System.out.println(" cat1 i :"+ i);
}
}
Cat2.java
package test;
public class Cat2 extends Cat1 {
public Cat2() {
System.out.println("200");
}
public Cat2(int i ){
super();
System.out.println("Cat 2 ; "+ i);
}
}
Cat3.java
package test;
public class Cat3 extends Cat2{
public Cat3() {
System.out.println("300");
}
public Cat3(int i){
super();
System.out.println("Cat 3 : "+ i);
}
}
Sample.java
package test;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Locale;
public class Sample {
/**
* @param args
*/
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
//Date d = cal.getTime();
Locale locale = new Locale("en");
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL, locale);
System.out.println(" LONg date : " + dateFormat.format(cal.getTime()));
String incomeData = "200,2,2,2,2";
int expense = 0;
String expenseSplit = incomeData;
System.out.println(" e");
String expenseArray[] = expenseSplit.split(",");
String income = expenseArray[0];
for (int i = 1; i < expenseArray.length; i++) {
expense = expense+Integer.parseInt(expenseArray[i]);
}
System.out.println(" Income "+ income);
System.out.println(" expense "+ expense);
}
}
答案 0 :(得分:0)
看起来你只是新对象并调用你需要的功能 比如
Cat3 cat3 = new Cat3();
或者你想在main()方法运行时自动调用吗?
答案 1 :(得分:0)
java是一种面向对象的语言,所以如果你不引用对象,它们就会坐在那里什么都不做。在main方法中,您可以将其视为可以创建对象的起点,并使用它们来访问它们的方法。
在main()方法中,您可以创建一些对象..
Cat1 sampleCat1 = new Cat1();
Cat1 anotherSampleCat1 = new Cat1(4);
答案 2 :(得分:0)
package test;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Locale;
public class Sample {
public static void main(String[] args) {
Cat1 cat1 = new Cat1(1);
Cat2 cat2 = new Cat2(2);
Cat3 cat3 = new Cat3(3);
Calendar cal = Calendar.getInstance();
//Date d = cal.getTime();
Locale locale = new Locale("en");
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL, locale);
System.out.println(" LONg date : " + dateFormat.format(cal.getTime()));
String incomeData = "200,2,2,2,2";
int expense = 0;
String expenseSplit = incomeData;
System.out.println(" e");
String expenseArray[] = expenseSplit.split(",");
String income = expenseArray[0];
for (int i = 1; i < expenseArray.length; i++) {
expense = expense+Integer.parseInt(expenseArray[i]);
}
System.out.println(" Income "+ income);
System.out.println(" expense "+ expense);
}
}