TIJ第二章部分习题 P89-90

package thinking_in_java_2;

public class P1 {
	
	static int a;
	static char c;

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("c = "+c);
		System.out.print("a = "+a);
		
	}

}
package thinking_in_java_2;

class ATypeName{
	/*class body goes here*/
	int a;
	int b;
}

public class P2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ATypeName a = new ATypeName();   
		a.a=1;
		a.b=2;
	}
	
}
package thinking_in_java_2;

//方法在类里面 
//e.g.show方法在DataOnly类里;
//    main方法在P4类里

class DataOnly{           
	//定义类的成员
	int i;
	double d;
	boolean b;
	//定义类的方法
	void show(){
		System.out.printf("i=%d,d=%f,b=%s",i,d,b);
	}
}

public class P4 {
	public static void main(String[] args) {
		DataOnly a = new DataOnly();
		a.i=1;
		a.b=true;
		a.d=1.1;
		a.show();
	}
}
package thinking_in_java_2;

public class P6 {

	public static void main(String[] args) {
		//在main外定义一个单纯的方法并调用(类似于c的子函数)
		String a="ds";
		System.out.println(storage(a));
	}
	
	static int storage(String s){
		return s.length()*2;
	}

}
package thinking_in_java_2;

//The method increment cannot be declared static
//static methods can only be declared in a static or top level type

//使用类名是引用static变量的首选方式
class StaticTest{
	static int i = 47;
}

class Incrementable{
	static int increment(){
		//使用类名是引用static变量的首选方式
		//当然也可以用对象.i这样子
		return StaticTest.i++;
	}
}

public class P7 {
	public static void main(String[] args) {
		StaticTest st1= new StaticTest();
		StaticTest st2= new StaticTest();
		System.out.printf("st1=%d,st2=%d",st1.i,st2.i);
		Incrementable sf= new Incrementable();
		System.out.printf("\n对象访问static int i=%d,类名访问static int i=%d(因为i在前面对象访问时已经变成48了[先用再加]虽然没有显示出来)",sf.increment(),Incrementable.increment());
	}
}

主要分清了类和方法到底该放哪里就很开心~

类作为类的放

目前的菜鸡水平暂时不考虑把类嵌套起来

方法放在类中

比如人类会吃饭

人类就是类;吃饭就是人类这个类的一个方法(功能)

Java中的方法可理解为C中的函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值