Inner class of abstract class

Hi All,
Sorry for my English...
Say I have an abstract Class A and and inner class within A named B.
When I extend class A (i.e. making a subclass of A) does it mean the class B also inheritaned?
Thank u in advance
Eyal

Eyal2007 wrote:
Does inner class of an outer abstract class can be static?Yes, why not?
is there any logic in this?Yes, if follows the normal meanings of access types and the difference between static and instance entities.
A protected inner class is accessible in the same places a protected field would be.

Similar Messages

  • Concrete classes implement abstract class and implements the interface

    I have one query..
    In java collection framework, concrete classes extend the abstract classes and implement the interface. What is the reason behind extending the class and implementing the interface when the abstract class actually claims to implement that interface?
    For example :
    Class Vector extends AbstractList and implements List ,....
    But the abstract class AbstractList implements List.. So the class Vector need not explicitly implement interface List.
    So, what is the reason behind this explicit definition...?
    If anybody knows please let me know..
    Thanx
    Rajendra.

    Why do you post this question again? You already asked this once in another thread and it has been extensively debated in that thread: http://forum.java.sun.com/thread.jsp?forum=31&thread=347682

  • Implementing Comparable in an abstract class

    Hi all,
    I am making my first sortie with abstract classes. I have had a good look around, but would still appreciate some advice with the following problem.
    In my application I have several classes that have many things in common. I have concluded therefore, that if I create and then inherit from an abstract super class, I can reduce and improve my code. I created this abstract class:
    public abstract class YAbstractObject implements Comparable {
        public YAbstractObject(int projectId, YObject object, String objectName) {
            this.projectId = projectId; // Always the same parameters
            this.object = object;
            this.objectName = objectName;
        // This is abstract as it must always be present for sub classes but differant processing will take place
        public abstract void resolveObject();
        // These three methods will always be the same for all sub classes
        public String getName() {
            return objectName;
        public YObject getObject() {
            return object;
        public boolean isValid() {
            return isValid;
    // Overridden and always the same for all sub classes
        public String toString() {
            return objectName;
        // implemented abstract method
        public int compareTo(Object thatObject) {
            // Issue here! I would like something as follows:
            //  return this.getName().compareToIgnoreCase(thatObject.getName());
    // Variable decleration
        private int projectId;
        private YObject object;
        private String objectName;
        private boolean isValid;As I have commented in the compareTo() method, I would like it to be able to use the getName() method for comparison objects and compare them. But it does not like this, as it does not know that "thatObject" is of the same class as this object - I hope that made sense.
    in essence, I want to inherit this method for different classes and have it work with each.
    Is there a way to do this? Generics?
    Any observations, greatly appreciated,
    Steve

    You can use also generics (if applicable: java -version >= 1.5).
    public abstract class Test implements Comparable<Test> {
         String name;
         public Test(String name) {
              this.name = name;
         public String getName() {
              return name;
         public int compareTo(Test obj) {
              return this.getName().compareTo(obj.getName());
    public class Other extends Test {
         public Other(String name) {
              super(name);
    public class Tester extends Test {
         public Tester(String name) {
              super(name);
         public static void main(String[] args) {
              Test t = new Tester("t");
              Test a = new Tester("a");
              Test o = new Other("t");
              System.out.println(t.compareTo(a));
              System.out.println(t.compareTo(new Object())); //compile error
              System.out.println(t.compareTo(o));
    }Without the compile error line it will give the following result:
    19
    0

  • Why use an Abstract Class ?

    I am new to Java and for some reason I can't get my head around why to use an abstract class. I understand that an abstract class is something like:
    public abstract class Food{ // abstract class
    public void eat(){
    // stub
    public class Apple extends Food{
    public void eat(){
    // Eat an apple code
    }So basically the idea above is that you can eat an "apple" but you can't eat "food" because you can't instantiate an abstract class.
    I understand what an abstract class is and how to write one. What I don't understand is why you would use it? It looks to me like I could have just created a normal class called "Food" and just not instantiated it. What are the benefits of using an abstract class?

    807479 wrote:
    I am new to Java and for some reason I can't get my head around why to use an abstract class.One of the first books I ever read about Object-Oriented design contained the following quote from [url http://en.wikipedia.org/wiki/Lucius_Cary,_2nd_Viscount_Falkland]Lord Falkland:
    "When it is not necessary to make a decision, it is necessary +not+ to make a decision."
    It took me quite a while to understand, but it's all about flexibility: As soon as you cast something in stone, you lose the ability to change it later on if something better/more appropriate comes along. Interfaces and abstract classes are all about delaying that decision.
    As jverd said, interfaces allow you to specify what is required without defining the how; and as ErasP said, abstract classes are usually incomplete: ie, they define some of the 'how', but not all of it.
    What is most important about abstract classes though is that they cannot exist on their own: They must be extended by a concrete class that completes the 'how' before they can be instantiated and, as such, they declare the intent of the designer.
    One of the most important uses of abstract classes is as "skeleton implementations" of interfaces, and there are a lot of examples of these in the Java Collections hierarchy. My favourite is probably AbstractList, which contains a skeleton implementation of a List. Because it exists, I can create a class that wraps an array as a List with very little code, viz:public final class ArrayAsList<T>()
       extends AbstractList<T>
       private final T[] values;
       public ArrayAsList(T... values) {
          this.values = values;
       @Override
       public T get(int index) {
          return values[index];
       @Override
       public T set(int index, T element) {
          T value = get(index);
          values[index] = element;
          return value;
       @Override
       public int size() {
          return values.length;
    };and somewhere else, I can use it:   List<String> letters =
          new ArrayAsList<String>("a", "b", "c");or perhaps, more practically:   List<String> words = new ArrayAsList<String>(
          bigTextString.split(" +") );Now that may not seem like a big deal to you, but given all that Lists can do, it's actually a very powerful bit of code. The above example is from "Effective Java" (p.95).
    HIH
    Winston

  • Abstract Class Polymorphism?

    I want to be able to add any of my sub classes to a collection (hash set) , without duplicating the code. The superclass for all these subclasses is an abstract class.
    Is there a possible way of achieving this?
    At the moment I have methods for each individual class; before making the parent class abstract, I could use the same method for all, but was advised as I did not want an instance of that parent class, the abstract class was best.
    Hope this is not too vague or abstract... :)

    I think if you use the wildcard symbol it'll allow you to add a covariant to the collection, for example
    public static void addSub(List<? super NameofSuperClass> varName)
    When you can to retrieve the data, if you want any methods not in the super class you would still be to cast it.
    Is this what you meant? - Peter sorry if it wasn't helpful

  • Instanciate generic subclass of an abstract class

    Hello,
    I'm writing a litle file manager API for my application, organised like a Database: a table filled by records.
    I want my table to be able to be able to manage different types of records (but one record type by table!), so I have this hierarchy:
    the abstract record class:
    public abstract class Record {
         public Record() {
         public abstract void readFrom(DataInput in, int length) throws IOException;
         public abstract void writeTo(DataOutput out) throws IOException;
         public abstract int prepareToWrite();
    }the abstract atomic record class, extending the abstract record class:
    public abstract class AtomicRecord<T> extends Record {
         public AtomicRecord() {
         public AtomicRecord(T value) {
              super();
         public abstract T getValue();
         public abstract void setValue(T value);     
    }and, for example, the StringRecord class:
    public class StringRecord extends AtomicRecord<String> {
         code doesn't matter.
    }now, I want to make a table of generic records:
    public class RandomRecordAccessAppendableFileTable<RecordType extends Record>{
         public final RecordType getRecord(long id) throws IOException {
              RecordType record = new RecordType();
    }problem: the RecordType is obviously not instanciable, as it extends Record, and not StringRecord. But I still want to instanciate a new StringRecord from a RandomRecordAccessAppendableFileTable<StringRecord> and a FooRecord from a RandomRecordAccessAppendableFileTable<FooRecord>.
    Is there a way I can do this?
    Thank you in advance.

    This is just my opinion, so you might ignore it: The design you are targeting is a result of misunderstanding what Generics are for and what Generics may provide in their current state. Their only purpose is to provide compile-time type safety. Creating instances the way you want to do seems more runtime focused, i.e., when generic information is gone.
    Maybe, you should consider passing a factory at construction time that enables to create a record of a specific type. Using the class object requires reflection, which will introduce implicit contracts to record classes and potential runtime failures.

  • Abstract classes and methods with dollar.decimal not displaying correctly

    Hi, I'm working on a homework assignment and need a little help. I have two classes, 1 abstract class, 1 extends class and 1 program file. When I run the program file, it executes properly, but the stored values are not displaying correctly. I'm trying to get them to display in the dollar format, but it's leaving off the last 0. Can someone please offer some assistance. Here's what I did.
    File 1
    public abstract class Customer//Using the abstract class for the customer info
    private String name;//customer name
    private String acctNo;//customer account number
    private int branchNumber;//The bank branch number
    //The constructor accepts as arguments the name, acctNo, and branchNumber
    public Customer(String n, String acct, int b)
        name = n;
        acctNo = acct;
        branchNumber = b;
    //toString method
    public String toString()
    String str;
        str = "Name: " + name + "\nAccount Number: " + acctNo + "\nBranch Number: " + branchNumber;
        return str;
    //Using the abstract method for the getCurrentBalance class
    public abstract double getCurrentBalance();
    }file 2
    public class AccountTrans extends Customer //
        private final double
        MONTHLY_DEPOSITS = 100,
        COMPANY_MATCH = 10,
        MONTHLY_INTEREST = 1;
        private double monthlyDeposit,
        coMatch,
        monthlyInt;
        //The constructor accepts as arguments the name, acctNo, and branchNumber
        public AccountTrans(String n, String acct, int b)
            super(n, acct, b);
        //The setMonthlyDeposit accepts the value for the monthly deposit amount
        public void setMonthlyDeposit(double deposit)
            monthlyDeposit = deposit;
        //The setCompanyMatch accepts the value for the monthly company match amount
        public void setCompanyMatch(double match)
            coMatch = match;
        //The setMonthlyInterest accepts the value for the monthly interest amount
        public void setMonthlyInterest(double interest)
            monthlyInt = interest;
        //toString method
        public String toString()
            String str;
            str = super.toString() +
            "\nAccount Type: Hybrid Retirement" +
            "\nDeposits: $" + monthlyDeposit +
            "\nCompany Match: $" + coMatch +
            "\nInterest: $" + monthlyInt;
            return str;
        //Using the getter method for the customer.java fields
        public double getCurrentBalance()
            double currentBalance;
            currentBalance = (monthlyDeposit + coMatch + monthlyInt) * (2);
            return currentBalance;
    }File 3
        public static void main(String[] args)
    //Creates the AccountTrans object       
            AccountTrans acctTrans = new AccountTrans("Jane Smith", "A123ZW", 435);
            //Created to store the values for the MonthlyDeposit,
            //CompanyMatch, MonthlyInterest
            acctTrans.setMonthlyDeposit(100);
            acctTrans.setCompanyMatch(10);
            acctTrans.setMonthlyInterest(5);
            DecimalFormat dollar = new DecimalFormat("#,##0.00");
            //This will display the customer's data
            System.out.println(acctTrans);
            //This will display the current balance times 2 since the current
            //month is February.
            System.out.println("Your current balance is $"
                    + dollar.format(acctTrans.getCurrentBalance()));
        }

    Get a hair cut!
    h1. The Ubiquitous Newbie Tips
    * DON'T SHOUT!!!
    * Homework dumps will be flamed mercilessly. [Feelin' lucky, punk? Well, do ya'?|http://www.youtube.com/watch?v=1-0BVT4cqGY]
    * Have a quick scan through the [Forum FAQ's|http://wikis.sun.com/display/SunForums/Forums.sun.com+FAQ].
    h5. Ask a good question
    * Don't forget to actually ask a question. No, The subject line doesn't count.
    * Don't even talk to me until you've:
        (a) [googled it|http://www.google.com.au/] and
        (b) had a squizzy at the [Java Cheat Sheet|http://mindprod.com/jgloss/jcheat.html] and
        (c) looked it up in [Sun's Java Tutorials|http://java.sun.com/docs/books/tutorial/] and
        (d) read the relevant section of the [API Docs|http://java.sun.com/javase/6/docs/api/index-files/index-1.html] and maybe even
        (e) referred to the JLS for "advanced" questions.
    * [Good questions|http://www.catb.org/~esr/faqs/smart-questions.html#intro] get better Answers. It's a fact. Trust me on this one.
        - Lots of regulars on these forums simply don't read badly written questions. It's just too frustrating.
          - FFS spare us the SMS and L33t speak! Pull your pants up, and get a hair cut!
        - Often you discover your own mistake whilst forming a "Good question".
        - Often you discover that you where trying to answer "[the wrong question|http://blog.aisleten.com/2008/11/20/youre-asking-the-wrong-question/]".
        - Many of the regulars on these forums will bend over backwards to help with a "Good question",
          especially to a nuggetty problem, because they're interested in the answer.
    * Improve your chances of getting laid tonight by writing an SSCCE
        - For you normal people, That's a: Short Self-Contained Compilable (Correct) Example.
        - Short is sweet: No-one wants to wade through 5000 lines to find your syntax errors!
        - Often you discover your own mistake whilst writing an SSCCE.
        - Often you solve your own problem whilst preparing the SSCCE.
        - Solving your own problem yields a sense of accomplishment, which makes you smarter ;-)
    h5. Formatting Matters
    * Post your code between a pair of &#123;code} tags
        - That is: &#123;code} ... your code goes here ... &#123;code}
        - This makes your code easier to read by preserving whitespace and highlighting java syntax.
        - Copy&paste your source code directly from your editor. The forum editor basically sucks.
        - The forums tabwidth is 8, as per [the java coding conventions|http://java.sun.com/docs/codeconv/].
          - Indents will go jagged if your tabwidth!=8 and you've mixed tabs and spaces.
          - Indentation is essential to following program code.
          - Long lines (say > 132 chars) should be wrapped.
    * Post your error messages between a pair of &#123;code} tags:
        - That is: &#123;code} ... errors here ... &#123;code}
        - OR: &#91;pre]&#123;noformat} ... errors here ... &#123;noformat}&#91;/pre]
        - To make it easier for us to find, Mark the erroneous line(s) in your source-code. For example:
            System.out.println("Your momma!); // <<<< ERROR 1
        - Note that error messages are rendered basically useless if the code has been
          modified AT ALL since the error message was produced.
        - Here's [How to read a stacktrace|http://www.0xcafefeed.com/2004/06/of-thread-dumps-and-stack-traces/].
    * The forum editor has a "Preview" pane. Use it.
        - If you're new around here you'll probably find the "Rich Text" view is easier to use.
        - WARNING: Swapping from "Plain Text" view to "Rich Text" scrambles the markup!
        - To see how a posted "special effect" is done, click reply then click the quote button.
    If you (the newbie) have covered these bases *you deserve, and can therefore expect, GOOD answers!*
    h1. The pledge!
    We the New To Java regulars do hereby pledge to refrain from flaming anybody, no matter how gumbyish the question, if the OP has demonstrably tried to cover these bases. The rest are fair game.

  • Abstract Classes vs Private Constructor

    Hopefully this doesn't make me sound to naive
    If we have a super class called food, and subclasses chocolate, chicken, cereal and so on then its clear we dont want to make instances of the super class food correct? So we can make this class an abstract class
    What are the benefits of making a class abstract over making a constructor private and in what circumstance would it be beneficial to do one over the other?
    Thanks, and sorry for a poor example!
    Edited by: compSciUndergrad on Apr 22, 2009 4:53 AM

    wrybread wrote:
    Also, Corlettk -
    Excellent point regarding prudent use of interfaces; thank you. If you read this, I'd appreciate any comment you have on how conservative programmers need to be in designing an interface. It seems to me that if I'm uncertain whether or not to include a certain member in the interface, I should omit it or include it elsewhere (perhaps in an interface all its own, or in an abstract super if that's applicable).
    Let me know if you want me to open this as a new thread; I'm just looking for your take on this topic. -- Thank you!Obviously, there's no right answer. Each deisgn must be assessed on a case-by-case basis. Every design presents new and interesting problems.
    I'm no OO guru... what I do know is that you can make some very nasty mistakes, thanks to experience of maintaining a fairly poorly written (first in the organisation) large java project.
    I'm of the opinion that interface should define an aspect of behaviour... If the Sun GODS had there time again they'd do java.io would be full of interfaces... Closeable, Openable, Readable, Writable, Printable... etc etc etc.
    Please remember that a class (or group of classes) can implement multiple interfaces... and an interface can extend multiple interfaces... So java supports "multiple type inheritance" as apposed to C++'s "multiple implementation inheritance".
    If you need an "aglomerate" interface as the type for a collection then assemble one from your premade "set of aspects"... eg: Input extends Openable, Closeable, Readable...
    package forums;
    interface AnInterface
      public void a();
    interface AnotherInterface
      public void b();
    interface AglomerateInterface extends AnInterface, AnotherInterface
      public void c();
    class AglomerateImpl implements AglomerateInterface
      public static void main(String[] args) {
        try {
          System.out.println("Hello World!");
        } catch (Exception e) {
          e.printStackTrace();
      public void a() {}
      public void b() {}
      public void c() {}
    }PS: You wouldn't normally define multiple interfaces and an implementation all in one file... sort of defeats the whole purpose really... and in fact you can't as soon as you make the interfaces public, which they need to be to be any use.
    Make sense?

  • Dynamically invoke methods of abstract class?

    Hi,
    I am using reflection to write a class (ClassA) to dynamically invoke methods of classes. I have an abstract class (ClassB) that has some of the methods already implemented, and some of the methods that are declared abstract. Is there any way that I can:
    (a) invoke the methods that are already implemented in ClassB;
    (b) I have another class (ClassC) that extends ClassB, some of the methods are declared in both classes. Can I dynamically invoke these methods from ClassB?
    Thanks in advance,
    Matt.

    Ok, the program is quite long, as it does other things as well, so I'll just put in the relevant bits.
    What I have is a JTree that displays classes selected by the user from a JFileChooser, and their methods.
    // I declare a variable called executeMethod
    private static Method executeMethod;
    // objectClass is a class that has been chosen by the user.  I create a new instance of this class to execute the methods.
    Object createdObject = objectClass.newInstance();
    // methodName is the method selected by the user.  objectClassMethods is an array containing all the methods in the chosen class.
    executeMethod = objectClassMethods[j].getDeclaringClass().getMethod(methodName, null);
    Object executeObject = executeMethod.invoke(createdObject, new Object[]{});Ok, here are the test classes:
    public abstract class ClassB{
         private int age;
         private String name;
         public ClassB(){ age = 1; name="Me";}
         public int getAge(){ return age; }
         public String getName(){ return name; }
         public void PrintAge(){System.out.println(age);}
         public void PrintName(){System.out.println(name);}
         public abstract void PrintGreeting();
    public class ClassC extends ClassB{
         public ClassC(){super();}
         public void PrintAge(){
              System.out.println("I am " + getAge() + " years old.");
         public void PrintGreeting(){
           System.out.println("Hello");
    }Now, I can print out the PrintAge method from ClassC (i.e. have it output "Hello" to the command line, how can I, say, get it to output the result of PrintName from ClassB, this method does not appear in ClassC. As you can see at the top, I can create a new instance of a normal method (in this case, ClassC), and have it output to the command line, but I know that I can't create a new instance of an abstract class. And since PrintName is implemented in abstract class ClassB, how do I get it to output to the command line?
    Thanks,
    Matt.

  • Abstract Classes versus Interfaces

    Somebody at work has just made an interesting observation and its bugging me, comments please.
    When I started Java I just used classes (and abstract classes), and didnt bother with Interfaces I understood them to be a way of getting round the lack of MultipleInheritance and it wasnt a problem that concerned me.
    But as time went on I found that sometimes I did want classes that had little in common to provide some additional feature (such as logging), and interfaces were great for this.
    ..so I was happy ..
    During all this time if I want a HashSet I would write code like this
    HashSet dataSet = new HashSet();but then I read that HashSet was an implementation detail and we should be using Interfaces as follows:
    Set dataSet = new HashSet();So whereas before I might have had a class hierachy with an Abstract class at the top , I started slotting in Interfaces above that and viewing the Abstract class as just a convenience to implementing the Interface.
    So which is the right method , originally I saw subclassing object as an 'is a ' relationship and implementing an interface as a 'implements' relationship. But more recently it seems to be turned on its head and implementing an interface is an 'is a' relationship (but supports multiple inheritance)
    Also it seems to be the trouble with this second approach is that anyone can implement an interface, for example I could implement Set,Map and List with one class, the class hierachy is not so helpful .

    Thanks, but the question was alot wider than that,
    the HashSet example was just one part of it.I think it is representative of all the situations that you talk about, which are whether an instantiator should handle the instantiated object by its interface or by its implementation.
    I suppose the question is
    "How do you code model "is a " relationship in java
    through extending a class or creating an interface
    and implementing it"
    MySubClass extends MySuperClass implements MyInterface {}MySubClass is a MySuperClass and a MyInterface. The way that I view it, the "is a" relationship applies to all type inheritance, even for the multiple type inheritance that you can have with interfaces. The "is a" relationship doesn't doesn't have to be a 1:1 mapping. There's no point in thinking about it differently since that's how the language behaves.
    an alternative question is
    "is it correct to mix/match both methods I described
    above"I thought I gave an answer. You said that my answer is not "broad enough." How so? My answer was that handling an object that you instantiate by its interface can reduce the amount of changes you have to make if you change the implementation. You will have to make one change (the line of code that instantiates the object) instead of many. Also, handling it by its interface makes it easier to switch from object A instantiating object B to object A being passed a reference to B and to object A getting its dependencies injected by XML configuration.
    It seems weird to handle an object by its interface if you already know it's implementation, but it's commonly seen and this is why I think it must be used. As I said, it's a small benefit of abstraction.
    The times when you may not want to do this is when the instantiator has to call methods from different interfaces of the object. You can handle it by its interface by casting between the different interfaces you have to work with, or you can just handle it by its implementation, gaining access to all of the object's interfaces.
    Note that everything I explained concerns the type by which the instantiator handles an instantiated object. If a class does not instantiate a certain object, then it almost always should receive it by its interface, unless it's some really common implementation that's never going to change.
    I use interface, abstract class, and base class interchangeably. It's up to you to decide which to use for type inheritance. It's good practice to favor interfaces.

  • Abstract classes and OO theory...

    I have an OO theory question related to abstract classes and their member variables. I realize opinions will vary from person to person but I'll ask anyway...
    If I'm creating an abstract class, should member variables that will be used by subclasses be private or protected? Why? Either way, they will have accessor methods for classes that instantiate them (where appropriate) but I'm debating whether or not to give subclasses direct access to these variables or not.
    To me, it seems odd to make variables in the abstract class private but I'm curious what your opinions are.
    Thanks...

    I knew you'd say that. I'd like to play along with a for-instance, if you will allow ... here's an example parent class:
    public abstract class ProvideMenu   extends JFrame {
      protected              JMenuBar       jmbar;
      protected              JMenu          jmfile,
                                            jmedit,
                                            jmhelp;
      protected              JMenuItem      jmfnew,
                                            jmfopen,
                                            jmfsave,
                                            jmfsaveas,
                                            jmfprint,
                                            jmfexit,
                                            jmecopy,
                                            jmepaste,
                                            jmhabout,
                                            jmhcontents;
      public ProvideMenu() {
        jmbar       = new JMenuBar();
        jmfile      = new JMenu( FILE_MENU );
        jmedit      = new JMenu( EDIT_MENU );
      public abstract void aMeth();
    }Now the subclass does not need to provide setProvideMenuFont( new Font( ... ) ) and Font getProvideMenuFont() methods, setProvideMenuEnabled(), etc. but can use the standard methods setFont, getFont setBackground(), setEnabled, etc, etc.
    Mind you I'm not advocating this ... what I am doing is trying to open the discussion up a bit - I hope no one minds ... what better design - just a for-instance - would you advocate?
    ~Bill

  • Static vs abstract classes

    Just wondering if anyone knows the difference between static classes and abstract classes.
    How do static methods, static variables work?
    Is there such a thing as an abstract method?
    Thanks

    Ok i think its easier to understand if u see some examples:
    abstract class X{
    protected int value;
    public abstract void setValue(int pValue);
    class Y extends X{
    public void setValue(int pValue) {
    this.value=pValue;
    }//each class, which extends x has to implement this method, or the class has to be //declared abstract too
    class Z extends X{
    public void setValue(int pValue) {
    this.value=2*pValue;
    You can use this inheritance-tree as follows:
    public class try {
    public static void main(String[] args) {
    X try=new X() //NOT possible!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    X try=new Y();
    try.setValue(10); //the value-field of try has the value 10
    try=new Z();
    try.setValue(10); //the value-field of try has the value 20
    The techinque i used above is called "dynamical linking" and is one of the advantages of an objectoriented language.
    The main difference of abstract and static is, that you can't instantiate an abstract class direct.
    A static class or a static method and variables has just one (and only one!!) represantation during runtime. And if you want to change the value of a static variable within a method this method has to be static too.
    Example:
    public class StaticTest {
    static int counter;
    public StaticTest() {
    counter++;
    public static void print() {
    System.out.println(this.counter);
    public class TestClass {
    public static void main(String[] args) {
    StaticTest test;
    for (int i=0;i<10;i++) {
    test=new StaticTest();
    StaticTest.print(); //the output would be 10!!!!!!!!!!!!!!
    I hope this helps

  • Java abstract classes and methods

    Can anyone please tell me any real time example of abstract classes and methods.
    I want to know its real use. If anyone have ever used it for some purpose while programming please do tell me.

    Ashu_Web wrote:
    No please.. I just want to know if you have used it while programming. Like "an abstract class can be used to put all the common method names in it without having to write actual implementation code."That would describe an Interface better than an abstract class. Abstract classes usually have at least some implementation.
    I want to know its usage in programming, not just a definition. I guess you understand what I am looking for.Yes, and I gave you one: java.util.AbstractList. It can be found inside the src.zip in your JDK directory and it is a pretty good example for an abstract class that provides some implementation and defines exactly what is necessary to make a full List implementation.

  • Extending abstract classes

    I just have a simple question. I have one class which is abstract
    public abstract class Person
         private String firstName;
         private String lastName;
         private String title;
         private String dateOfBirth;
         private String homeAddress;
         private String phoneNumber;
         public static final String MR = "Mr";
         public static final String MISS = "Miss";
         public static final String MS = "Ms";
         public static final String MRS = "Mrs";
         public static final String DR = "DR";
         public static final String PROF = "Prof";
         public Person(String firstName, String lastName, String title, String dateOfBirth,
                         String homeAddress, String phoneNumber){
              this.firstName=firstName;
              this.lastName=lastName;
              this.title=title;
              this.dateOfBirth=dateOfBirth;
              this.homeAddress=homeAddress;
              this.phoneNumber=phoneNumber;
         And i have another class which extends this class
    public abstract class Borrower extends Person{
      public LibraryItem [] itemsBorrowed;
      private double currentFine;
      private int barCode;
      public LibraryItem [] getItemsBorrowed()
           return itemsBorrowed;
      public double getCurrentFine()
           return currentFine;
      public int getBarCode()
           return barCode;
      }When i try to compile these two classes, i get the error
    Cannot find symbal constructor Person(). The problem is that the tutor hates us providing default constructors, and i presume that this is what the error is asking for. Is there any way around this or does a default constructor need to be povided?
    cheers

    codingMonkey wrote:
    georgemc wrote:
    nick2price wrote:
    Ok, i get you, better call the superclass constructor as tutor hates me using no param constructorsChallenge him on that. Not only are they perfectly acceptable, they're a mandatory part of the JavaBeans spec.Personally, even though there are nothing wrong with them, I prefer to avoid no-arg constructors in a lot of cases. Usually when I feel that a class should always have certain attributes. I.e. instead of having a no-arg constructor for something like a Person class, I'd rather have a constructor that takes at least a name. It is true that the name could always be initialized in the no-arg constructor, but I would think that it makes more sense for a person to always have a name, rather than being called "null" or "N/A".If you plan on using any framework that uses the Beans spec (and while the inexperienced, self-professed "purist" might balk at that, you'll find it virtually impossible to avoid as a commercial coder) you won't be able to with those classes. Your argument about always needing a sensible starting point falls down where you have multiple disparate types that you are re-constructing. While it's quite nice to say "a Person should always have a Name", if you have, for example, a persistence framework that will generically map the results of various database queries back onto Java objects, you have to write some special case code for each class in your domain model, that says "in order to contruct this object, you first need to perform this query, then invoke this constructor with this part of the result of that query, then populate the rest of the properties using setter methods". For every class in your domain model. That's a fair amount of overhead. The no-args constructor model completely circumvents that, since everything's populated by the same generic code - beans introspection. Think about it. For every class in your model, you have to have separate chunks of code that are aware of - and hence, coupled to - a specific query, and a specific constructor of a specific class. Far from ideal.
    Even if you decide to roll your own code to manage peristence, configuration, remoting and the like, you'll still eventually settle on no-args constructors as extremely handy tools. Note that I'm all for the presence of other constructors as well, that do allow sensible creation of objects with certain values. Just that the no-args constructor is so infinitely useful for writing a huge amount of generic code
    I would think that it makes more sense for a person to always have a name, rather than being called "null" or "N/A".Me too. And there's nothing in any of my points that gainsays, or opposes that. You create a Person instance, and he's called "null" for a few clock cycles before you populate him from a database query - nothing wrong with that

  • Why Immediate and ultimate super class extends in one abstract class ?

    What�s a need to extents the two super class in single class
    public abstract class ProcessorServlet extends HttpServlet implements Servlet

    What�s a need to extents the two super class in
    single class
    public abstract class ProcessorServlet extends
    HttpServlet implements Servlet
    Only one class is being extended. HttpServlet.
    Servlet is an interface.
    You may only extend ONE class. You may implement as many interfaces as you like (there is probably some limit but not worth worrying about).

Maybe you are looking for

  • Solaris 8 on Compaq Armada E500

    Anyone install solaris 8 on Compaq Armada E500, I am having problems with the graphics card, ATI RAGE Mobility-P AGP card. Is any of the other cards compatible with this system.

  • How do I convert file formats?

    I am trying to process HD video files from a Panasonic camera. They are coming onto my Macbook pro as CPI extension files and cannot be recognized by iphoto, imovie or Final Cut Express. Is there a way to convert video files to something useable? Tim

  • Importing from Desktop

    While trying out how to use Aperture's 'filing' system I decided to start over and copied all the images in a project to a folder on my desktop. If I look inside that folder all the images are there. For some reason, when I try to import these images

  • Restricting Null Values in the report

    Hi All, I have a aggregated feild displayed in the bottom of the report and sorted on the report on that field to show me top results. When I try to run the report, Null values are coming first in the report (Displayed as NaN). I want to restrict the

  • Why 'wrong number of parameters' error in this call to a stored procedure?

    A stored procedure exists that inserts a new record and returns the newly generated record ID. This stored procedure is called from a WinForms application but at the ExecuteNonQuery time an exception is thrown indicating that the wrong number of para