gpt4 book ai didi

java - 类图中的public、protection、private的作用是什么?有什么例子吗?

转载 作者:行者123 更新时间:2023-12-02 02:42:16 27 4
gpt4 key购买 nike


我一直对访问修饰符很好奇。

public 表示该项目可供有权访问该对象的任何人使用,

protected 意味着它可供对象本身和任何子类使用,并且

private 表示只能在类本身内访问。

但是,我不知道公共(public)、 protected 和私有(private)用例的示例。
我的意思是,有人可以向我解释类图上公共(public)、私有(private)和 protected 访问修饰符的情况吗?
只是为了确保我正确理解它们。

谢谢!

最佳答案

确切地说,访问类型不仅有3种,在不同的语言中还有更多。
例如:

  1. public – 使用此访问修饰符定义的类或其成员可以从任何地方公开访问,甚至可以从类的范围之外访问。
  2. private – 具有此关键字的类成员将在类本身内访问。它通过类实例的引用来保护成员免受外部类的访问。
  3. protected – 与 private 相同,只不过允许子类访问 protected 父类(super class)成员。
  4. abstract – 该关键字只能用于 PHP 类及其函数。为了包含抽象函数,PHP 类应该是抽象类。
  5. final – 它防止子类覆盖使用final关键字定义的父类(super class)成员。
  6. 内部 - 可以在包含其声明的程序内访问,也可以在同一程序集级别内访问,但不能从另一个程序集访问。
  7. protected 内部 - protected 和内部的访问级别相同。它可以访问同一程序集中的任何位置,也可以访问同一类中从同一类继承的类

其中一些适用于类,一些适用于函数,还有一些也适用于变量。
因此,在大多数语言中,所有类成员都使用 public 访问类型声明(例如,Java 除外)。

回到主要问题。
所有这些访问修饰符的应用都是为了方便组件的封装。

在 C++ 中使用此类访问修饰符的简单示例 ( taken from here ):

#include <iostream>
#include<conio.h>
using std::cout;
using std::endl;

struct B { // default access modifier inside struct is public
void set_n(int v) { n = v; }
void f() { cout << "B::f" << endl; }
protected:
int m, n; // B::m, B::n are protected
private:
int x;
};

struct D : B {
using B::m; // D::m is public
int get_n() { return n; } // B::n is accessible here, but not outside
// int get_x() { return x; } // ERROR, B::x is inaccessible here
private:
using B::f; // D::f is private
};

int main() {
D d;

// d.x = 2; // ERROR, private
// d.n = 2; // ERROR, protected
d.m = 2; // protected B::m is accessible as D::m

d.set_n(2); // calls B::set_n(int)
cout << d.get_n() << endl; // output: 2

// d.f(); // ERROR, B::f is inaccessible as D::f


B& b = d; // b references d and "views" it as being type B

// b.x = 3; // ERROR, private
// b.n = 3; // ERROR, protected
// b.m = 3; // ERROR, B::m is protected

b.set_n(3); // calls B::set_n(int)
// cout << b.get_n(); // ERROR, 'struct B' has no member named 'get_n'

b.f(); // calls B::f()
return 0;
}

因此,要了解此修饰符的用途,首先必须了解面向对象编程的核心原理,尤其是封装范例。
这不是可以通过示例代码轻松解释的事情。
修饰符只是庞大的 OOP 世界的一小部分。

关于java - 类图中的public、protection、private的作用是什么?有什么例子吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45253116/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com