半路出家——Java中的访问权限控制

Java中的访问权限控制


本人打杂匠一个,在未定的心性下不断的尝试学习新的东西,若有不对,忘各位大神不吝赐教。不以为耻,反以为荣

我们先来复习一下传统的C++访问权限:

//
//  Parent.h
//  rightsTest
//
//  Created by qing mo on 9/8/15.
//  Copyright (c) 2015 chaos. All rights reserved.
//

#ifndef rightsTest_Parent_h
#define rightsTest_Parent_h
#include <iostream>
#include <string>

class Parent
{
public:
    Parent(int id, std::string name);

private:
    int id;
    std::string name;

public:

    int getId(void) const { return this->id; }
    void setId(int newId) { this->id = newId; }

    std::string getName(void) const { return this->name; }
    void setName(std::string newName) { this->name = newName; }

};

#endif
//
//  Person.h
//  rightsTest
//
//  Created by qing mo on 9/8/15.
//  Copyright (c) 2015 chaos. All rights reserved.
//

#ifndef rightsTest_Person_h
#define rightsTest_Person_h
#include "Parent.h"


class Person : public Parent
{
private:
    std::string title;
public:
    Person(int id, std::string name, std::string title);
    std::string toString() const;

};

#endif
//
//  Person.cpp
//  rightsTest
//
//  Created by qing mo on 9/8/15.
//  Copyright (c) 2015 chaos. All rights reserved.
//
#include <iostream>
#include <string>
#include "Person.h"

Person::Person(int id, std::string name, std::string title):
Parent(id, name), title(title)
{

}

std::string Person::toString() const
{
    return this->getName() + this->title;
}

这里Person类不能直接访问父类中的private成员name。
而且有一个比较核心的——C++中默认的访问权限是private
接下来,我们看看Java,由于我是半路出家,基础十分不牢固,今天就闹了大笑话。
A.java

package cn.javass.spring.chapter3;

public class A {
    private int id;
    String name;

    public A(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

B.java

package cn.javass.spring.chapter3;

public class B extends A {

    String title;

    public B(int id, String name, String title) {
        super(id, name);
        this.title = title;
    }

    public String toString() {
        return name + title;
    }

    public static void main(String[] args) {
        B b = new B(2, "lvzi", "master");
        System.out.println(b.toString());
    }
}

这里就是Java与C++的一个区别点,如果不注意的过渡过去,可能永远不会知道,Java的默认访问权限是包保护
C++访问权限

访问控制 当前类 子类 其他类
public
protected x
private x x

Java访问权限

访问权限 当前类 相同包中的子类 不同包中的子类 相同包中的其他类 不同包中的其他类
public
protected x
private x x x x
默认 x x

由此可以看出Java多出来的一个默认包保护权限是十分灵活的。但是如果一旦不注意,就会默认为是第一张表的权限控制,而忽略的对数据封装隐藏的目的。

猜你喜欢

转载自blog.csdn.net/eagleqingluo/article/details/48301269