Abstract class & final class

Which is more correct... Or which is the more preferred way.
abstract class A
  final method1(){}
  final method2(){}
  final method30(){}
}or
final class A
  private A(){}
  method1(){}
  method2(){}
  method3(){}
}My understanding is that both classes cannot be instantiated. The first one requires writing 'final' for EACH method. The second one involves writing a private constructor.

It depends on what you are trying to do. If you are trying to make a class that can be sub-classed but has some methods that cannot be overriden, then "abstract class A" with final methods is the way to go. If you want a class that cannot be sub-classed or instantiated then "final class A" with private constructor is the way to go.
classes cannot be instantiatedOnly true for "final class A" because you made the only constructor private. Not true for the abstract one.// you forgot return values for the methods
abstract class A
  final static /*void*/ method1(){}  // package private
  final static /*void*/ method2(){}  // package private
  final static /*void*/ method30(){} // package private
// this would work
A a = new A(){};
// if I am in the same package as A, then this would work
a.method1();
// or this
public class B extends A
  public B(String whatever)
    // Although, I cannot override the super methods
    // becuase they are all declared as final
    // I can only invoke them if I am in the same package.  You
    // declared them as package private instead of class "private"
}Using final as a class modifier disables the ability to sub-class it but does not disable the ability to create an object of that class. You must make a private constructer. If the only constructor is "private" then you can't subclass or instantiate, so making the class final is uneeded.

Similar Messages

  • Why class builder allows to develop abstract final class ? What is the use of such class in ABAP?

    I am new to ABAP. I tried creating abstract class and found that class builder allows development of abstract final class. What is the use of such class in ABAP?

    Hi,
    Does not compile:
    This one do:
    Inheritance:
    Regards.

  • Casting & abstract class & final method

    what is casting abstract class & final method  in ABAP Objects  give   some scenario where  actually  use these.

    Hi Sri,
    I'm not sure we can be any more clear.
    An Abstract class can not be instantiated. It can only be used as the superclass for it's subclasses. In other words it <b>can only be inherited</b>.
    A Final class cannot be the superclass for a subclass. In other words <b>it cannot be inherited.</b>
    I recommend the book <a href="http://www.sappress.com/product.cfm?account=&product=H1934">ABAP Objects: ABAP Programming in SAP NetWeaver</a>
    Cheers
    Graham

  • Question  about Abstract,Final Class

    when we are using final keyword along with class definition .we are making that class final, means we can’t extend that class. The same thing happens when we make our constructors private. From usability perspective both are same ? or is there any difference?
    Secondly accounting to java syntax a class can be either final or abstract and not both .Then why language specification doesn't impose any restriction on making abstract classes constructor private. We can create an Abstract class with private Constructor (Basically utility class with all methods are static) ,to make this class Singleton .This situation is equal to abstract final class ?
    Thanks,
    Paul.

    EJP wrote:
    when we are using final keyword along with class definition .we are making that class final, means we can’t extend that class. The same thing happens when we make our constructors private.No it doesn't.
    Secondly accounting to java syntax a class can be either final or abstract and not both.Correct.
    Then why language specification doesn't impose any restriction on making abstract classes constructor private.Why should it? That proposition doesn't follow from your previous sentence.I think OP is asking about this case
    public abstract class WTF {
      private WTF() {}
      private WTF(...) {}
    }where the class is abstract and all the c'tors are final. It's an abstract class that cannot be extended, much like a final abstract class would be if it were allowed. So, since purpose of abstract classes is to be extended, the OP seems to be asking, "Why can we, in this fashion, create an abstract class that cannot be extended?"
    I don't know the answer to that, but I would guess that, while final is an explicit syntactical element for the purpose of making a class non-extensible, in the all-private-c'tors case, the non-extensibility is simply a side effect, and probably enough of a corner case that it wasn't worth the effort to explicitly forbid it in the spec.
    I also think it's something not worth thinking much about. It was certainly not a key point of some grand design.

  • What are the uses of declaring a class "final"?

    Can any one please tell me the uses of declaring a class "final"?
    I know that final classes cannot be extended. Other than this,
    Is there any thing that will improve the compiler time for the final classes?

    compiler performance is utterly unimportant anyway...
    If the compiler takes too long, just get a faster build system :)

  • Abstract method and class

    I'm a beginner in Java and just learn about abstract method and class.
    However, i am wondering what is the point of using abstract method/class?
    Because when I delete the abstract method and change the class name to public class XXXX( changed from "abstract class XXXX), my program still runs well, nothing goes different.
    Is it because I haven't encountered any situation that abstract method is necessary or ?
    Thanks!

    Yes - you probably haven't encountered a situation where you need an abstract.
    Abstract classes are not designed to do anything on their own. They are designed to provide a template for other classes to extend by inheritance. What you have build sounds like a concrete class - one which you are creating instances of. Abstract classes are not designed to be ever instantiated in their pure form - they act like a partial building block, which you will complete in a class which extends the abstract.
    An example might be a button class, which provides some core functionality (like rollover, rollout etc) but has an empty action method which has to be overwritten by a relevant subclass like 'StartButton'. In general, abstract classes may not be the right answer, and many people would argue that it is better to use an interface, which can be implemented instead of extended, meaning that you can ADD instead of REPLACING.
    Not sure if that helps.. there are whole chapters in books on this kind of thing, so it's hard to explain in a couple of paragraphs. Do some google searches to find out more about how they work.

  • Overidding a method defined in a Final class via an interface.

    Hi,
    Is it possible to override methods of a final class
    which has implemented methods of an interface.
    interface A{
         void method1();     
    public final class FinalityA implements A{
         public void method1(){
              // Code
    }Now,I would like to override the functionality of
    method1() defined in class FinalityA.
    I cannot subclass FinalityA as this class is final.
    // Invalid.
    class Myclass extends FinalityA{
    }Is it possible to override the functionality defined in method1()
    Please suggest

    You can do:
    public class MyClass implements A {
       private final FinalityA _wrapee;
       public MyClass(FinalityA wrapped) {
           _wrapee = wrapped;
      public void method1() {
           .. do some special processing
          _wrapee.method1();
           .. do some more stuff
            }If you want to get really clever you can do stuff with java.lang.reflect.Proxy that allows you to automatically pass on calls to interface methods (this kind of thing is increasingly used for stuff like transaction management).
    What you can't do is to fiddle with the code of the method if called from a reference to FinalityA rather than a reference to the interface. The whole point of final classes and methods is to prevent that.

  • Java.lang.VerifyError: Cannot inherit from final class

    Hi i am trying to call a crystal report from jsp but i am getting this error
    error:-
    org.apache.jasper.JasperException: Cannot inherit from final class
         org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:460)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:355)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:329)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    root cause
    javax.servlet.ServletException: Cannot inherit from final class
         org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:841)
         org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:774)
         org.apache.jsp._1_jsp._jspService(_1_jsp.java:95)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:98)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:331)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:329)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    root cause
    java.lang.VerifyError: Cannot inherit from final class
         java.lang.ClassLoader.defineClass1(Native Method)
         java.lang.ClassLoader.defineClass(Unknown Source)
         java.security.SecureClassLoader.defineClass(Unknown Source)
         org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:1853)
         org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:875)
         org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1330)
         org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1209)
         java.lang.ClassLoader.loadClassInternal(Unknown Source)
         com.crystaldecisions.reports.sdk.ReportClientDocument.open(Unknown Source)
         org.apache.jsp._1_jsp._jspService(_1_jsp.java:64)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:98)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:331)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:329)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    my jsp is
    <%@ page import="com.crystaldecisions.report.web.viewer.*" %>
    <%@ page import="com.crystaldecisions.sdk.occa.report.data.*"  %>
    <%@ page import="com.crystaldecisions.reports.sdk.ReportClientDocument" %>
    <%
        Object reportSource = session.getAttribute("reportSource");
        if (reportSource == null)
           String report = "report.rpt";
           ReportClientDocument reportClientDoc = new ReportClientDocument();
           reportClientDoc.open( "report.rpt", 0);
           reportSource = reportClientDoc.getReportSource();
           session.setAttribute("reportSource", reportSource);
        CrystalReportViewer viewer = new CrystalReportViewer();
        viewer.setReportSource(reportSource);
           viewer.setEnableLogonPrompt(false); 
        viewer.setOwnPage(true);
        viewer.processHttpRequest(request, response, getServletConfig().getServletContext(), null);
    %>
    and in my WEB-INF/lib i included jar files namely
    Concurrent.jar,CrystalCharting.jar,CrystalCommon.jar,CrystalContentModels.jar,CrystalExporters.jar,CrystalExportingBase.jar,CrystalFormulas.jar,CrystalQueryEngine.jar,CrystalReportEngine.jar,CrystalReportingCommon.jar,icu4j.jar,jrcerom.jar,keycodeDecoder.jar,log4j.jar,MetafileRenderer.jar,rasapp.jar,rascore.jar,rpoifs.jar,serialization.jar,URIUtil.jar,xml-apis.jar,xbean.jar,xercesImpl.jar,webreporting.jar,webreporting-jsf.jar
    please help me

    You can't inherit from a final class. 
    So - are you trying to inherit from a final class?
    Sincerely,
    Ted Ueda

  • Final method and final class

    What is final method and final class in abap objects.

    ejp wrote:
    Since that doesn't work--or would overyy complex to implement... would be impossible to implement. Once the method-local copy goes out of existence, ipso facto it can never be changed. This is the whole point.I consider it impossible too, but I'm not a language/compiler/runtime expert, so I allowed for the possibility that there could be some way to do it--e.g. local variables that are references in inner classes live on the heap instead of the stack, or something. My point isn't that it's possible, just that if it were somehow to be done, it would by ugly, so we may as well consider it impossible--it just ain't gonna happen.
    we go with the logic, "Okay, we need to copies, but keeping them in sync is a nightmareNo, it is +meaningless.+No, it's not meaningless. If we have the two copies, and they're not final, then after the inner object is created, the method can continue running, and either the method or the inner object could modify its copy. As far as our code knows, it's the same variable, so there'd have to be some way to keep them in sync. That's either impossible or undesirably complex--like the above, it doesn't matter which--so it's final in order to get past the issue of keeping the copies in sync.

  • Abstract Classes & Interface Classes

    Dear members of the Sun Community
    My studies are progressing and just 1 period ago we started doing Object-Orinted Programming in Java and I must say I'm quite fond of it. It's become quite clear that OOP is an important aspect of Programming and just can't be missed. We've learned about Inheritance, Polymorfism, Mutators, Inspectors, Uses-Relationships and everything else however now I've come to the point where I got a problem:
    Up until now we have been using normal classes to work with in which you could create objects and in your main program create objects from that class however. We've just learned about Abstract and Interface classes. As far as I'm concerned I'm quite confused with both of them.
    If I am not mistaken (please correct me if I'm wrong) Abstract classes are classes from which you cannot create an object but is only used to make a subclass inherit everything from this superclass.
    I am not quite sure what Interface classes are as they just plain confuse me. Would anyone be so kind to maybe explain what all of this is ?
    Thanks a whole bunch
    Herazio

    Funny enough that already solved the question !
    Thank you so much for the quick reply ^^
    Herazio

  • Final class CL_PT_EMPLOYEE. Why?

    Today I tried to make a local class as a sub class to CL_PT_EMPLOYEE and found out that this class was defined as a final class.
    Does any one have an idea why the class CL_PT_EMPLOYEE has been defined as a final class. Is that to stop any re-use of SAP code. Any one from SAP?
    (P.S. Please dont over exert yourself in explaining the meaning of a final class to me)

    Hello Ahsan,
    Sorry if I wasn't clear, this is an example of sarcasm. The use of the word "apparently" should have given it away, and particularly the exaggeration "untold harm" was supposed to convey the impression that I do not believe this for one minute.
    This is just what I was told by OSS, it was about two years ago and there were several conversations back and forth, some by telephone. Basically, by allowing us to create a subclass we would be able to redefine a superclass method and... well, I am not quite sure what the risk is to be honest, but SAP seemed to think this was a dangerous tool to let loose upon us customers. It was the type of response that is under discussion in this thread:
    A (disbelieving) question regarding the OSS
    As others have a really suggested, composition is the answer and usually a better technique.
    The only time when you should need to create a subtype of a standard SAP class is if you have to use polymorphism to feed your own version of an SAP class to something else that expects a particular class as input. This is the <sarcasm>"risky" part by which we could damage the system according to OSS</sarcasm>, yet is quite commonly used in workflow. In the BOR world they even provided a neat feature called delegation (basically a reverse inheritance) to accomplish this.
    Cheers,
    Mike
    Edited by: Mike Pokraka on Sep 2, 2008 5:59 PM - clarification

  • Interface cast to final class

    Read in a book saying that an interface object cannot be cast to a final class object. See the following:
    final class Apple { }
    interface Squeezable{ }
    class Citrus implements Squeezable{ }In this case then:
    Squeezable sq = new Citrus();
    Apple apple = (Apple)sq; // compile errorOf course there are two fixes for the compile error.
    (1) Make Apple implement Squeezable (this is easy to understand).
    (2) Make Apple a non-final class (although there will be a runtime exception).
    Can anybody tell me why it won't compile when Apple is a final class? What's going on behind the scene with the compiler here? Thanks!

    senore100 wrote:
    Thanks for all your reply. Well, actually the compiler should know that the actual object is a Citrus. No, it shouldn't. It doesn't become a Citrus obejct until runtime. The compiler only looks at the reference type on the left side of the =, not what's happening on the right side.
    What if instead of new, it was Squeezeable sq = squeezableFactory.createSqueezeable(); It could return any class that implements Squeezeable.
    Now, you could try to argue that it should at least do it for new, when it knows what the class will be. But there's really no point for that, and it would just complicate the language by adding special cases.

  • How do I redefine a Method of a Final Class?

    Hi,
    Is it possible to redefine a method of a final class and if so, can someone please give me a brief example of that technique?
    Thank you very much!
    Andy

    Hi,
    Please find the example.
    Program Description :      Interface I1 contains two methods : M1 and M2.
    I1 is included and incorporated in class : C1 with M2 as a final method. Both the methods are implemented in class C1.
    Class C2 is a subclass of class C1. It redefines method : I1M1 and re-implements it, but it does not do that for I1M2 as that is declared as final method.
    In the START-OF-SELECTION block, object OREF1 is created from class C1 and OREF2 from class C2 and both the methods M1 and M2 are called using both the objects.
    Example:
    report ytest .
    interface i1 .
      methods : m1 ,
                m2 .
    endinterface.
    class c1 definition.
      public section.
       interfaces : I1 final methods m2 .
    endclass.
    class c1 implementation.
      method i1~m1.
       write:/5 'I am m1 in c1'.
      endmethod.
      method i1~m2.
       write:/5 'I am m2 in c1'.
      endmethod.
    endclass.
    class c2 definition inheriting from c1.
      public section.
       methods : i1~m1 redefinition .
    endclass.
    class c2 implementation.
      method : i1~m1.
       write:/5 'I am m1 in c2'.
      endmethod.
    endclass.
    start-of-selection.
      data : oref1 type ref to c1,
             oref2 type ref to c2 .
       create object : oref1 , oref2.
       call method  : oref1->i1~m1 , u201C Output : I am m1 in c1
                      oref2->i1~m1 , u201C Output : I am m1 in c2
                      oref1->i1~m2 , u201C Output : I am m2 in c1
                      oref2->i1~m2 . u201C Output : I am m2 in c1
    Output :      I am m1 in c1 
    I am m1 in c2 
    I am m2 in c1 
    I am m2 in c1 
    Thanks,
    Anitha

  • Jsp : Cannot inherit from final class

    hi, i have big problem.
    when i call a class using xml(DOM,SAX,...) in my jsp page, i get an error message:
    org.apache.jasper.JasperException: Cannot inherit from final class
    i don't understand why?
    help me please!!!

    Try replacing xercesImpl.jar under %Tomcat_Home%/common/endorsed with the one included with Xalan-Java.

  • Clientgen Exception - java.lang.VerifyError:Cannot inherit from final class

    When i create a client jar from webservice ear the ant taks fails with compiler errors, such as:
    CreateProxy:
    [clientgen] Generating client jar for earname.ear(WebServiceName_WS) ...
    BUILD FAILED
    java.lang.VerifyError: Cannot inherit from final class
    at java.lang.ClassLoader.defineClass0(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:539)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123)
    at weblogic.utils.classloaders.GenericClassLoader.findLocalClass(GenericClassLoader.java:480)
    at weblogic.utils.classloaders.GenericClassLoader.findClass(GenericClassLoader.java:182)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:289)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:235)
    at weblogic.utils.classloaders.GenericClassLoader.loadClass(GenericClassLoader.java:224)
    at weblogic.webservice.server.WebServiceFactory.loadNonArrayClass(WebServiceFactory.java:1318)
    at weblogic.webservice.server.WebServiceFactory.loadClass(WebServiceFactory.java:1293)
    at weblogic.webservice.server.WebServiceFactory.initTypeMaps(WebServiceFactory.java:384)
    at weblogic.webservice.server.WebServiceFactory.createFromMBean(WebServiceFactory.java:184)
    at weblogic.webservice.tools.build.internal.WSDLGenImpl.getWebServiceRuntime(WSDLGenImpl.java:240)
    at weblogic.webservice.tools.build.internal.WSDLGenImpl.run(WSDLGenImpl.java:135)
    at weblogic.webservice.tools.build.internal.ClientGenImpl.doClientGenFromEAR(ClientGenImpl.java:438)
    at weblogic.webservice.tools.build.internal.ClientGenImpl.run(ClientGenImpl.java:345)
    at weblogic.ant.taskdefs.webservices.clientgen.ClientGenTask.doClientGen(ClientGenTask.java:351)
    at weblogic.ant.taskdefs.webservices.clientgen.ClientGenTask.execute(ClientGenTask.java:208)
    at org.apache.tools.ant.Task.perform(Task.java:341)
    at org.apache.tools.ant.Target.execute(Target.java:309)
    at org.apache.tools.ant.Target.performTasks(Target.java:336)
    at org.apache.tools.ant.Project.executeTarget(Project.java:1339)
    at org.apache.tools.ant.Project.executeTargets(Project.java:1255)
    at org.apache.tools.ant.Main.runBuild(Main.java:609)
    at org.apache.tools.ant.Main.start(Main.java:196)
    at org.apache.tools.ant.Main.main(Main.java:235)
    Total time: 25 seconds
    This is a ant command:
    <clientgen ear="${build}/earname.ear" onlyConvenienceMethod="true" warName="webservice.war" serviceName="WebServiceName_WS" packageName="my.package.webservices.generated" autotype="true" clientJar="${build.dist}/client/WebServiceName_WS.jar" overwrite="false" useServerTypes="true" keepGenerated="false" generateAsyncMethods="false" saveWsdl="true" j2me="false" useLowerCaseMethodNames="true" typePackageName="my.package.webservices.generated" usePortNameAsMethodName="false" />
    My webservice do not include any final class.
    I'm using WebLogic 8.1 SP4.Is there a solution for above problem?
    Thanks.
    Regards.

    Hi all,
    I m also facing quite similar problem.
    I have one sample JMX program, which i want to collect data from weblogic 9.2.
    but when i compile sample program on jdk 1.4 and run it on JDK 1.4 it throws following exception
    java.lang.VerifyError: class weblogic.utils.classloaders.GenericCl
    assLoader overrides final method .
    ERROR 02/13 09:54:03 Stderr 700100 at java.lang.ClassLoader.defineClass0(Native Method)
    ERROR 02/13 09:54:03 Stderr 700100 at java.lang.ClassLoader.defineClass(Unknown Source)
    ERROR 02/13 09:54:03 Stderr 700100 at java.security.SecureClassLoader.defineClass(Unknown Source)
    ERROR 02/13 09:54:03 Stderr 700100 at java.net.URLClassLoader.defineClass(Unknown Source)
    ERROR 02/13 09:54:03 Stderr 700100 at java.net.URLClassLoader.access$100(Unknown Source)
    ERROR 02/13 09:54:03 Stderr 700100 at java.net.URLClassLoader$1.run(Unknown Source)
    ERROR 02/13 09:54:03 Stderr 700100 at java.security.AccessController.doPrivileged(Native Method)
    ERROR 02/13 09:54:03 Stderr 700100 at java.net.URLClassLoader.findClass(Unknown Source)
    ERROR 02/13 09:54:03 Stderr 700100 at java.lang.ClassLoader.loadClass(Unknown Source)
    ERROR 02/13 09:54:03 Stderr 700100 at java.lang.ClassLoader.loadClass(Unknown Source)
    but sample program works fine if i run it on JDK 1.5..
    can someone tell me...wats reason?
    Thanks
    Nihil

Maybe you are looking for

  • Upgrade disk space storage in a 8 GB iPod Nano (6th generation)?

    Hello. Is there a way to upgrade/replace an old sixth generation iPod Nano's 8 GB disk storage to 16 GB like with computers? Or do I have to buy a new one? Thank you in advance.

  • Ora-00353

    Dear All, when I m going to recover dataguard then I receive following error. ORA-00283: recovery session canceled due to errors ORA-00368: checksum error in redo log block ORA-00353: log corruption near block 6144 change 1368965150 time 01/03/2009 0

  • Data Access Error when importing Standard Reports

    After installation, when I try to import standard reports, I got a "Data Access Error". FDM 9.3.1 Oracle 10g In the fdm.err, I find the following description: ORA-12899 : too long value for "MYFDMSCHEMA"."TREPORT"."REPORTDESC" (real 152, max 75). It

  • PS CS4 Error: Could not build preview because of a disk error

    I have been using this version of Photoshop without any problems for about two years, and then I upgraded to OS X Lion last week and now I get a disk error when I try to save a file.  The message says "Photoshop could not build preview because of a d

  • MVC Framework

    Hi, We're working with the MVC Framework. The personnel application is running very good. But when we try to create our own application and have a problem. We use Rational Rose to generate the service xml file and it works good when we use standard p