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

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?

raggy wrote:
bastones_ wrote:
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.

Similar Messages

  • Whats the difference between a class method and a instance method.

    I have a quiz pretty soon and one of the questions will be: "How does an instance method differ from a class method." I've tried looking this up but they gave me really complicated explanations. I know what a instance method is but not really sure what a class one is. Can someone post an example of a class method and try to explain what makes it so special?
    Edited by: tetris on Jan 30, 2008 10:45 PM

    Just have a look:

  • Service/Database Accounts - NT SERVICE\MSSQLSERVER & NT SERVICE\SQLSERVERAGENT - what are they for?

    Hi Guys,
    I’ve done a fair amount of research for this question but just cannot seem to find the answer to my question in simple, non-DBA, terms.
    Server 2008 R2
    SQL 2008 R2
    There are 2 users in the system database logins (NT SERVICE\MSSQLSERVER, NT SERVICE\SQLSERVERAGENT) … what are they for? It appears that they
    are accounts to run the corresponding Windows services but yet they cannot be selected from the list of available built-in accounts, local accounts or domain accounts.
    Also, I am using a couple of domain user accounts to run the services, do I need to add them to the database? I changed the service accounts from NETWORK
    SERVICE to the domain user accounts using the SQL Configuration Manger which is supposed to take care of managing the user group membership and registry changes but the domain accounts are not in the database …. The services appear to be running fine.

    In basic terms:
    As you say, in the SQL Server Database Engine there are two logins;
    NT SERVICE\MSSQLSERVER and NT SERVICE\SQLSERVERAGENT. The Database Engine runs in Windows as a Windows service named
    MSSQLSERVER. The NT SERVICE\MSSQLSERVER login is used by the service to connect to the Database Engine. Basically, this is how it connects to itself. The SQL Server Agent runs as a Windows service named
    login is how the Windows process that is SQL Server Agent connects to the Database Engine to read the
    msdb database to find out what it should do; and then do it. Both of these logins are members of the
    sysadmin fixed server role, so they can do anything in the Database Engine. And they need to stay that way.
    No, they can't be selected in the list of available built-in accounts, local accounts or domain accounts. This is because they are services, not accounts. They have a security identifier (SID) in Windows,
    but Windows knows they aren't real users. Windows can authenticate them, but they don't have passwords that any human can use. If you run
    lusrmgr.msc and look at the groups, you will see groups like
    is a member of the group.
    As for the account that you used to run the services, this is complicated and has changed from SQL Server 2005 to SQL Server 2008 and now again in SQL Server Code Named 'Denali'. The short answer is that
    the account you specify will be used when a process tries to reach outside of the current Windows environment. But within the computer, there is a mix of authorization granted to the domain user, the service, and the Windows group
    The good news is that SQL Server Configuration Manager figures out all the stuff you need when you change the accounts. If you are a glutton for punishment, you can get an idea for how complicated this
    is by looking at the Denali documentation where I have tried to provide more specific information. (Note this is not the same as SQL Server 2008.) You can see it at:
    Configure Windows Service Accounts and Permissions
    Rick Byham, Microsoft, SQL Server Books Online, Implies no warranty

  • How to implement the abstract classes MessageDigest and Signature?

    Hi all,
    I've recently started working on JCDK 2.2.1.
    I have a problem to share and get suggestions from you!
    My aim is to implement ECDSA on Java card
    I have seen the Javacard API and tried to program using the classes
    MessageDigest and Signature. They are abstract classes and except the
    Method getInstance in them, the rest of all methods are declared abstract.
    Does that mean we have to give definition for them or else can we use
    them as they are?
    I tried giving some definitions, but to my surprise there's no such
    initiation of any variable to the algorithm we provide in the method
    "getInstance"! Then, it's not possible to give defn,. for other
    methods like getAlgorithm, reset, etc. How can we resolve this ?
    Any ideas?

    try this...
    hope it can help u

  • RealStrat and Kontakt 3 - How are they for you Logic 8/Mac Pro?

    I'm thinking on splurging on these two products to use in Logic 8 with an Intel Mac Pro. How are they for you? Do they work OK? I don't see too many negative comments here so I'm assuming that they're working OK. I'll go look the Native Instruments and MusicLab forums as well but thought there might be those here who could comment.

    K3 works fine on my 8-core since version 3.01 - actually 3.02 is buggy again so don´t upgrade to the latest version of K3 which is 3.02.
    If there would not be the annoying 2 Gigabyte RAM limit within 32-Bit applications I would be even happier, but if you need more Sample space just setup an additional K3 in standalone mode and wire it through the IAC Bus.
    If you use it in multitimbral mode with multiple outputs you'll have to write any automation onto the assigned Aux tracks as automating the single Midi tracks for K3 does not work.
    Altogether K3 is an awesome mashine with clear improvements compared to K2.

  • 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.

  • 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

  • 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() {
       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 !

  • Abstract class, Interface and two models issue

    I will post my code and then ask the question (text between code snippets is bold, so you don't miss it, it's not shouting):
    public class AppScreen extends JFrame
                           implements ActionListener {
      private MemoryTableModel model;
      public AppScreen() {
        this.model = new MemoryTableModel();
      public void actionPerformed(ActionEvent actEvt) {
          if(table.getSelectedRow() != -1) {
          else {
      public MemoryTableModel getModel() {
        return model;
    public class MemoryTableModel extends BasicTableModel
                                  implements MemoryTableInterface {
      public MemoryTableModel() {
      public synchronized void insertRow(String file, String time) {
      public synchronized void editRow(int selectedRow, String file, String time) {
    public synchronized void deleteRow(int selectedRow) {
    public abstract class BasicTableModel extends AbstractTableModel {
      private final String FILE_COLUMN = "Executable file";
      private final String TIME_COLUMN = "Time";
      protected String[] columnNames   = new String[2];
      protected List<RowRecord> data   = new ArrayList<RowRecord>();
      BasicTableModel() {
      public int getColumnCount() {
      public int getRowCount() {
      public String getValueAt(int row, int col) {
      public Class<? extends String> getColumnClass(int c) {
      public String getColumnName(int col) {
      public List<RowRecord> getData() {
      public int getTimeColumn() {
      public int getFileColumn() {
    public interface MemoryTableInterface {
      public void insertRow(String file, String time);
      public void editRow(int selectedRow, String file, String time);
      public void deleteRow(int selectedRow);
    In this form, everything works fine. But now, I would like to choose between two models at the start, so I thought I would do this:
    public class AppScreen extends JFrame
                           implements ActionListener {
      private BasicTableModel model;
      public AppScreen() {
        if(...) {
          this.model = new MemoryTableModel();
        else {
          this.model = new JDBCTableModel();
    public void actionPerformed(ActionEvent actEvt) {
          if(table.getSelectedRow() != -1) {
          else {
      public BasicTableModel getModel() {
        return model;
    public class JDBCTableModel extends BasicTableModel
                                implements JDBCTableInterface {
      public JDBCTableModel(Connection conn)
        throws ClassNotFoundException, SQLException {
      public void insertRow(String file, String time) throws SQLException {
      public void editRow(int selectedRow, String newFile, String newTime)
          throws SQLException {
      public void deleteRow(int selectedRow) throws SQLException {
    public interface JDBCTableInterface {
      public void insertRow(String file, String time) throws SQLException;
      public void editRow(int selectedRow, String file, String time)
          throws SQLException;
      public void deleteRow(int selectedRow) throws SQLException;
    }But I'm getting error message from AppScreen that method deleteRow(int) is undefined for the type BasicTableModel. I thought if I initialize variable model as some implementation of BasicTableModel, it will be OK. Apparently it's not, so:
    where and what am I missing or
    how can I realize this choosing between two models so I don't have to write "if(model == MemoryModel) else if(model == JDBCModel)" around every method where I have to decide.

    I would like to have issues interfacing with two classy models, as well. ;-)
    You need to have your BasicTobleModel class implement your JDBCTableInterface interface (even if it doesn't implement those methods itself), if that is how you intend to use that class.
    Edit: Too slow.

  • 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 )
    return actual;

  • Abstract classes, Interfaces, and concrete classes

    I have another technical interview tomorrow and somehow I keep getting asked the same question and I feel my answer is not really up to par. The question is:
    "What is the advantage of subclassing an abstract class versus concrete class?"
    "What is the difference of using an interface versus an abstract class, which is better to use?"
    For the first question, I usually answer performance is the advantage because you don't have to instantiate the class.
    For the second question, I usually say that you can put implementation in an abstract class and you can't in an interface. I really can't answer the second part to this question.
    Any ideas?

    For the first question, I usually answer performance
    is the advantage because you don't have to instantiate
    the class. Try invoking the class B in the following somewhere in another class.
    abstract class A{
          System.out.println("abstract instantiated");
    class B extends A{

  • Documentation for abstract classes (Behavior and Binding) ?

    I am looking at the beautiful sample-app made by Jasper Potts at the www.fxexperience.com. ("Javafx 2.0 Audio Player")
    There some abstract classes are used, for Behavior and Binding.
    It turns out that I have difficulties finding documentation for those classes. The classes are:
    Could anybody give me hint, pls, where I could find documentation for those classes.
    They are all in the JavaFx-Runtime-Jar-file, together with all the Javafx-classes.
    The Javafx-classes are pretty well documented in the meantime.
    But, allthough in the same "package", the com.sun... classes are still black boxes to me.
    Appreciate a link from somebody who knows, pls.

    Hi Hans,
    the classes in the com.sun.* packages are internal classes, in other words they are meant to be black boxes for you. :-)
    A developer should not use these classes, because they can change anytime without warning, even between minor releases. But a developer should also not need to use the internal classes. If Jasper needed them in the demo, it is a clear indicator that something is missing in the public API.
    The classes seem to be part of the UI controls, which were already open-sourced. If you just want to play with the classes, you can study the sources. As a long term solution, I suggest to add a feature request in JIRA for the parts you are missing in the public API (http://javafx-jira.kenai.com).

  • Abstract class method returning unknown class

    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
    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();

  • Academic Question about Classes Method and Constructor

    Given the similarity between the Constructor class and the Method class, why don't they have a common super class for the methods they have in common that are unique to them?

    sledged wrote:
    jschell wrote:
    sledged wrote:
    I've found that the most common reason for invoking a constructor or method through reflection is because you don't know what you need until runtime, commonly because what you want can vary based on context, or is otherwise being specified external to the bit of code that uses reflection. Not true. The fact that I don't need it until runtime never means I don't know what I need.Never? Then your experiences with the reflection API have been different than mine. Either that or I wasn't very clear. Let's take Apache Commons BeanUtils;
    It doesn't matter how you access a class. You can't use it unless
    1. You have a goal in mind
    2. That object in some way fulfills that goal.
    3. You know how that object fulfills that goal.
    And as I already pointed out you can't use a JFrame for a JDBC driver. Simple as that. Nor can I create a new class that implements, for example, ProC (Oracle method to embed access into C code) using my own idiom despite that it provide database access. It MUST match what jdbc expects.
    Sometimes it's not even clear before runtime whether a constructor's needed or a method.
    I disagree. That isn't true in any OO language.Perhaps not out the box, but it can be true when using certain tools built from the OO language. Let me continue using the Spring framework as an example. It does not know whether to use a method or a constructor to instantiate any bean defined in the XML configuration metadata until that XML file is read and it determines whether or not a given bean definition has the "factory-method" attribute. The XML file in not read until runtime, therefore with any given bean defined therein, Spring does not know until runtime whether to use a constructor or method.Not apt at all.
    As I already said those are two different idioms. Spring supports them because they are used to solve different problems not because they wish constructors didn't exist.
    The basis of OO is the "object". You can't have a method without the object in the conceptual OO model. (And in Smalltalk that is always true.)
    True, but one may not always care how the "object" is provided. When the method [Properties.load(InputStream)|http://java.sun.com/javase/6/docs/api/java/util/Properties.html#load%28java.io.InputStream%29] is called, it isn't going to care whether the InputStream argument was instantiated by one of the FileInputStream constructors, or if it came from a [URL.openStream()|http://java.sun.com/javase/6/docs/api/java/net/URL.html#openStream%28%29] method call. It'll work with either regardless of their respective origins.
    That of course has nothing to do with anything. Unless you are suggesting that construction in any form should not exist.
    A factory is not a constructor.I'm not saying it is. I'm just pointing out a number of the similarities between the two.
    So? There are many similarities between RMI and JDBC but that doesn't mean that they should be the same.
    With your argument you can claim that construction doesn't exist because any method, regardless of intent, that uses 'new' would eliminate the need for construction. And that isn't what happens in OO languages.I wouldn't claim that construction doesn't exist in any OO language. But I do know that in ECMAScript construction exists on the basis of whether or not a method is called with the 'new' operator. So in ECMAScript a single method can also be a constructor.
    And in C++ I can entirely circumvent the object construction process. Actually I can do that in JNI as well.
    I would still be a bad idea.
    They are not interchangable.Normally, no, but with a high enough level of abstraction, they can become interchangeable. Again, the Spring framework is a great example. It doesn't care if a method or a constructor is used, and it won't know which one has been chosen until runtime. I don't even think Spring checks the return type of a method, so you could use a void return type method. (Although I don't know what that would buy you because the bean would always be set to null, but still...)
    Based on that argument every possible programming problem could be solved by simply stating that one must implement the "doit()" method. One just need to generalize it enough.
    Different APIs exist because there are in fact differences not because there are similarities.
    Over generalization WILL lead to code that is hard to maintain. Actually generalization itself, even when done correctly, can lead to code that is actually more complex.
    Because construction is substantially different than calling a method. In all OO languages.Yes, construction is different, but the actual call to a constructor and a method is only syntactically different with the presence of the 'new' operator. With reflection the difference is between calling Method.invoke() and Constructor.newInstance(), and, as I mentioned earlier, there's enough similarity between the two methods that they could be called by a single method specified by a common super class.Which does not alter the fact that the process of achieving the result is fundamentally different.

  • Saving MSW or TextEdit docs to iCloud - where are they for retrieval?

    It does not help being ignorant about iCloud, but I am.
    I was saving a transcript in TextEdit when the iCloud prompt screen appeared indicating I could save it there. Because I have no idea where it can be retrieved, I saved it as normal, which is not a problem for me whatsover because I have a meticulously operated IMac with specific folders to save all my documents for various organizations including personal files Something I have done for over 10 years without any problems when it comes to retrieving files for later use. My IMac and MacBook are not lacking storage space. Have lots to spare.
    Ancient users like me from the past century may not be catching onto iCloud like I should. I went to a Mountain Lion workshop but it was mostly an overview, no specifics. I found out that Apple has 3 new programs that simulate MSW Office documents. I have a sense that MSW Office files are not compatible with iCloud storage.
    Okay! I need help to better understand saving files to iCloud and where on my system is iCloud to retrieve them? And, upon doing so, when I go to my MacBook, can I retrieve the same files on this device?
    Dummy #1, for sure! Your patience and understanding will be most appreciated. Look forward to your assistance.
    Message was edited by: kananaskis

    It will have been saved in your Home/Library/Mobile Documents/com~apple~TestEdit/Documents folder.
    But remember:
    In Lion and Mountain Lion that Library folder is now invisible. To make it permanently visible enter the following in the Terminal application window: chflags nohidden ~/Library and hit the Enter button - 10.7: Un-hide the User Library folder.

Maybe you are looking for

  • Iweb & Leopard

    Hi all, When I publish a web page in Iweb it goes to preferences. I can't update the web page on the web like I did on Tiger?????????? [email protected]

  • Transaction data reset

    hi Can we clean transaction data . and start transaction again from  initial number range if it is possible then what is the procedure Thanks

  • [CS5] masking a person on a clip with heavy motion stabalization already done

    Hoping to get somekind of a basic outline on how to proceed with this task: I've been working on some really nasty willdly jerky footage. I received some coaching that directed me to use the stabalizer aspect of motion tracking and man did that reall

  • Sales Order Using Idoc

    Hello All, We are creating Sales Order through Idocs : Basic Type  - ORDERS05   Message Type - ORDERS Sales Order is being created but for few Items , Reason for Rejection is set (thts not required in our case). I am trying to figure out why for some

  • ALV-Toolbar : Control the &LOCAL& Buttons

    Hi, all I have the following problem with ALV-Toolbar. If I use editable ALV-Grid Control, I get in the toolbar new buttons such as DELETE_ROW or UNDO. This buttons don’t trigger any events of the class CL_GUI_ALV_GRID. If I look at Function Code of