![](/img/trans.png)
[英]How to prevent a class from being inherited outside the library, while being inherited by public classes?
[英]how to prevent class 'a' from being inherited by another class?
我有一個名為fdetails
的類,我不希望任何其他類從這個類繼承。
我可以將它設置為不被另一個類繼承嗎? 我想用以下 3 種語言完成這項工作:
java: final
vb: NotInheritable (NonOverrideable for properties)
c#: sealed
在 Java 中使用 final 關鍵字:
public final class fdetails{
}
在 C# 中使用 Sealed 關鍵字:
public sealed class fdetails{
}
在 VB.net 中使用 NotInheritable 關鍵字:
public notinheritable class fdetails
end class
在 C# 中,您使用sealed
關鍵字來防止類被繼承。
在 VB.NET 中,您使用NotInheritable
關鍵字。
在 Java 中,您使用關鍵字final
。
在 JAVA 中 - 使用 final 關鍵字:
public final class FDetails
在 C# 中 - 密封關鍵字:
sealed class FDetails
為了防止C#中的類被繼承,使用了關鍵字sealed。 因此密封類不能作為任何其他類的基類。 同樣明顯的是,密封類不能是抽象類。 下面的代碼...
//C# Example
sealed class ClassA
{
public int x;
public int y;
}
任何類都不能從上面定義的 ClassA 繼承。 可以創建 ClassA 的實例,然后可以訪問它的成員,但是下面的代碼是不可能的......
class DerivedClass : ClassA { } // Error
在 Java 和 VB.net 中相同:
java: final
vb: NotInheritable (NonOverrideable for properties)
替代https://stackoverflow.com/a/4096427/5292885答案,可以使用私有構造函數創建基類以避免繼承(在 C# 中,您會收到錯誤,例如該類由於其保護級別而無法訪問,以防萬一參考基類)
對於 C#,它是“密封”關鍵字。
對於 Java,它是“final”關鍵字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.