二、Java初级--6、访问修饰符和包

1、四种访问控制符:
default:不加控制符的时候,默认就是default,只能在同一个包内可以访问
private:私有的,封装的概念
public:公有的,可以公开调用
protected:在子类和本包中可见,当子类位于不同包中,也可以访问protected

新建class类:Dog

public class Dog {  
    public String name; 
    private int weight;  
    public void print(){
        System.out.println(name + ":" + weight);
    }
}
public class MyTest {
    public static void main(String[] args) {
        Dog d=new Dog();
        d.name="hello";
        d.print();
    }
}

执行结果

2、包的概念
package:用于对类或其它类型进行分类组织,如由很多个class组成一个包
通过import引入包中的类
类:第一个字母大写,如Job
变量名:第一个字母小写,如jobName


结构
package study;

public class Job {
    public String jobName;
    public void show(){
        System.out.println(jobName);
    }
}

MyTest类:

import study.*; //引入study包中的所有类
public class MyTest {
    public static void main(String[] args) {
        Job j=new Job();
        j.jobName="快递";
        j.show();
    }
}
执行结果

3、default概念
将show()定义为default,则只能在同一个包中引用


定义show为defalut

将MyTest类物理移动到study包中


同一个package

4、protected
在子类是可见的,即使在不同包中也是可见的


结构
package javastudy;

public class Person {
    protected String name;
    protected int height;
    public Person(){
        this.name="";
        this.height=0;
    }
    public Person(String name,int height){ //构造函数必须与类名相同,且不能有返回值,但不能加void
        this.name=name;
        this.height=height;
        }
    public void show()
    {
        System.out.println("姓名:"+name+"身高:"+height);
    }

}

package javastudy;

public class Student extends Person {
    private int score;
    public Student(){
        super("hello",190);
        score=70;
    }
    public Student(String name,int height,int score){
        super(name,height);
        this.score=score;
    }
    public void show(){
        System.out.println("你的名字是:" +name+ "身高是:" +height+ "得分:"+score);
    }
}
package javastudy;

public class testit {

    public static void main(String[] args) {
        Student t=new Student("zhang",180,90);
        t.show();
    }
}

上面是演示protected同一包中的子类可以访问,下面演示不同包中的子类可以访问


结构
package javastudy;

import study.children;

public class testit {

    public static void main(String[] args) {
        children c=new children();
        c.show();
    }
}

package study;

import javastudy.Person;

public class children extends Person {
    public void show(){
        System.out.println("这是一个小孩,姓名:"+name+ "身高"+height);
    }
}
执行结果
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,699评论 19 139
  • 一、Java 简介 Java是由Sun Microsystems公司于1995年5月推出的Java面向对象程序设计...
    子非鱼_t_阅读 9,814评论 1 44
  • importUIKit classViewController:UITabBarController{ enumD...
    明哥_Young阅读 9,452评论 1 10
  • 基于前几日我说想用清单来管理娃,那清单应该如何去做,我想起了以前在得到上听的《清单革命》,恰巧樊登老师也...
    瞳小甜Rosie阅读 4,233评论 0 0
  • 终于有了属于自己的一家店。真好! 交了房租和押金后。钱已所剩无几,便只好简单的布置了一番。没有钱做货柜,我就把用过...
    大張冰阅读 1,885评论 4 2