demo1文件夹
TelPhone
package demo1;
/*
*类和对象
*/
public class TelPhone {
float screen;
float cpu;
float mem;
void call(){
// 局部变量
int num = 0;
int mem = 66;
System.out.println("num: "+num);
System.out.println("mem: "+mem);
System.out.println("TelPhone 有打电话的功能");
}
void sendMessage(){
System.out.println("screen:" + screen +"\n TelPhone 有发短信的功能");
}
}
InitailTelPhone
package demo1;
public class InitailTelPhone {
public static void main (String[] args){
TelPhone phone = new TelPhone();
phone.call();
phone.screen = 0.2123f;
phone.sendMessage();
}
}
运行
demo2
TelPhone
package demo2;
/*
构造方法
*/
public class TelPhone {
float screen;
float cpu;
float mem;
// 无参数构造方法
// public TelPhone(){
// System.out.println("无参数构造方法");
// }
public TelPhone(float xScreen,float xCpu,float xMem){
if(xScreen > 100){
screen = xScreen;
}else{
screen = 0.25f;
System.out.println("参数有问题,改为默认值:" + screen);
}
screen = xScreen;
cpu = xCpu;
mem = xMem;
System.out.println("有参数构造方法");
}
}
InitailTelPhone
package demo2;
public class InitailTelPhone {
public static void main(String[] args){
// TelPhone phone = new TelPhone();
new TelPhone(50f,2.3f,16);
}
}
运行
static 使用之静态变量
public class HelloWorld {
// 定义静态变量,保存班级名称
static String className = "JAVA开发一班";
public static void main(String[] args) {
// 访问静态变量,输出班级名称
System.out.println(className);
}
}
static 使用之静态使用
package demo3;
public class Static {
static int num = 12;
int nums = 21;
public static void main(String[] args){
System.out.println(num);
Static hh = new Static();
System.out.println(hh.nums);
}
}
static 使用之静态初始化块
package demo3;
public class Static2 {
String name; // 声明变量name
String sex; // 声明变量sex
static int age;// 声明静态变量age
// 构造方法
public Static2() {
System.out.println("通过构造方法初始化name");
name = "tom";
}
// 初始化块
{
System.out.println("通过初始化块初始化sex");
sex = "男";
}
// 静态初始化块
static {
System.out.println("通过静态初始化块初始化age");
age = 20;
}
public void show() {
System.out.println("姓名:" + name + ",性别:" + sex + ",年龄:" + age);
}
public static void main(String[] args) {
// 创建对象
Static2 hello = new Static2();
// 调用对象的show方法
hello.show();
}
}