Java se - 实例方法,类方法

定义

实例方法:可以对当前对象的实例变量进行操作,也可以对类变量进行操作,由实例对象调用。
类方法:不能访问实例变量,只能访问类变量。由类名或者实例对象调用,不能出现this或者super关键字。

Demo

package com.lanjerry;

public class Demo0717 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        People p1=new People("小明",18,100);
        p1.show();
        People p2=new People("小明",18,200);
        p1.show();
        p2.show();
        p1.change(300);
        p1.show();
        p2.change(400);
        p1.show();
        p2.show();
    }

}

class People{
    String name;
    int age;
    static int weight;
    
    People(String name,int age,int weight)
    {
        this.name=name;
        this.age=age;
        this.weight=weight;
    }
    
    public void show()
    {
        System.out.println("name is:"+this.name+"  age is:"+this.age+" weight is:"+this.weight);
    }
    public static void change(int weight)
    {
        //this.weight=weight;//报错,内容:Cannot use this in a static context
        People.weight=weight;
    }
}
Result

name is:小明 age is:18 weight is:100
name is:小明 age is:18 weight is:200
name is:小明 age is:18 weight is:200
name is:小明 age is:18 weight is:300
name is:小明 age is:18 weight is:400
name is:小明 age is:18 weight is:400

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,779评论 18 399
  • 从三月份找实习到现在,面了一些公司,挂了不少,但最终还是拿到小米、百度、阿里、京东、新浪、CVTE、乐视家的研发岗...
    时芥蓝阅读 42,376评论 11 349
  • 1、.java源文件: 一个以”.java“为后缀的源文件:只能有一个与文件名相同的类,可以包含其他类。 2、类方...
    Hughman阅读 1,525评论 1 9
  • “ 风决定要走,云怎么挽留……”不知道是云恋着风,还是风追着云;飘动的云如白绵,云携清风游。夏天,阳光下草儿盈露,...
    踏足远行阅读 446评论 2 3
  • 01 大四的那个夏天,爷爷病重。我们全家都心情沉重,看着爷爷一天一天地消瘦,我们都清楚,爷爷的日子不多了。 五月的...
    乔木渥丹阅读 351评论 0 0