(1)构造方法
- 构造方法:对对象的数据进行默认初始化;
- 格式:
方法名与类名相同;
没有返回值类型,没有viod;
没有具体的返回值; - 如果我们没有给出构造方法,系统会自动提供一个无参构造方法;
- 如果我们给出了构造方法,系统将不再提供默认的无参构造方法,就必须给出无参构造方法;
/*
类的组成:
成员变量
构造方法
成员方法
*/
class Student{
private String name;
private int age;
public Student(){}//无参构造方法
public Student(String name,int age){//可以同时带一个或多个参数
this.name=name;
this.age=age;
}
/*
给成员变量赋值有两种方式:
setXxx();方法
构造方法
*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
(2)static关键字
- 针对多个对象有共同的的成员变量值的时候,java就提供了一个关键字来修饰:static;
class Person{
String name;
int age;
static String country;//国籍使用static修饰
public Person(String name,int age,String country){
this.name=name;
this.age=age;
this.country=country;
}
public Person(String name,int age){
this.name=name;
this.age=age;
}
public void show(){
System.out.println("姓名:"+name+"年龄:"+age+"国籍:"+country);
}
}
class PersonDemo {
public static void main(String[] args) {
Person p1 = new Person("小花",16,"中国");
p1.show();
Person p2 = new Person("小红",17);//会自动显示中国
p2.show();
Person p3 = new Person("小名",18);//会自动提示中国
p3.show();
}
}
- 可以修饰成员变量和成员方法;
- static关键字特点:
随着类的加载而加载,优先于对象存在;
被被类的所有对象共享;
可以通过对象调用,有可以通过类名调用; - 在静态方法中没有this关键字
静态是随着类的加载而加载,this是随着对象的创建而存在,静态比对象先存在; - 静态方法只能访问静态的成员变量和静态的成员方法;
- 非静态方法可以访问非静态的成员变量和成员方法,也可以访问静态的成员变量和成员方法;
class Demo{
public int num=10;
public static int num2=20;
public void function(){
}
public static void function()2{
}
public void show(){
System.out.println(num); //隐含的告诉你访问的是成员变量
System.out.println(this.num); //明确的告诉你访问的是成员变量
System.out.println(num2);//访问静态的成员变量
function();
function2();
}
public static void method(){
//无法从静态上下文中引用非静态 变量 num
//System.out.println(num);报错
System.out.println(num2);
//无法从静态上下文中引用非静态 方法 function()
//function();报错
function2();
}
}
(3)静态变量和成员变量的区别
- 所属不同:
静态变量属于类,所以也称为类变量;
成员变量属于对象,所以也称为实例变量(对象变量); - 内存中位置不同
静态变量存储于方法区的静态区;
成员变量存储于堆内存; - 内存出现时间不同:
静态变量随着类的加载而加载,随着类的消失而消失;
成员变量随着对象的创建而存在,随着对象的消失而消失; - 调用方法不同
静态变量可以通过类名调用,也可以通过对象调用;
成员变量只能通过对象名调用。