Using Abstract Class Methods

I just want to know that in how many ways can we use the non abstract methods of the class without extending the class(dont want to implement all abstract methods of the parent class).One way is that if the methods are static then we can use CLASSNAME.METHODNAME().Is their any other way of doing it

none at all. not a single one. by definition, a non-static method has to be invoked on a particular instance of a class, and an abstract class cannot be instantiated. somebody is probably going to say you can do this:
abstract class AbstractClass {
  abstract void minceAbout();
  void talkRubbish() {
     // do stuff
new AbstractClass() {
    void minceAbout() {}
}.talkRubbish();but that is extending the AbstractClass, no matter what their argument. why d'you ask, anyway? why not implement the methods? sounds like a design smell

Similar Messages

  • When to use abstract classes instead of interfaces with extension methods in C#?

    "Abstract class" and "interface" are similar concepts, with interface being the more abstract of the two. One differentiating factor is that abstract classes provide method implementations for derived classes when needed. In C#, however,
    this differentiating factor has been reduced by the recent introduction of extension methods, which enable implementations to be provided for interface methods. Another differentiating factor is that a class can inherit only one abstract class (i.e., there
    is no multiple inheritance), but it can implement multiple interfaces. This makes interfaces less restrictive and more flexible. So, in C#, when should we use abstract classes
    instead of interfaces with extension methods?
    A notable example of the interface + extension method model is LINQ, where query functionality is provided for any type that implements IEnumerable via
    a multitude of extension methods.

    Hi
    Well I believe Interfaces have more uses in software design. You could decouple your component implementing against interfaces so that
    you have more flexibility on changing your code with less risk. Like Inversion of Control patterns where you can use interfaces and then when you decide you can change the concrete implementation that you want to use. Or other uses for interfaces is you could
    use Interceptors using interfaces (Unity
    Interceptor) to do different things where not all of these is feasible or at least as straightforward using abstract classes.
    Regards
    Aram

  • Why use abstract classes?

    Why should I use abstract classes instead of a regular class with empty method bodies? Just better design? Is there some logical or performance based reason?

    Why should I use abstract classes instead of aregular
    class with empty method bodies? Just better design?Is
    there some logical or performance based reason?Because it describes what you're doing.
    If you define a "regular" class with empty message
    bodies, everyone who looks at it will say "WTF is he
    trying to do" or, if they're charitable, "Look,
    Harvey, someone who's trying to make Java look just
    like C++!".
    sigh Maybe answers like THIS are why people keep asking the same question.
    Here's a couple things an abstract class does that a "regular" class with empty methods bodies doesn't:
    1) An abstract class cannot be instantiated.
    2) An abstract class forces it's abstract methods to be implemented.
    If you were to extend a non-abstract class with empty method bodies, you wouldn't have to override the methods... you could just leave them empty. An abstract class forces it.
    There's a lot more reasons... those are a couple obvious ones.

  • Why are we using Abstract class?

    Why are we using Abstract class? What is specify use of Abstract class?

    The way I understand it....and I may be wrong because
    I am very new....is that by making the class abstract
    you will add abstract methods to it. Those abstract
    methods MUST be defined in in any subclass that
    inherits from the abstract class thereby making the
    abstract a template for subclasses.
    If your animal class is abstract then you would need
    an abstract method (Which is just siganture, no body)
    of say "numberOfLegs". Then in your dog and cat
    classes which extend animal you must define a
    "numberOfLegs" method with appropriate code.it isn't mandatory for an abstract class to have abstract methods. if a class does have abstract methods, the class must be abstract. but the following is perfectly legal
    public abstract class NoAbstractMethods {
      public void doStuff() {
         // do stuff
    }a subclass of an abstract class can also be abstract, and as such need not implement any additional methods

  • When to use abstract class compared to interface

    hi
    can some one plase advise me when to use abstract class compared to interface?
    Example will be appreciated...

    So an abstract class can carry implementation. This can be used to formulate a rule of thumb as to when to use it over an interface.
    If you have a so called type specialization relationship between the subtypes and the supertype then they're likely to benefit from shared implementation provided by the supertype, so use class (abstract or concrete) extension in this case. Type specialization is when the supertype represents a general concept like Fruit and the subtypes are specialized forms of that like Apple and Banana.
    Another common kind of relationship is called type expansion. In this case the subtypes are unlikely to have any use of implementation provided by the supertype, so use interface implementation. Type expansion is when the supertype represents a specific character the subtypes take on. For example Apple and Bicycle ure unrelated in the type specialization sense but still can share a common character like Comparable. The subtypes have been expanded to include the supertype character, namely the ability to be compared.

  • Most commenly used abstract class in java.

    hi all,
    can anyone please tell me, what is most commonly used abstract class in java. this question was asked in interview.

    I hate interviewers when they ask about specifics of some classes.The fact that you hate it doesn't automatically follow that it's a bad question from the perspective of the person conducting the interviewer. You don't know what the real question is.
    Bad "real" question: Do you know the statistics of Java usage off the top of your head?
    Good "real" question: Do you know that Object isn't Abstract and can you name a few Abstract classes off the cuff?
    Even then Programmers are so literal minded - the real question may be "Talk about what you know a bit."

  • Abstract class method polymorphically using constructors?

    how can i have a method defined in an abstract superclass call a constructor of the actual class running the method?
    abstract class A {
    public List getMultple() {
    List l = new ArrayList();
    for (short i=0;i<4;i++) {
    l.add(this());//<obviously this breaks
    return l
    or something like that. A won't run this method, but its children will...and they can call their constructors, but what do i put here to do that?
    i've tried a call back. an abstract method getOne() in the superclass forces each child to define that method and in each of those i return the results of a constructor. that works fine.
    the problem is i want to abstract this method out of each of these children classes cause its the exact same in each one, just using a different constructor to get multiple of each in a list. so if i use this callback method, then i am not saving the number of methods in each class, so why bother at all?
    any ideas?

    I still say you are coming at it from the wrong angle. A super class is not the way to go. What you are doing sounds like something very similar to something I did not too long ago.
    My requirement was that I had tab delimited text files filed with data that I had to parse. Each line would be used to instantiate one object, so a particular file could be used to instantiate, for example, a thousand objects of the same class. There were different types of files corresponding to different classes to instantiate instances of.
    Here is the design I ended up using.
    An object of class DataTextFileReader is instantiated to parse the text file and generate objects. It includes code for going line by line, handling bad lines and generating objects and reports. The constructor:
    public DataTextFileReader(File inputFile, LineParser<T> theLineParser)LineParser is an interface with one method:
    public T read(String line);When you call a load() method of the DataTextFileReader, it does its thing with the aid of the LineParser's read method, to which each line is passed, and stores the generated objects in an ArrayList. This can be returned by using another method. There are other methods for getting the reports, etc.
    Obviously, the LineParser chosen needs to have code appropriate for parsing the lines in question, so you have to choose and instantiate the right one.
    I find this design to work well. I arrived at it after spending hours giving myself headaches trying to come up with a design where there was a superclass roughly equivalent to the DataTextFileReader mentioned above, and classes extending this that fulfilled the duty of the LineParsers mentioned above... rather like what you are trying to do now.
    I did not care for the solution at first because it did not give me the "Ah, I am clever!" sensation I was expecting when I finally cracked the problem using inheritance, but I quickly came to think that it was much better OOD anyway.
    The LineParsers mentioned above are essentially embodiments of the Factory pattern, and I would recommend you do something similar in your case. Obviously your "constructors" all have to be different, so you should make a separate class for each of those. Then you can put the code that performs the query and loops to create loads of objects in another class called something like DatabaseDepopulator, using appropriate generics as in my example. Really it is the same problem, now that I look at it.
    This will also result in better separation of concepts, if you ask me. Why should the class constructor know how to parse a database result query, much less perform the query? It has nothing to do with databases (I presume). That is the job of an interpreter object.
    As a final note, remember... 95% of the time you feel like the language won't let you do what you want, it is because you shouldn't anyway.
    Drake

  • EJB question: How to use abstract class in writing a session bean?

    I had written an abstract class which implements the session bean as follow:
    public abstract class LoggingSessionBean implements SessionBean {
    protected SessionContext ctx;
    protected abstract Object editRecord(Object obj) throws Exception;
    public LoggingSessionBean()
    super();
    private final String getBeforeUpdateImage(Object obj) throws Exception {
    // implement the details of extracting the backup image ...
    public void setSessionContext(SessionContext ctx)
    this.ctx = ctx;
    private final void writeThisImageToDatabase(String aStr) {
    // connect to database to write the record ...
    public final Object update(final Object obj) {
    try {
    final String aStr = getBeforeUpdateImage(obj);
    writeThisImageToDatabase(aStr);
    editRecord(obj);
    } catch (Exception e) {
    ctx.setRollbackOnly();
    This abstract class is to write the backup image to the database so that other session beans extending it only need to implement the details in editRecord(Object Obj) and they do not need to take care of the operation of making the backup image.
    However, some several questions for me are:
    1. If I write a class ScheduleSessionBean extending the above abstract class and the according 2 interfaces ScheduleSession and ScheduleSessionHome for this session bean (void update(Object obj); defined in ScheduleSession), do I still need to write the interfaces for LoggingSession and LoggingSessionHome?
    2. If I wrote the interface LoggingSession extending EJBObject where it defined the abstract methods "void update(Object obj);" and "void setSessionContext(SessionContext ctx);", that this meant I needed to write the ScheduleSession to implement the Logging Session?
    3. I used OC4J 9.0.4. How can I define the ejb-jar.xml in this case?

    Hi Maggie,
    1. do I still need to write
    the interfaces for LoggingSession and
    LoggingSessionHome?"LoggingSessionBean" can't be a session bean, because it's an abstract class. Therefore there's no point in thinking about the 'home' and 'remote' interfaces.
    2. this
    meant I needed to write the ScheduleSession to
    implement the Logging Session?Again, not really a question worth considering, since "LoggingSessionBean" can't be an EJB.
    3. I used OC4J 9.0.4. How can I define the
    ejb-jar.xml in this case?Same as you define it for any version of OC4J and for any EJB container, for that matter, since the "ejb-jar.xml" file is defined by the EJB specification.
    Let me suggest that you create a "Logging" class as a regular java class, and give your "ScheduleSessionBean" a member that is an instance of the "Logging" class.
    Alternatively, the "ScheduleSessionBean" can extend the "Logging" class and implement the "SessionBean" interface.
    Good Luck,
    Avi.

  • OC4J 9.0.4 migrate to 10.1.3.1 JSP fails using abstract class for ResultSet

    Consider the following JSP code snipet:
    <%
    com.class.SQLDataSource detail = ((com.class.SQLDataSource)request.getAttribute("AcctList"));
    %>
    <%while detail.next()) {detail.getRow();%>
    <tr ...>
    <td ...><%= detail.getString("ACCT") %></td>
    </tr>
    <%}%>
    blah, blah, blah
    class snipet looks like this:
    public abstarct class SQLDataSource extends serializable {
    private ResultSet resultSet = null;
    private PreparesStatement stmt = null;
    public boolean next() throws SQLException {
    boolean result = getResultSet().next();
    return (result);
    public String getString(String columnName) throws SQLExcpetion {
    return getResultSet().getString(columnName);
    public void execute() throws SQLException {
    -- checks stmt
    -- if null generates resultSet from "AcctList.sql" query
    -- if not null, re-executes as-is stmt for a query only
    protected ResultSet getResultSet() throws SQLException {
    execute(); // see above
    return resultSet;
    The problem:
    <%= detail.getString("ACCT") %> generates a NullPointerException
    Yet, if I add debug statements in the SQLDataSouce class, they conclusively show that resultSet has 1902 rows and I can diplay the contents on these rows (on the console, of course, the JSP still generates a NullPointerException).
    If I "hardcode" the creation of a ResultSet in the JSP, the pages displays properly (not the desired method).
    PLEASE TAKE NOTE: This JSP/Class combination works PERFECTLY in OC4J 9.0.4 using JDeveloper 9.0.5.2. When I deploy the **EXACT SAME** JSP/Class combination in JDeveloper/OC4J 10.1.3.1, I receive the NullPointerException.
    So what this feels like to me (and my VERY limited J2EE experinece) is that the abstract class SQLDataSource has somehow lost/closed/dropped/corrupted resultSet when "returning" to the JSP for display of the contents of resultSet. This is, of course, a laymans explanation of the experienced effect of running this code.
    It makes me wonder if under 10.1.3.1 "something more" must be done so that the (abstract) SQLDataSource class can operate in the same way it did under 9.0.4.
    Last note: this NullPointerException happens whether I deploy to standalone OC4J 10.1.3.1 or if I execute my application withing JDevloper's Embedded OC4J instance.
    Any Assistance on this MOST aggrivating problem would be greatly appreciated.
    Others have yet to solve it in similar posts of mine. Hopefully this more definitive description will help YOU be my personal HERO.
    Ed.

    repost to pique interest

  • When should I use abstract classes and when should I use interfaces?

    Can any body tell me in which scenario we use /we go for Interface and which scenario we go for abstract class, because as per my knowledge what ever thing we can do by using Interface that thing can also done through abstract class i mean to say that the
    behavior of the two class.
    And other thing i also want to know that which concept comes first into the programming abstract class or Interface.
    S.K Nayak

    The main differences between an abstract class and an interface:
    Abstract
    An abstract class can contain actual working code (default functionality), and can have either virtual or abstract method.
    An abstract class must be sub-classed and only the sub-classes can be instantiated. Abstract methods must be implemented in the sub-class. Virtual methods may be overridden in the sub-class (although virtual methods typically contain code, you still may
    need/want to override them). A good use for an abstract class is if you want to implement the majority of the functionality that a class will need, but individual sub-classes may need slightly different additional functioality.
    Interface
    An interface only contains the method signatures (method name and parameters), there is no code and it is not a class.
    An interface must be implemented by a class. An interface is not a class and so it cannot be sub-classed. It can only be implemented by a class. When a class implements an interface, it must have code in it for each method in the interface's definition.
    I have a blog post about interfaces:
    http://geek-goddess-bonnie.blogspot.com/2010/06/program-to-interface.html
    (sorry, I have no blog posts specific to abstract classes)
    ~~Bonnie DeWitt [C# MVP]
    http://geek-goddess-bonnie.blogspot.com

  • Abstract class methods

    I'm confused. Is this true or false.
    The great thing about polymorphism is that you can call one method. If the subclass inherited that method, it will be customized and perform a different duty. That way, the action it performs will depend on 1>whether or not it's a sub or super class and also 2>if the method was overridden if it was a subclass.
    Now, my confusion. If an object reference is to a Super-abstract-class... how do the method calls and properties go?? well let me let you answer for me. Thanks so much in advance for this clarification.

    Yes. You are - pretty much.
    The abstract class, as such, can never be instantiated. BUT a class derived from the superclass IS an instance of the superclass.
    Silly example:
    abstract public class Animal {
       public Animal() {
       public abstract int getNumberOfLegs();
    }That's our animal class, and we know that anything that's an animal has a number of legs - but we can't just create a "generic" animal.
    public class Cat extends Animal {
       public Cat() {
          super();
       public int getNumberOfLegs() {
          return legCount;
       public void maim(int legsToRemove) {
          legCount -= legsToRemove;
          if(legCount < 0 ) legCount = 0;
       private int legCount = 4;
    }A Cat is a specific type of animal, so we can find out how many legs it has (usually 4). Note again that a cat IS an animal, so Cat IS an instance of Animal.
    Java even provides a special operator to test this:
    Cat cat = new Cat();
    System.out.println("A cat is a cat: " + (cat instanceof Cat));
    System.out.println("A cat is an animal: " + (cat instanceof Animal));The term used to describe the "Guarantee" that a subclass of an abstract class (or an implementation of an interface) is usually and technically a "contract", but I prefer to think of it as a "Promise" since you can break the promise by messing with the bytecode - at which point the JVM will spot the lie and complain !
    D.

  • Abstract class/ method calls

    Hi, in an
    abstract class Report
    private int mat
    private string add
    private int mat
    private double creduced = 0.125;
    private double sreduced = 0.25;
    public Property(String location, int material)
    add = location;
    mat = material;
    public double getActualPrice()
    double base = getPrice();
    double money = base;
    if (mat == 1)
    money -= base * creduced;
    return money;
    etc and two abstract classes called getPrice() , and getInsurance()- which i have both coded in the extended class
    in a class called "class Info extends Report" I want to use the getActualPrice() method since it will anyway cause of inheritence but i want to add a new if line to it. How do I do this and code it in the extended class?
    Can i super call the instance variables and local variables ? I have tried super calls on the instance variables but since none of them are included in any of the constructors it wont work.

    public double getActualPrice()
    double actual=super.getActuelPrice();
    if ( something )
       actual=dosomethingwith(actual){
    return actual;
    }

  • What are abstract classes/methods and what are they for?

    Hi,
    I've just heard about abstract classes and methods and I'm just wondering what exactly they're used for, and why are they there for the Graphics class for example?
    Cheers.

    raggy wrote:
    bastones_ wrote:
    Hi,
    I've just heard about abstract classes and methods and I'm just wondering what exactly they're used for, and why are they there for the Graphics class for example?
    Cheers.Hey bro, I'll try to solve your problemYou have to know two important concepts for this part. 1 is Abstract classes and the other is Interface classes. Depends on the nature of the project, you need to set certain level of standards and rules that the other developers must follow. This is where Abstract classes and Interface classes come into picture.
    Abstract classes are usually used on small time projects, where it can have code implementation like general classes and also declare Abstract methods (empty methods that require implementation from the sub-classes).Wrong, they are used equally among big and small projects alike.
    Here are the rules of an Abstract class and method:
    1. Abstract classes cannot be instantiatedRight.
    2. Abstract class can extend an abstract class and implement several interface classesRight, but the same is true for non-abstract classes, so nothing special here.
    3. Abstract class cannot extend a general class or an interfaceWrong. Abstract classes can extend non-abstract ones. Best example: Object is non-abstract. How would you write an abstract class that doesn't extend Object (directly or indirectly)?
    4. If a class contains Abstract method, the class has to be declared Abstract classRight.
    5. An Abstract class may or may not contain an Abstract methodRight, and an important point to realize. A class need not have abstract methods to be an abstract class, although usually it will.
    6. Abstract method should not have any code implementations, the sub-classes must override it (sub-class must give the code implementations). An abstract method must not have any implementation code code. It's more than a suggestion.
    7. If a sub-class of an Abstract class does not override the Abstract methods of its super-class, than the sub-class should be declared Abstract also.This follows from point 4.
    9. Abstract classes can only be declared with public and default access modifiers.That's the same for abstract and non-abstract classes.

  • Abstract class method returning unknown class

    Hi
    I have created an abstract class having one of the method returning an object of a class which is not present at the compiletime. surprisingly the compiler didn't check the availability of the returning class at compilation time. it gave exception of classnotfound when I tried to rum it.
    is there any explanation of it??

    Thanks for the replay. I got the reason.
    actually evenif I did not compile to class file, but I have kept my java file in the same directory. while compiling the abstract class the compiler automatically compiled the reffered class and generated the required class file.
    I got the error when I moved the java file to another dir
    the code is like
    <code>
    abstract class AbstractTest{
         CompleteClass method1(){
              System.out.println("inside method1 of abstract class");
              return new CompleteClass();
         ExtraClass method2(){
                   System.out.println("inside method2 of abstract class");
                   return new ExtraClass(); // this class was not compiled before
         } // only java file is there in the dir
         abstract void demoMethod();
    </code>

  • Can't navigate to a page when using a class method

    I am working on windows phone 8.1 universal app where I have created a class method and placed it in the NavigationHelper_LoadState method of one of the  pages in my app. My navigation is as follows, I click on a link on my Mainpage and that takes me
    to the page in question,  where I have placed the class method in LoadState.
    The class method checks the authentication state of the user. If the user is not logged in, it is supposed to take him to a separate login page (SHDSignIn from the snippet below).
    The problem I am running into is that when I hit that part of the code in my class method, it just steps through the redirect code but doesn't take me to the login page but rather takes me to the  page that was clicked from mainpage.
    From the troubleshooting I have done up to this point seems like an issue probably because I am calling the method from NavigationHelper_LoadState and the system doesn't like it?? Can someone please explain and also provide a workaround for this?
    Here is my code for the class function:
    public async void SHDAuthState(string errormessage, ProgressBar myprogressbar, TextBlock mytextblock, TextBlock myservernetworkerror)
    //Get the values for the userID and password from the settings....
    string shdLoggedInValue = (string)appRoamingSettings.Values["shdLoggedIn"];
    //If not logged in, redirect to the SHD sign in page...
    if (shdLoggedInValue != "Yes")
    this.rootFrame.Navigate(typeof(SHDSignIn));
    //Getting the cookie if it has expired..
    else
    //Get the cookie value...
    string myCookieValue = (string)appRoamingSettings.Values["MyCookie"];
    //Get the original cookie obtain time....
    long CookieObtainedTimeValue = (long)appRoamingSettings.Values["CookieObtainedTime"];
    //Convertig date/time back to DateTime object....
    origCookieObtainedTime = DateTime.FromBinary(CookieObtainedTimeValue);
    currentDateTime = DateTime.Now;
    //Check to see if cookie has expired....
    cookieTimeElasped = currentDateTime - origCookieObtainedTime;
    cookieTimeElapsedMins = cookieTimeElasped.TotalMinutes;
    // 2 days = 2880 mins but we give a margin of 1 minute
    //Get a new cookie if it has expired and save to settings
    if (cookieTimeElapsedMins >= 2879)
    // Start showing the progress bar...
    mycontrols.progressbarShow(myprogressbar, mytextblock);
    //Get the values for the userID and password from the settings....
    string UserIDValue = (string)appRoamingSettings.Values["UserID"];
    string PasswordValue = (string)appRoamingSettings.Values["Password"];
    //Update the requestData string before sending.....
    requestData = "{" + string.Format(RegisterRequestData, UserIDValue, PasswordValue) + "}";
    string registerResults = await SHDAPI(registerUrl, requestData, errormessage);
    if (registerResults != null)
    // Get the cookie and the time and save it to settings
    var shdCookie = JsonConvert.DeserializeObject<SHDHelper.SHDObject>(registerResults).RegistrationCookie;
    //Save cookie to the app settings
    appRoamingSettings.Values["MyCookie"] = shdCookie;
    // build the UI
    // Stop showing the progress bar...
    mycontrols.progressbarNoShow(myprogressbar, mytextblock);
    else
    // Stop showing the progress bar...
    mycontrols.progressbarNoShow(myprogressbar, mytextblock);
    //Show the error message...
    myservernetworkerror.Visibility = Windows.UI.Xaml.Visibility.Visible;
    Also, I have the rootFrame defined as follows in my class:
    Frame rootFrame = Window.Current.Content as Frame;
    I am calling the class method from the LoadState method as follows
    SHD_helper.SHDAuthState(errorMessage, pgbar, pgText, ServerNetworkError);
    thanks
    mujno

    that is correct.  I wanted to keep the login page redirect inside my class method so that I could do the check every time someone came to pages that require authentication. I wanted it in the LoadState method so I can do a check there, redirect
    them to login page or just get a cookie and then pass that cookie to page to build the UI for the page
    I can do what you are suggesting and have actually tried it but then I have to track which page to take the user to after they log in...
    I have multiple clicks in the appbar  and pages from where the user can come to these authentication-bound pages..
    Suggestions?
    Also, what am I doing wrong in my class method that it doesn't navigate to the login page in the LoadState method?
    Thanks 
    mujno

Maybe you are looking for

  • Error while installing the Add-on

    We are trying to install an Add-On in SBO 2005A with patch level-11. It is not creating the company object and we are getting the following error in one of the client machine. System.Runtime.InteropServices.COMException (0x80040154): Retrieving the C

  • Reload files from bridge cs6

    My mobo died and so I had to rebuild my system.  I am running Bridge cs6 on a win7 64 bit machine.  In order to rebuild my system I built a new C: drive, i.e., I created a new system drive.  All my files from before the crash are available.  All my d

  • User Exit: Saving data in Production Order Header Long Text

    Hi PP Gurus, Can any one let me know which user exit can be used to save some data in the Long Text of Production Order Header. We try PPCO0007, it works well on ECC, but my client's system version is 4.7, it does not work. In 4.7 version, is there a

  • Why should we Purge Audit data?

    Hi I have read several threads about purging audit details like the one below Re: OWB purge audit I want to know what are the benefits of purging the audit details.Please tell me how audit details are important and how can they play a role in decidin

  • BPM Limitations

    Hello, i have a view questions about limitations in bpm processes: 1. Will it be possible to extract single data records out of a list during data mapping in next releases? 2. Is it possible to react on asynchronous events during an bpm process? is i