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中的函数