非靜態(tài)內(nèi)部類隱試持有外部類的強(qiáng)引用糯景,此時(shí)內(nèi)部類可以隨意調(diào)用外部類中的方法和成員變量左胞。使用static定義的內(nèi)部類相對(duì)獨(dú)立担钮,不能訪問(wèn)外部類的非靜態(tài)成員暇榴,占用資源更少厚棵。
將viewHolder定義為static,可以將其與外部類解引用蔼紧,如果不定義為static婆硬,當(dāng)在viewHolder中執(zhí)行復(fù)雜的邏輯或者做一些耗時(shí)的操作,就容易出現(xiàn)內(nèi)存泄漏歉井。如果是static則不能使用外部類資源柿祈,也就避免了相互引用造成的內(nèi)存泄漏。當(dāng)然哩至,出現(xiàn)內(nèi)存泄漏的情況是比較少見的躏嚎。
主要是防止內(nèi)存泄漏,用static相當(dāng)于直接寫了一個(gè).java文件菩貌,與外部類沒有了依賴關(guān)系卢佣。
但是在stackoverflow答案卻是另外一回事:
If you declare the viewholder as static you can reuse it in other adapters. Anyway, I do not recommend to do it, create a new separated class and use it from multiple places, it does make more sense. One class for one purpose.
In the case of view holders, this classes will be only used inside the adapter, their instances should not go to the fragment or activity or elsewhere just by definition. This means having it static or non-static, in the case of view holders, is the same.
另一個(gè)類似的答案
By using static it just means you can re-use MyVh in other adapters. If you know for certain that you'll only need MyVh in that one adapter, then you should make it non-static.
If you will need it in other adapters it may even be better to just create it as a separate class entirely, rather than a nested class.
There should be no effects on performance for static vs non-static!
再說(shuō)明一下內(nèi)部類的使用:
不常用的語(yǔ)法:outer.new MyInner()
;
class MyOuter {
class MyInner {
}
}
void use() {
MyOuter outer = new MyOuter();
MyOuter.MyInner inner = outer.new MyInner();
}
public class MyOuter {
static class MyInner {
}
void use() {
//MyOuter outer = new MyOuter();
MyOuter.MyInner inner = new MyOuter.MyInner();
}
}