Mark As Completed Discussion

Special Methods in Object-Oriented Programming

Now you know the bare bones of Object-Oriented Programming. But, as I said in the previous lesson, there is still much more you have to discover. In today's lesson, we will go through a number of special functions that almost all OOP-supported programming languages have for convenience.

Special Methods in Object-Oriented Programming

Keep in mind that these functions are utility functions and are not essential for OOP programming languages, meaning that you can do the same things with or without these functions. However, you'll save a tremendous amount of effort and lines of code if you know these functions. So let's begin. We will be improving our previous example based on Shapes with the new knowledge we will learn in this lesson.

Let's recap what we learned previously and see the final implementation of all the Shape classes.

TEXT/X-JAVA
1// Shape.java
2public class Shape {
3    protected int maxWidth;
4    protected int maxHeight;
5
6    // Getters and Setters
7    public int getMaxWidth() { return maxWidth; }
8    public int getMaxHeight() { return maxHeight; }
9    public void setMaxWidth(int maxWidth) { this.maxWidth = maxWidth; }
10    public void setMaxHeight(int maxHeight) { this.maxHeight = maxHeight; }
11    public int getMaxArea() { return maxWidth*maxHeight; }
12
13    public double getArea() {
14        return getMaxArea();
15    }
16}
17
18// Circle.java
19public class Circle extends Shape {
20    protected int radius;
21
22    // Getters and Setters
23    public int getRadius() { return radius; }
24    public void setRadius(int radius) { this.radius = radius; }
25
26    @Override
27    public double getArea() {
28        return 3.14*radius*radius;
29    }
30}
31
32
33// Rectangle.java
34public class Rectangle extends Shape {
35    protected int height;
36    protected int width;
37
38    // Getters and Setters
39    public int getHeight() { return height; }
40    public int getWidth() { return width; }
41    public void setWidth(int width) { this.width = width; }
42    public void setHeight(int height) { this.height = height; }
43
44    @Override
45    public double getArea() {
46        return (double)height*width;
47    }
48}
49
50// Main.java
51public class Main {
52    public static void main(String[] args) {
53        // Your code here
54    }
55}