java中static关键字的使用--静态方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hju22/article/details/83876636

一、静态方法中只能有静态成员。

static修饰的方法可以被类直接调用,不需要new对象。所以static方法内部的变量和方法也是需要被类调用的,所以static方法内部的变量和方法都是static的。

package com.keyword.test;

/**
 * 静态方法内部只能出现静态成员(静态变量、静态方法)
 */
public class StaticFuntion {
    public static void main(String[] args) {
        Student stuA=new Student("张三");
        Student stuB=new Student("李四");
        Student.print();
    }
}
class Student{
    String name;
    static int age;
    Student(String name){
        this.name=name;
    }
    static void print(){
        System.out.println(age);  //相当于Student.age
        System.out.println(name); //Student.name?Student中的name有多个,就会让java不知道该使用哪一个
    }
        }

在这里插入图片描述

二、静态方法中不能出现this、super关键字

静态方法是针对类的,而this、super是针对对象的,所以不能出现这两个关键字

猜你喜欢

转载自blog.csdn.net/hju22/article/details/83876636
今日推荐