zoukankan      html  css  js  c++  java
  • Java 访问修饰符

    class Telphone{
      private float screen=5.0f;
      private float cpu=1.4f;
      private float mem=2.0f;
      public float getScreen(){
        return screen;
      }
      public float setScreen(float newScreen){
        screen=newScreen;
    }
    //其他getter/setter方法 }

    蓝色体为访问修饰符

    作用:可修饰属性和方法的访问范围

     同包:指在一个路径下

    访问修饰符  本类  同包  子类  其他

    private     √

    默认      √   √

    protected      √     √     √

    public      √   √     √     √

    class Telphone{

    private float screen;    //若将“private”改为“public”,

    private float cpu;

    private float mem;

    public void sendMessage(){

    System.out.println("sendMessage");

    }

    public float getScreen(){

    return screen;

    }

    public void setScreen(float screen){

    this.screen=screen;    //为了区分属性和参数名,所以在参数名前+this,意思为:将参数的值赋给当前对象的属性

    this.sendMessage();    //调用当前对象的方法

    }

    public float getCpu(){

    return cpu;

    }

    public void setCpu(float cpu){

    this.cpu=cpu;

    }

    public float getMem(){

    return mem;

    }

    public void setMem(float mem){

    this.mem=mem;

    }

    public Telphone(){

    System.out.println("无参的构造方法执行了");

    }

    public Telphone(float newScreen,float newCpu,float newMem){

    if(newScreen<3.5f){

    System.out.println("输入的数据错误");

    screen=3.5f;

    }

    cpu=newCpu;

    mem=newMem;

    System.out.println("有参的构造方法执行了");

    }

    }

    class Ex17{

    public static void main(String[] args){

    Telphone phone2=new Telphone(1.5f,1.4f,2.0f);

    //若将“private”改为“public”,则在此添加 “phone2.screen=6.0f;” 不会报错

    System.out.println("screen:"+phone2.getScreen());

    }

    }

  • 相关阅读:
    Spring 注解@Component,@Service,@Controller,@Repository
    HttpServlet service方法
    Intellij Idea生成serialVersionUID的方法
    创建数据库池实战
    代理模式
    基于SOA架构的TDD测试驱动开发模式
    服务治理要先于SOA
    简述我的SOA服务治理
    SOA服务类项目开发模式
    oracle容器化docker解决方案
  • 原文地址:https://www.cnblogs.com/chenyuan7/p/8082735.html
Copyright © 2011-2022 走看看