Java面向对象上-作业

1.创建一个Test类,包含有一个public权限的int型成员变量与一个char类型的成员变量,观察在main方法中的初始值。

public class Test{
    	public static int n1;
        public static char n2;
        public static void main(String[] args){
        System.out.println(n1);
        System.out.println(n2);
        }
}

结果输出:n1=0
                  n2=a

2.编写一个程序,展示无论你创建了某个特定类的多少个对象,这个类的某个特定的static成员变量只有一个属性。

public class Test{
    	public static void main(String[] args){
		Person per1 = new Person();		
        per1.name="Joey";		
        Person per2 = new Person();		
        per2.name="Jashua";		
        per1.country="CHINA";		
        per1.printInformation();		
        per2.printInformation();        	        
    }
}
class Person{		
    String name;		
    static String country="USA";				
    public void printInformation(){			
        System.out.println("name:"+this.name+"国籍:"+this.country);		
    }
}


3.一个斐波那契数列是由数字1、1、2、3、5、8、13、21、34等等组成的,其中每一个数字(从第三个数字起)都是前两个数字的和。创建一个方法,接受一个整数参数,并显示从第一个元素开始总共由该参数指定的个数所构成的所有斐波那契数字。例如,如果运行 java Fibonacci 5(Fibonacci为类名),那么输出应该是1、1、2、3、5。

public class Fibonacci{
	public static void main(String[] args){
		if(args.length<0){
			System.out.println("没有传参");
		}		
                else{
			int n=Integer.parseInt(args[0]);
			for(int i=1;i<=n;i++){
				System.out.print(fibonacci(i)+",");
		        }
		    }
                }
        public static int fibonacci(int args){
	    if(args<=1){
		    return args;
	    }
	    else{
		    return fibonacci(args-1)+fibonacci(args-2);
	    }
        }
}


4.创建一个带默认构造方法(即无参构造)的类,在构造方法中打印一条消息"Hello Constructor";再为这个类添加一个重载构造方法,令其接收一个字符串参数,并在这个有参构造方法中把"Hello Constructor"和接收的参数一起打印出来。

public class Test{	
    public static void main(String[] args){		
    Hallo hal=new Hallo();		
    Hallo hal1=new Hallo("略略略");	
    }
}
class Hallo{
	public Hallo(){
	System.out.println("Hello Constructor");
	}
        public Hallo(String x){	
	System.out.println("Hello Constructor"+x);
	}
}

猜你喜欢

转载自blog.csdn.net/qq_41268108/article/details/83048485