java static

一、静态属性(类属性)、静态方法(类方法)

类和对象都可以调用静态属性和方法,但推荐使用类调用

二、注意

1、静态属性和静态方法的加载顺序优先于构造方法

因此,成员方法可以使用静态属性和成员变量 ,静态方法只能使用静态属性

2、静态方法不能使用this,this代之对象

三、static块

static块在类第一次被使用是调用

例子

 1 package cn.wt.test;
 2 
 3 public class Student {
 4     private String name;
 5     private int age;
 6     static String isClass = "创造101";
 7 
 8     static {
 9         System.out.println("使用static块");
10     }
11 
12     public Student() {
13     }
14 
15     public Student(String name, int age) {
16         this.name = name;
17         this.age = age;
18     }
19 
20     public String getName() {
21         return name;
22     }
23 
24     public void setName(String name) {
25         this.name = name;
26     }
27 
28     public int getAge() {
29         return age;
30     }
31 
32     public void setAge(int age) {
33         this.age = age;
34     }
35 
36     public static String introduce(){
37 //        System.out.println(age);
38         return "我的班级是" + isClass;
39     }
40 
41     public void isShow(){
42         String str = "大家好,我叫" + this.name + ",我今年" + this.age
43                 + "岁。我的班级是" + isClass;
44         System.out.println(str);
45     }
46 }
Student.java
 1 package cn.wt.test;
 2 
 3 import javax.sound.midi.Soundbank;
 4 
 5 public class Demon01 {
 6     public static void main(String[] args) {
 7 //        Student stu1 = new Student("杨过", 18);
 8         String introduce = Student.introduce();
 9         System.out.println(introduce);
10         System.out.println(Student.isClass);
11 
12 //        Student stu2 = new Student("小龙女", 38);
13 //        System.out.println("姓名:" + stu1.getName() + ",年龄:" + stu1.getAge() + "班级:" + Student.isClass);
14 //        System.out.println("姓名:" + stu2.getName() + ",年龄:" + stu2.getAge() + "班级:" + Student.isClass);
15 
16 //        String isIntro = Student.introduce();
17 //        System.out.println(isIntro);
18 //        stu1.isShow();
19 //        stu2.isShow();
20 
21     }
22 }
Demon01
posted @ 2020-01-16 22:58  市丸银  阅读(135)  评论(0编辑  收藏  举报