Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: Abstract Classes Help

  1. #1
    Junior Member
    Join Date
    Apr 2010
    Location
    Inverness - Scotland
    Posts
    21
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Abstract Classes Help

    I'm currently studying Java Programming with no previous experience of programming what so ever (yes it was silly but i'll learn) and I was wondering if anyone can explain in simple terms what an abstract class is and give me an example how to write code for it.

    Thanks, Stacey


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Abstract Classes Help

    Abstract classes are classes that have at least one abstract method in them. They're used in conjunction with the other object-oriented ideas such as polymorphism and inheritance.

    Ex.: Say you wanted to have a class that generally represents some type of shape. How would you calculate the area of a shape? There's not really any answer because there are an infinite number of different shapes. This would be a good candidate to declare an abstract method for.

    public abstract class Shape
    {
         public abstract double Area();
    }

    Now if you defined a certain type of shape, like circle or square, you can implement this function.

    public class Square extends Shape
    {
         private double side;
     
         public Square(double side)
         {
              this.side = side;
         }
     
         public double area()
         {
              return this.side * this.side;
         }
    }
     
    public class Circle
    {
         private double radius;
     
         public Circle(double radius)
         {
              this.radius = radius;
         }
     
         public double area()
         {
              return this.radius * this.radius * Math.PI;
         }
    }

    So what's the point of having the abstract class in the first place anyways? All it's doing there is taking up space because the Circle and Square classes could have easily been defined and used without the Shape class.

    However, what if your program doesn't know what kind of shape it's going to be handling (it could be a circle, square, triangle, etc.)? By using the shape class you can guarantee that at least the area() method will exist and must be called with 0 parameters, and will have a return type of double.

    public class Tester
    {
         public static void main(String[] args)
         {
              Shape[] shapes = new Shape[5];
              // create a few different shapes
              shapes[0] = new Circle(4.5);
              shapes[1] = new Square(3);
              shapes[2] = new Circle(7);
              shapes[3] = new Square(1);
              shapes[4] = new Circle(1.23);
     
              double averageArea = computeAverageArea(shapes);
              System.out.println("The average area of the shapes was " + averageArea);
         }
     
         public static double computeAverageArea(Shape[] shapes)
         {
              double average = 0;
              for (int i = 0; i < shapes.length; i++)
              {
                   average += shapes[i].area();
              }
              return average;
         }
    }

    Some notes about abstract classes:
    Interfaces are basically purely abstract classes (i.e. all methods are abstract). You can also define classes to implement multiple Interfaces while all classes can only extend one other class (either abstract or not).

    Abstract Classes and Interfaces can not be instantiated, but they can have a constructor. Also, just because they can't be instantiated doesn't mean you can't declare a variable to hold that type (see the above example).

    and one last comment, Java is a good language to start learning from It's got good documentation, a wide user base, and shares the syntax and coding style of a lot of other very powerful languages. It has the advantage of being simple while still being very powerful.

  3. The Following User Says Thank You to helloworld922 For This Useful Post:

    SweetyStacey (April 18th, 2010)

  4. #3
    Junior Member
    Join Date
    Apr 2010
    Location
    Inverness - Scotland
    Posts
    21
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Abstract Classes Help

    Thanks for that, was well put

    I bought a book called "Beginning Programming with Java for Dummies" It covers pretty much everything in the basics apart from abstracts and that happens to be the first assignment in my course..just my luck.

    Do you think it's worth buying the second book in that series called "Java for Dummies" it bases it on java 6 which is what my course is on?



    Stacey

  5. #4
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Abstract Classes Help

    Sun (well, now Oracle) has a good tutorial on their website (Link) that can take you through the basics of the language. They're completely free, but I think they were designed for people that have some previous programming experience. I'd suggest taking a look at them first, and then the book if you feel like you still need the extra help (granted, I've never looked at that book so I'm not quite sure at the quality of the content). It's ok if it doesn't make sense at first, some of those concepts are quite difficult to grasp at first.

    Also, you can ask your questions here and we'll try our best to answer them or point you in the right direction.

  6. #5
    Forum old-timer
    Join Date
    Nov 2008
    Location
    Faversham, Kent, UK
    Posts
    472
    My Mood
    Mellow
    Thanks
    4
    Thanked 58 Times in 54 Posts

    Default Re: Abstract Classes Help

    Just to add - an important use of abstract classes is to hold code and data that is common to all the subclasses. Don't duplicate the same data and code in every subclass, push it up into an abstract superclass. This way, each subclass only has the features that make it different from the superclass and the other subclasses. This expresses a principle known as DRY (Don't Repeat Yourself).

  7. #6
    Member
    Join Date
    Apr 2010
    Location
    The Hague, Netherlands
    Posts
    91
    Thanks
    3
    Thanked 10 Times in 10 Posts

    Default Re: Abstract Classes Help

    Quote Originally Posted by dlorde View Post
    Just to add - an important use of abstract classes is to hold code and data that is common to all the subclasses. Don't duplicate the same data and code in every subclass, push it up into an abstract superclass. This way, each subclass only has the features that make it different from the superclass and the other subclasses. This expresses a principle known as DRY (Don't Repeat Yourself).
    Actually, this is not entirely correct, though you mean right. You don't just push in all the codes and data to the superclass, you should think more on the line of: give the right objects the right responsibility's, but if that responsibility's has different kind of codes what would you do? No, in the abstract class you don't just put code, but in this case for example you put in your abstract class a abstract method and the actual code you put in the subclasses. But this doesn't take away you should work DRY, that was a good advice.

  8. #7
    Forum old-timer
    Join Date
    Nov 2008
    Location
    Faversham, Kent, UK
    Posts
    472
    My Mood
    Mellow
    Thanks
    4
    Thanked 58 Times in 54 Posts

    Default Re: Abstract Classes Help

    Quote Originally Posted by Bryan View Post
    Actually, this is not entirely correct, though you mean right. You don't just push in all the codes and data to the superclass, you should think more on the line of: give the right objects the right responsibility's, but if that responsibility's has different kind of codes what would you do? No, in the abstract class you don't just put code, but in this case for example you put in your abstract class a abstract method and the actual code you put in the subclasses. But this doesn't take away you should work DRY, that was a good advice.
    Actually this is not entirely correct, though you mean well

    I didn't say 'just push in all the codes and data to the superclass', I said push common code and data to the superclass. By 'common', I mean code that is shared by all the subclasses (I also said "Don't duplicate the same data and code"). This is a common (no pun intended) refactoring that most good IDEs provide a facility to do automatically.

    Please comment on what I actually said, not what you think I said.

    <pedant>Incidentally, the plural of 'code', in programming, is 'code', not 'codes'.</pedant>

  9. #8
    Member
    Join Date
    Apr 2010
    Location
    The Hague, Netherlands
    Posts
    91
    Thanks
    3
    Thanked 10 Times in 10 Posts

    Default Re: Abstract Classes Help

    Yeah, we are talking about the same thing but in different ways. You say common code, I say responsibility.

    Let me explain why I don't say common code. Lets say you have some code that validates some input. And there are 2 very different kind of objects which both needs the validating code. You can't go to both its superclass and put the code in that class even though its common code. Its not its responsibility, instead you need a Validator object or something similar. Do you get what I mean?
    Last edited by Bryan; May 5th, 2010 at 02:32 PM.

  10. #9
    Forum old-timer
    Join Date
    Nov 2008
    Location
    Faversham, Kent, UK
    Posts
    472
    My Mood
    Mellow
    Thanks
    4
    Thanked 58 Times in 54 Posts

    Default Re: Abstract Classes Help

    Quote Originally Posted by Bryan View Post
    Yeah, we are talking about the same thing but in different ways. You say common code, I say responsibility.
    With respect, we're not talking about the same thing at all - responsibility is the class's abstract role or task set - what the class must do according to its contract. Common code is the shared implementation of that responsibility - how the class/subclass exercises its responsibilities - and don't forget the common data.

    I guess the difference is semantically somewhat similar to the difference between a class and an instance.

    Lets say you have some code that validates some input. And there are 2 very different kind of objects which both needs the validating code. You can't go to both its superclass and put the code in that class even though its common code. Its not its responsibility, instead you need a Validator object or something similar. Do you get what I mean?
    If you're talking about classes that are not part of the same hierarchy, i.e. don't have a common superclass because there is no common 'is-a' relation (no Liskov Substitution relation), then yes - clearly you can't push the common code up to a common superclass, because there isn't one, or they are already subclasses of different superclasses. But we were talking about a single class hierarchy - context is important...
    Last edited by dlorde; May 5th, 2010 at 03:01 PM.

  11. #10
    Member
    Join Date
    Apr 2010
    Location
    The Hague, Netherlands
    Posts
    91
    Thanks
    3
    Thanked 10 Times in 10 Posts

    Default Re: Abstract Classes Help

    Alright, I get your point on your first comment.

    Quote Originally Posted by dlorde View Post
    If you're talking about classes that are not part of the same hierarchy, i.e. don't have a common superclass because there is no common 'is-a' relation (no Liskov Substitution relation), then yes - clearly you can't push the common code up to a common superclass, because there isn't one, or they are already subclasses of different superclasses. But we were talking about a single class hierarchy - context is important...
    Ok, lets take a single class hierarchy. Lets say a User system? In this User system I have a UserService that provides me with the User objects, its like a DataMapper. And those users have points(doesn't matter what kind). These points are retrieved from a different site.

    How would you do this? Where would you put the retrieval from the points? Seen your stand of view I would guess in UserService? Or the User superclass?

  12. #11
    Forum old-timer
    Join Date
    Nov 2008
    Location
    Faversham, Kent, UK
    Posts
    472
    My Mood
    Mellow
    Thanks
    4
    Thanked 58 Times in 54 Posts

    Default Re: Abstract Classes Help

    Quote Originally Posted by Bryan View Post
    Ok, lets take a single class hierarchy. Lets say a User system? In this User system I have a UserService that provides me with the User objects, its like a DataMapper. And those users have points(doesn't matter what kind). These points are retrieved from a different site.

    How would you do this? Where would you put the retrieval from the points? Seen your stand of view I would guess in UserService? Or the User superclass?
    So what is the User hierarchy? UserService sounds like a factory so wouldn't be part of the hierarchy, and I'm not sure why the points coming from 'a different site' is relevant. You haven't described enough about the User super/subclasses and the points for me to answer the question.

    My point is simply that when you have a number of siblings in a hierarchy that use common implementation and data, you should look to minimise the redundancy by pushing up the common code and data to the superclass where possible/practical. It's a standard refactoring technique.

    So if all User subclasses (UserA, UserB, UserC) have 'points' members, and have some common method implementations to manage these members, the points and the common methods (e.g. accessors & basic mutators) should be pushed up to the User superclass. IOW if all sibling subclasses have data X and non-polymorphic method Y, X and Y should be in the superclass. The subclasses then represent only the specialisations of the superclass.

    There are many variations on the theme, e.g. the Template Method pattern for when partial polymorphism is required, but it's pretty standard stuff.

    I get the feeling we're talking at cross-purposes in some way...

Similar Threads

  1. Java: interfaces and abstract classes
    By pinansonoyon in forum Object Oriented Programming
    Replies: 1
    Last Post: May 6th, 2010, 10:17 AM
  2. A Question Regarding Abstract Classes & Packages
    By Kerubu in forum Object Oriented Programming
    Replies: 3
    Last Post: December 21st, 2009, 01:27 PM
  3. [SOLVED] Error "TitleChanger is abstract; cannot be instantiated"
    By Uzual in forum AWT / Java Swing
    Replies: 2
    Last Post: May 26th, 2009, 11:23 AM
  4. [SOLVED] Java program using two classes
    By AZBOY2000 in forum Object Oriented Programming
    Replies: 7
    Last Post: April 21st, 2009, 06:55 AM
  5. Java program with abstract class along with two subclasses
    By crazydeo in forum Collections and Generics
    Replies: 2
    Last Post: June 10th, 2008, 11:45 AM