Abstract Methods

Abstract methods are methods declared without an implementation (no body and semicolon at the end).

1

2

3

abstractvoidgetSalary();

An important thing to remember about abstract methods is that if a class has one or more abstract methods then the class itself must also be declared abstract. The reason is that an abstract method has no implementation and so it wouldn’t be possible to instantiate an object of such a class (partially implemented).

1

2

3

4

5

6

7

8

9

10

11

12

13

14

publicclassEmployee{

protectedStringposition;

protectedintexperience;

privateStringname;

publicStringgetName(){

returnname;

}

// compiler error (abstract methods can only be in an abstract class)

abstractvoidgetSalary();

}

Abstract Classes

The things that you need to know about abstract classes for the exam are:

They cannot be instantiated, but can be extended

They may or may not have abstract methods

If a subclass of an abstract class doesn’t provide implementations for all the abstract methods, it must also be declared abstract

They may have static fields and static methods

Unlike interfaces:

They can contain implemented methods

They can contain fields that aren’t constants (static and final)

Abstract classes implementing interfaces are allowed not to implement all of the interface methods, but the subclasses must implement the remaining methods:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

interfaceI{

voidmethod1();

voidmethod2();

voidmethod3();

}

// this abstract class only implements one method from interface I

abstractclassAimplementsI{

publicvoidmethod1(){

// some implementation here

}

abstractvoidmethod4();

}

// this descendant of A implements the remaining methods from interface I

classBextendsA{

publicvoidmethod2(){

// some implementation here

}

publicvoidmethod3(){

// some implementation here

}

voidmethod4(){

// some implementation here

}

}

That’s all coders! If you have any comments or questions, you can drop me a line or leave a comment below and I will be pleased to help you.

In case you’re looking for a complete (but still short, precise and to-the-point) study guide to help you get your valuable Oracle® Java Programmer certification, including many tricky real-exam-like questions, study sheets, and other bonuses, then the Java Certification Roadmap book is your book.

Finally, if you found this content useful and know more programmers, colleagues or friends that may be interested in getting the Java Certification, click one of the buttons belowclick the button on the bottom left corner of your screen to let them know about the Java Certification Roadmap.