定义一个类:
class Person {
public int age;//成员属性 实例变量
public String name;
public String sex;
public void eat() {//成员方法,实例成员函数
System.out.println("吃饭!");
}
public void sleep() {
System.out.println("睡觉!");
}
}
public class Main{
public static void main(String[] args) {
Person person = new Person();//通过new实例化对象
person.eat();//成员方法调用需要通过对象的引用调用
person.sleep(); //产生对象 实例化对象
Person person2 = new Person();
Person person3 = new Person();
}
}
static关键字
class TestDemo{
public int a; 实例变量,存放于对象
public static int count; //静态变量,存放在方法区
public static void change() { //静态成员函数
count = 100; //a = 10; error 不可以访问非静态数据成员
}
}
public class Main{
public static void main(String[] args) {
TestDemo t1 = new TestDemo();
t1.a++;
TestDemo.count++;
System.out.println(t1.a);
System.out.println(TestDemo.count); //无需实例化对象,可直接调用
System.out.println("============");
TestDemo t2 = new TestDemo();
t2.a++;
TestDemo.count
System.out.println(t2.a);
System.out.println(TestDemo.count);
TestDemo.change();//可直接调用
System.out.println(TestDemo.count);
}
}
输出结果:
1
1
===========
1
2
100
总结:所有被static所修饰的方法或者属性,全部不依赖于对象。
getter和setter方法 以及 构造方法
class Person {
private String name;//实例成员变量 封装
private int age;
public void setName(String name){
//name = name;//不能这样写
this.name = name;//this 当前对象的引用
}
public String getName(){
return name;
}
/*public Person(){ //不带参数的构造方法
this.name = "cocao";
}
public Person(String name , int age){//带两个参数的构造方法
this.name = name;
this.age = age;
}*/
public void show(){
System.out.println("name: "+name+" age: "+age);
}
}
class main{
public static void main(String[] args) {
Person person = new Person();
person.setName("caocao"); //设置这个成员的值
System.out.println(person.getNeme()); //获取这个成员的值
person.show();
/* Person person = new Person();//调用不带参的构造方法
person.show();
Person person1 = new Person("dsoknov",9);//调用带参的构造方法
person1.show();*/
}
}
运行结果 caocao name: caocao age: 0
//name: cocao age: 0
//name: dsoknov age: 9
=============================================
class{
private String name;
private int age;
private String sex;
public Person() { //*this()调用构造函数*
this("bit", 12, "man");//**必须放在第一行进行显示**
} //这两个构造函数之间的关系为重载。
public Person(String name,int age,String sex) {
this.name = name;
this.age = age;
this.sex = sex;
public void show(){
System.out.println("name:"+name+"age:"+age+"sex:"+sex);
}
}
}
public class Main{
public static void main(String[] args) {
Person person = new Person();//调用不带参数的构造函数
person.show();
}
}
// 执行结果 name: bit age: 12 sex: man
代码块:
class{
private String name;
private int age;
private static int count;
//静态代码块 -》 初始化静态的数据成员
static {
count = 88888888;
System.out.println("静态代码块");
}
//实例代码块--》初始化实例数据成员
{
this.age = 10000;
this.name = "哪吒";
//count = 9999;
System.out.println("实例代码块");
}
}
//执行顺序:静态代码块==》实例代码块==》构造方法