[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.
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...
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?
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
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.
Code Java:
public abstract class Shape
{
public abstract double area(); // how would you even define the area of Shape?
}
Code Java:
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
}
}
Code Java:
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:
Code Java:
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:
Code Java:
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)
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!
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
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
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:
Code Java:
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?
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:
(original code re-posted)
Code Java:
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.
Code Java:
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).
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 :)
Re: Abstract methods. What are they for? And when it's necessary to use them?
Quote:
Originally Posted by
helloworld922
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.
Code Java:
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?
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.
Code Java:
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();
}