我正在阅读J.Bloch的EffectiveJava,现在我正在阅读继承与组合部分。据我所知,他说继承并不总是好的。Arelatedcauseoffragilityinsubclassesisthattheirsuperclasscanacquirenewmethodsinsubsequentreleases.Supposeaprogramdependsforitssecurityonthefactthatallelementsinsertedintosomecollectionsatisfysomepredicate.Thiscanbeguaranteedbysubclassingt
我有一个类,它有一个默认情况下访问说明符是公共(public)的方法。现在,我想在子类中扩展这个类,我想重写这个方法以获得访问说明符“private”。编译此代码时,出现编译错误:"attemptingtoassignweakeraccessprivileges".有人可以向我解释在子类中分配较弱的权限有什么问题吗?这是导致编译错误的代码:classSuperclass{voidfoo(){System.out.println("Superclass.foo");}}classSubclassextendsSuperclass{privatevoidfoo(){System.out.p
我在摆弄AspectJ并想出了一个我似乎无法正确实现的想法(我的生活故事)。我已经定义了一个方面:packagemy.package;importorg.aspectj.lang.annotation.*;importorg.aspectj.lang.ProceedingJoinPoint;@AspectpublicclassMyAspect{@Pointcut("execution(**(..))&&this(o)")publicvoidinstanceMethod(Objecto){}@Pointcut("within(@Marker*)")publicvoidmethodsFro
我有以下代码。classTest{inti=0;Test(){System.out.println(this);System.out.println(this.i);}}publicclassDemoextendsTest{inti=10;Demo(){super();System.out.println("callingsuper");System.out.println(this);System.out.println(this.i);}publicstaticvoidmain(String[]args)throwsIOException{Demod=newDemo();}}O/P
我将要创建一个工厂,它创建某种类型T的对象,它扩展了某个类A和另一个接口(interface)I。但是,T一定是未知的。以下是最低限度的声明:publicclassA{}publicinterfaceI{}这是工厂方法:publicclassF{publicstaticTnewThing(){/*...*/}}编译一切正常。当我尝试使用以下方法时,效果很好:A$a=F.newThing();...虽然这不是:I$i=F.newThing();编译器提示:Boundmismatch:ThegenericmethodnewThing()oftypeFisnotapplicableforth
请引用以下Java代码:classBase{Base(){System.out.println("BaseConstructor");method();}voidmethod(){}}classDerivedextendsBase{intvar=2;Derived(){System.out.println("DerivedConstructor");}@Overridevoidmethod(){System.out.println("var="+var);}}classTest2{publicstaticvoidmain(String[]args){Derivedb=newDerive
假设我们有下一种情况:父类A:classA{publicA(){}publicdoSomething(){System.out.println(this.getClass());}}有一个子类B:classBextendsA{publicB(){}publicvoiddoSomething(){super.doSomething();System.out.println(this.getClass());}}和主类:classMain{publicstaticvoidmain(String[]args){Aab=newB();ab.doSomething();}}当我执行这段代码时结果
我有这样的类(class):MyClassextendsMyAbstractClassimplementmyInterface1,myInterface2,...我需要创建带有附加字段的新类:MyType1field1;MyType2field2;.......似乎正确创建将包装MyClass的新类,如下所示:MyWrapClass{MyClassmyClass=newMyClass(...);MyType1field1;MyType2field2;.....但是MyWrapClass用作myInterface1或myInterface2类型!所以问题是:我是否应该在MyWrapCla
事实1:Javadoesnotsupportmultipleinheritance.事实2:Objectisasuperclassofallotherclasses如果我有一个Parent类和一个继承Parent类的Child类:classParent{}classChildextendsParent{}在这种情况下,如果Java不支持多重继承,Child类将如何继承Object类?这三者之间的关系是如何定义的?选项1:选项2: 最佳答案 这是选项2。如果您定义一个父类(superclass),那将是您的类的直接父类(supercl
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭7年前。ImprovethisquestionJ.Bloch在他为Java6编写的EffectiveJava中提到了以下内容(第17项):Ifyoufeelthatyoumustallowinheritancefromsuchaclass,onereasonableapproachistoensurethattheclassneverinvokesanyofitsoverridablemethodsandtodocumentthisf