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 13 of 13

Thread: Abstract methods. What are they for? And when it's necessary to use them?

  1. #1
    Junior Member
    Join Date
    Jul 2010
    Posts
    21
    My Mood
    Sleepy
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Question [Resolved] Abstract methods. What are they for? And when it's necessary to use them?

    Hi, first of all I'd like to wish a Merry Christmas and a Happy New Year to all who celebrates these holidays.

    And now, to my question.
    I'm watching video tutorials from bucky, and I just can't get why and when it is necessary to use abstract methods he talks about in 55th video?
    Why don't we just create methods in classes that need them instead of creating "bodyless" abstract methods ?
    I understand that all classes that inherit from the class that implements abstract method must override it, but I just can't get the idea of such implementation. Is it just a good programming practice? Or was it just designed to remind a programmer that he must use the method?

    Thanks.
    Last edited by goodguy; December 26th, 2010 at 06:32 AM.


  2. #2
    Junior Member
    Join Date
    Oct 2010
    Posts
    21
    Thanks
    3
    Thanked 1 Time in 1 Post

    Default Re: Abstract methods. What are they for? And when it's necessary to use them?

    Hmm the only example I can provide is a number guessing game I made. I had guessinggame as an abstract classwhich normalgame and testgame extended. I set guessinggame to abstract because I didn't want it instantiated as it had no meaning without being extended, it was the children that extended the basic template class and defines the values which determined why they were that type of game. I used an abstract method because depending on the type of the game I wanted to define how the secret number was set (normal game needs no parameter as it randomly generates while for test game you pass an int to it to set yourself). By doing this it mean in the children class you can override the methods to specify what they are capable of and also stop them from doing the other.

    I'm sorry it is not the best explanation but maybe it gives you a slight idea...

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

    goodguy (December 25th, 2010)

  4. #3
    Junior Member
    Join Date
    Jul 2010
    Posts
    21
    My Mood
    Sleepy
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: Abstract methods. What are they for? And when it's necessary to use them?

    Ok, but what if you just extend guessinggame without any abstract methods, and just create those methods from scratch in normal and test game classes? Wouldn't it do the same job?

  5. #4
    Junior Member
    Join Date
    Oct 2010
    Posts
    21
    Thanks
    3
    Thanked 1 Time in 1 Post

    Default Re: Abstract methods. What are they for? And when it's necessary to use them?

    I think this will clear things up for you; abstract methods are methods that are not implemented. In order to actually use these methods you must override them in the child classes to implement functionality.

    Now you could just do what you said if you plan to instantiate two different objects, however my above method utilised polymorphism (depending on the mode selected the object instantiated is normalgame or testgame but there is only one reference e.g. case a: guessinggame g1 = new normalgame case b: guessinggame g1 = new testgame) as well so it was necessary to effectively have two different methods and override so that I could "see" and access the child method (parent classes can't see child class methods that aren't inherited and overrided).

    My understanding is by using an abstract class with abstract methods you create an easy to understand structure when looking at it from a design point of view. In the example I provided it easily enables me to create further types of game child classes and they can override the abstract method how they wish to implement the specific functionality.

    I might have tried explaining it in bad way, my apologies I've not had a huge amount of experience with using abstraction myself, hopefully someone else will be able to explain in a more concise way. May I ask what situation you are trying to implement abstraction or is it just a general question? I've only used it with polymorphism as well so I may only confuse you if I continue to try help lol
    Last edited by LDM91; December 25th, 2010 at 02:06 PM.

  6. #5
    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 methods. What are they for? And when it's necessary to use them?

    Take this example:

    You have a base class called shape. Let's say this class is used to compute the area of multiple different subclasses of shapes. How would you even begin to compute the area of a shape? It makes absolutely no sense. Instead, you declare area to be abstract, and force all sub-classes to implement area (well, all non-abstract sub classes).

    It's true that you could still define area methods in all sub-classes without the abstract declaration in shape, however it doesn't let you take advantage of polymorphism.

    public abstract class Shape
    {
        public abstract double area(); // how would you even define the area of Shape?
    }

    public class Rectangle extends Shape
    {
        double width, height;
        public Square(double width, double height)
        {
            this.width = width;
            this.height = height;
        }
     
        public double area()
        {
            return width * height; // ah, it makes sense here
        }
    }

    public class Circle extends Shape
    {
        double radius;
        public Circle(double radius)
        {
            this.radius = radius;
        }
     
        public double area()
        {
            return Math.PI * radius * radius; // ah, it makes sense here
        }
    }

    Then, to take advantage of polymorphism:

    public static double sumOfAreas(ArrayList<Shape> shapes)
    {
        // compute the area of several arbitrary shapes
        double totalArea = 0;
        for(int i = 0; i < shapes.size(); ++i)
        {
            totalArea += shapes.get(i).area();
        }
        return totalArea;
    }

    Without polymorphism, you'd have to do this:

    public static double sumOfAreas(ArrayList<Circle> circles, ArrayList<Rectangle> rectangles)
    {
        // compute the area of several circles and rectangles
        double totalArea = 0;
        for(int i = 0; i < circles.size(); ++i)
        {
            totalArea += circles.get(i).area();
        }
        for(int i = 0; i < rectangles.size(); ++i)
        {
            totalArea += rectangles.get(i).area();
        }
        return totalArea;
    }

    Notice that with the second method you're limited only to computing the area of circles and rectangles. However, with the first method you can find the total area of any number of different shapes provided they extended the base shape class. This is a simple example, but it demonstrates the power of abstraction.

    edit:

    There's more details here: General CS concepts - Abstraction (note: this deals with abstraction in general, not just abstract classes)
    Last edited by helloworld922; December 25th, 2010 at 04:07 PM.

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

    goodguy (December 26th, 2010)

  8. #6
    Junior Member
    Join Date
    Oct 2010
    Posts
    21
    Thanks
    3
    Thanked 1 Time in 1 Post

    Default Re: Abstract methods. What are they for? And when it's necessary to use them?

    Thanks for clearing up what I made a terrible mess of trying to say haha!

  9. #7
    Junior Member
    Join Date
    Jul 2010
    Posts
    21
    My Mood
    Sleepy
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: Abstract methods. What are they for? And when it's necessary to use them?

    Ah, I got it now. Thanks a lot!

    Seems like I couldn't get it at first 'cause I got use to programming in ActionScript 3 which can push any types of object into the same array, so there's no need for them to extend one common class

  10. #8
    Senile Half-Wit Freaky Chris's Avatar
    Join Date
    Mar 2009
    Posts
    834
    My Mood
    Cynical
    Thanks
    7
    Thanked 105 Times in 90 Posts

    Default Re: Abstract methods. What are they for? And when it's necessary to use them?

    Technically you could do that in Java because all classes extend Object. But that approach should be avoided at all costs.

    Any time when you cannot be 100% percent certain of what is contained within a data structure means you have an issue and you should never be put into that situation.


    Chris

  11. The Following User Says Thank You to Freaky Chris For This Useful Post:

    goodguy (December 29th, 2010)

  12. #9
    Junior Member
    Join Date
    Jul 2010
    Posts
    21
    My Mood
    Sleepy
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: Abstract methods. What are they for? And when it's necessary to use them?

    Isn't there a way to check what type of object it is?

    If I do it in AS3 I typically use something like this:

    if (myArray[0] is MovieClip) {
         trace("I found a movie clip object");
    } else {
         throw new Error("it's not a movie clip");
     }

    What construct can be used to do the same in java?
    Last edited by goodguy; December 29th, 2010 at 01:50 AM.

  13. #10
    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 methods. What are they for? And when it's necessary to use them?

    Yes, but it involves using the Java Reflection API.

    There are 2 problems with using the Reflection API:
    1. You will have very little compile-time warnings and errors that something is wrong.
    2. Your code will be mangled beyond all belief and very difficult to decipher. In fact, many code obfuscators (at least those for languages which support reflection) use reflection (along with other techniques) to make any de-compiled code near impossible to reverse engineer.

    Compare this code for summing up an array of shapes vs. the same code using reflection:

    public static double sumOfAreas(ArrayList<Object> objects) throws IllegalArgumentException, SecurityException,
    			IllegalAccessException, InvocationTargetException, NoSuchMethodException
    {
        // compute the area of several shapes
        double totalArea = 0;
        for (Object o : objectList)
        {
    	totalArea += (Double) o.getClass().getMethod("area").invoke(o);
        }
        return totalArea;
    }

    (original code re-posted)
    public static double sumOfAreas(ArrayList<Shape> shapes)
    {
        // compute the area of several arbitrary shapes
        double totalArea = 0;
        for(int i = 0; i < shapes.size(); ++i)
        {
            totalArea += shapes.get(i).area();
        }
        return totalArea;
    }

    Notice a few things:
    1. Using reflection, it's very easy to accidentally misspell the name of the method, pass the incorrect parameters to the reflected method, as well as pass incorrect parameters to the original method (the first sumOfAreas method could take an arraylist of strings, but that is disallowed in the second piece of code).
    2. What does that first piece of code even mean? This is probably one of the simplest pieces of reflection code, and even then it's extremely complex vs. the code using polymorphism and abstraction. The code gets exponentially more complex when you try to introduce generics.
    3. The error messages generated by the Reflection API are rather cryptic, compounding any issues encountered from the first two items.

    With your above example, theoretically you could use the instanceof operator, however that will limit you to number of different types of objects you can handle with that piece of code.

    In Java, if you want two methods with the same name but differ by parameter type, simply overload the method.

    public static void doit(String val)
    {
        // do something
    }
     
    public static void doit(MovieClip val)
    {
        // can do something completely different from doit(String), but could also be very similar. No need to use reflection or instanceof
    }

    Frankly, I would be surprised if ActionScript didn't provide similar object oriented tools (albeit with slightly different terminology and syntax), and I would strongly recommend going this route rather than trying to use Reflection or instanceof (or other similar variants).

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

    goodguy (December 29th, 2010)

  15. #11
    Junior Member
    Join Date
    Jul 2010
    Posts
    21
    My Mood
    Sleepy
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: Abstract methods. What are they for? And when it's necessary to use them?

    Very good reply.

    As I'm just a beginner in Java, and I didn't get used to using any of these approaches, I'll follow your advice and try to get myself used to doing everything the right way

  16. #12
    Junior Member
    Join Date
    Dec 2010
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Abstract methods. What are they for? And when it's necessary to use them?

    Quote Originally Posted by helloworld922 View Post
    Take this example:

    You have a base class called shape. Let's say this class is used to compute the area of multiple different subclasses of shapes. How would you even begin to compute the area of a shape? It makes absolutely no sense. Instead, you declare area to be abstract, and force all sub-classes to implement area (well, all non-abstract sub classes).

    It's true that you could still define area methods in all sub-classes without the abstract declaration in shape, however it doesn't let you take advantage of polymorphism.

    public abstract class Shape
    {
        public abstract double area(); // how would you even define the area of Shape?
    }
    But then why would'nt you just make that an interface as opposed to a abstract class?

  17. #13
    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 methods. What are they for? And when it's necessary to use them?

    There could be certain things which all shapes inherit, for example the location and color of the shape. In that case you have to use an abstract class because there would be object members defined and/or defined methods. However, you're right that in that form it could also be an interface.

    public abstract class Shape
    {
        public Point center;
        public Color color;
     
        public Shape(Point center, Color color)
        {
            this.center = center;
            this.color = color;
        }
     
        public abstract double area();
        public abstract double perimeter();
    }

Similar Threads

  1. abstract class
    By robinglow in forum Java Theory & Questions
    Replies: 2
    Last Post: August 20th, 2010, 01:36 AM
  2. newbie question about Abstract methods
    By FailMouse in forum Java Theory & Questions
    Replies: 3
    Last Post: August 10th, 2010, 11:51 PM
  3. Graphic Environment Abstract Methods
    By striko_514 in forum Java Theory & Questions
    Replies: 2
    Last Post: July 5th, 2010, 01:01 AM
  4. [SOLVED] Abstract Classes Help
    By SweetyStacey in forum Object Oriented Programming
    Replies: 10
    Last Post: May 6th, 2010, 06:15 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