Hope anyone can help, i am learning Java and as comparable to anyone else in this forum i guess i am a newbie to programming as well.
I have come across a chapter on abstract class and methods but don't really fully understand what they are used for and why, and thought i would get an explanation from someone who is an experienced programmer.
Below i have example code i have been working on, with the help from this book, what i am not sure about is why in the class Dims do i have to have abstract double area() when each sub class uses an area method anyway, or is it calling the area method from the super class, why do you have to have methods that override?
// Using abstract methods and classes
package Training2;
abstract class Dims {
double dim1;
double dim2;
Dims(double a, double b) {
dim1 = a;
dim2 = b;
}
// area is now an abstract method
abstract double area();
}
class Rectangles extends Dims {
Rectangles(double a, double b) {
super(a, b);
}
// Override area for Rectangles
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangles extends Dims {
Triangles(double a, double b) {
super(a, b);
}
// Override area for right Triangles
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 /2;
}
}
public class AbstractAreas {
public static void main(String args[]) {
// Dims d = new Dims(10, 10); // Illegal now
Rectangles r = new Rectangles(9, 5);
Triangles t = new Triangles(10, 8);
Dims dimref; // This is OK, no object is created
dimref = r;
System.out.println("Area is " + dimref.area());
dimref = t;
System.out.println("Area is " + dimref.area());}
}
Apologies for the waffling on but i really need some guidance.
Thanks in advance.