例3.12
JPerson.java
public class JPerson
{
static String name = "王五";
int age = 20;
String country = "中国";
public static void main(String args[])
{
JPerson s1 = new JPerson();
JPerson s2 = new JPerson();
JPerson s3 = new JPerson();
}
}
例3.13
JPerson2.java
public class JPerson2
{
static String name = "王五";
int age = 20;
String country = "中国";
public static String setName(String n)
{
name = n;
return name;
}
public void setValue(int age, String country)
{
this.age = age;
this.country = country;
}
}
例3.14
JStaticTest.java
public class JStaticTest
{
String testName;
public static void main(String args[])
{
JStaticTest s = new JStaticTest();
s.testName = JPerson2.name; // 类变量的调用
System.out.println("testName的值为 " + s.testName);
s.testName = JPerson2.setName("李四"); // 类方法的调用
System.out.println("JPerson2.name的值为 " + JPerson2.name);
System.out.println("现在testName的值为 " + JPerson2.name);
}
}
例3.15
JBook.java
public class JBook
{
public int id; // 书的编号
public static int bookNumber = 0; // 书的总数
public JBook()
{
++bookNumber;
}// JBook构造方法结束
public void info()
{
System.out.println("当前书的编号是:" + id);
} // 方法info结束
public static void infoStatic()
{
System.out.println("书的总数是:" + bookNumber);
} // 静态方法引用静态变量
public static void main(String args[])
{
JBook a = new JBook();
JBook b = new JBook();
a.id = 1101;
b.id = 1234;
System.out.print("变量a对应的");
a.info();
System.out.print("变量b对应的");
b.info();
JBook.infoStatic();
System.out.println("比较(a.bookNumber==Book.bookNumber)" + "的结果是:"
+ (a.bookNumber == JBook.bookNumber));
System.out.println("比较(b.bookNumber==Book.bookNumber)" + "的结果是:"
+ (b.bookNumber == JBook.bookNumber));
}
}
例3.16
JStaticUse.java
public class JStaticUse
{
static int a = 2;
static int b;
static
{
b = a * a;
a = 3;
}
public static void main(String args[])
{
JStaticUse s1 = new JStaticUse();
System.out.println("b的值为 " + b);
JStaticUse s2 = new JStaticUse();
System.out.println("b的值现在为 " + b);
}
}
注:本博客内容节选自高飞编著的Java程序设计实用教程 ,详细内容请参阅书籍。