java 什么时候用静态类,关于java:我什么时候想让我的私有类静态?

一般来说,将私有类声明为静态类有什么好处吗?

在什么情况下,我想使用下面的一个而不是另一个?

private static class Foo

{

...

}

VS

private class Foo

{

...

}

Java内部类和静态嵌套类可能是有用的。

您可以在本文中找到第二个有用的答案:stackoverflow.com/questions/1844355/java-static-class

我认为这是一个很好的起点:http://java67.blogspot.fi/2012/10/nested-class-java-static-vs-non-static-inner.html

1) Nested static class doesn't need reference of Outer class but non

static nested class or Inner class requires Outer class reference. You

can not create instance of Inner class without creating instance of

Outer class. This is by far most important thing to consider while

making a nested class static or non static.

2) static class is actually static member of class and can be used in

static context e.g. static method or static block of Outer class.

3) Another difference between static and non static nested class is

that you can not access non static members e.g. method and field into

nested static class directly. If you do you will get error like"non

static member can not be used in static context". While Inner class

can access both static and non static member of Outer class.

这应该是公认的答案。

但是,我们已经使用了private,它仍然可以访问吗?

它只能在嵌套类内部访问,而不能作为嵌套类的私有对象访问外部世界。

如果需要访问封闭类的成员变量/方法,请使用非静态形式。如果没有,请使用静态形式。

这是个糟糕的答案。即使从静态类中,如果我得到对父类对象的引用,我也可以访问私有成员。

但你为什么要这么做?如果您需要访问私有变量,并且它是一个内部类,那么只需将其设置为非静态的,而不是将其设置为静态的,并将引用传递给父类。

它们是不同的概念。非静态(即内部)类对父类的对象具有隐式引用。所以,如果没有父类的对象,就不能有内部类的对象。例如map.entry(或更好的迭代器)——它需要引用父映射对象。静态嵌套类的一个例子是builder,它需要访问父类的私有构造函数。

但是这些类(例如map.entry)不是私有的。手术室询问了私人班级的情况。

@JeffStorey,也许接口不是私有的,但是实现是可能的,并且很好地进行私有/保护。也就是说,当您说mylist.getIterator()时,您得到了一些私有或受保护的迭代器iface的实现。

是的,你是对的。

我假设你指的是内类。

我认为动机来自于你想如何将你的内心阶层联系起来。如果希望内部类与外部类的特定实例相关联,则使用private class,否则使用private static class。

我敢肯定,private和"inner"类是同义词。

我发现在一般抽象类中有一个特定的异常非常有用。即。:

public abstract class AbstractClass

{

private void doSomethingOrThrowException() throws SpecificException

{

....

if ( ! successful)

{

throw new SpecificException();

}

}

private static class SpecificException extends Exception {}

}

如果我不考虑静态的话,编译器会给我一个错误,说明:The generic class AbstractClass.SpecificException may not subclass java.lang.Throwable。

静态类与普通类的区别仅仅在于它们可以在不创建实例的情况下被访问。因此,如果每次都需要一些类可访问,请使用static

我不认为他问什么是静态类。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值