简体   繁体   English

class在Java和C++中默认是private还是public?

[英]Is a class private or public by default in Java and C++?

Are classes private or public by default in Java and C++? Java 和 C++ 中的类默认是私有的还是公共的?

  • Java : Java

    By default, the classes visibility is package private, ie only visible for classes in the same package. 默认情况下,类可见性是包私有的,即仅对同一包中的类可见。

  • C++ : C ++

    The class has no visibility defined like in Java. 该类没有像Java那样定义的可见性。 They are visible if you included them to the compilation unit. 如果将它们包含在编译单元中,它们是可见的。

In Java, a top-level class is either public or non-public. 在Java中, 顶级类是公共类或非公共类。 There is no "private". 没有“私人”。 You can only use the public keyword or leave it off. 您只能使用public关键字或将其关闭。 If you leave it off it is non-public, ie, visible only to other classes in the same package. 如果您将其关闭,则它是非公开的,即仅对同一包中的其他类可见。

A nested class, that is, a class inside of another class, can be made public, package-private, protected, or private, just like any other class member. 嵌套类,即另一个类中的类,可以像其他任何类成员一样成为public,package-private,protected或private。 The default (ie, the one with no modifier) is package-private, visible only to classes in the same package. 默认值(即没有修饰符的那个)是包私有的,仅对同一包中的类可见。

EDIT: Forgot the C++ answer, so see (and upvote) @zeller's answer. 编辑:忘了C ++答案,所以看看(和upvote)@ zeller的答案。 :) :)

According to §6.6.1 of the JLS , 根据JLS的§6.6.1

If a top level class or interface type is not declared public, then it may be accessed only from within the package in which it is declared. 如果顶级类或接口类型未声明为public,则只能从声明它的包中访问它。

So, a Java class is by default package-private . 因此,Java类默认是package-private

This doesn't apply to C++, however. 但是,这不适用于C ++。 A class lacks visibility -- only its members can have access control. 一个类缺乏可见性 - 只有其成员才能拥有访问控制权。 See §11 of the C++11 standard for information on member access control. 有关成员访问控制的信息,请参阅C ++ 11标准的第11节。 Here's an excerpt from ¶1... 这是¶1的摘录......

A member of a class can be 一个班级的成员可以

  • private ; private that is, its name can be used only by members and friends of the class in which it is declared. 也就是说,它的名称只能由声明它的类的成员和朋友使用。
  • protected ; protected that is, its name can be used only by members and friends of the class in which it is declared, by classes derived from that class, and by their friends (see 11.4). 也就是说,它的名称只能由声明它的类的成员和朋友,从该类派生的类以及他们的朋友使用(见11.4)。
  • public ; public that is, its name can be used anywhere without access restriction. 也就是说,它的名称可以在没有访问限制的任何地方使用。

while you use whatever any top level oop Languages like Java, C# it's obey: Class are private as default Objects are private as default Methods are public as default当您使用任何顶级 oop 语言,如 Java、C# 时,它遵守: Class 默认为私有 对象默认为私有 方法默认为公共

Java Java

By default Java class is package-private.默认情况下 Java class 是包私有的。

C++ C++

In C++ there is no visibility defined like Java.在 C++ 中没有像 Java 这样定义的可见性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM