Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Tutorial 37 (Abstract Classes)
- //Abstract classes are something you can use when you want to start creating a class hierarchy.
- //But the base class is not going to be doing anything in itself, its only gonna act as base for other classes.
- //Machine is a base class
- //App.java
- public class App {
- public static void main(String[] args) {
- Camera cam1 = new Camera();
- cam1.setId(5);
- Car car1 = new Car();
- car1.setId(4);
- car1.run();
- //Machine machine1 = new Machine(); //Error: "cannot instantiate type Machine" see Machine.java comment
- }
- }
- //---------------------------------------------------------------------------------------------------------------------------------------
- //Machine.java
- public abstract class Machine { //adding "abstract" to "public class Machine {" prevents the user of this heirarchy from creating the base parent class, in this case: Machine
- //abstract classes can have abstract methods
- private int id;
- //then right click>generate getters and setters>check mark id> boom:
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public abstract void start(); //make methods abstract and with "@Override" to make child classes implement them
- public abstract void doStuff();
- public abstract void shutUp();
- public void run(){
- start();
- doStuff();
- shutUp();
- }
- }
- //---------------------------------------------------------------------------------------------------------------------------------------
- public class Camera extends Machine {
- @Override
- public void start() {
- System.out.println("Starting camera.");
- }
- @Override
- public void doStuff() {
- System.out.println("Taking a photo");
- }
- @Override
- public void shutUp() {
- System.out.println("Shutting down the camera.");
- }
- }
- //---------------------------------------------------------------------------------------------------------------------------------------
- public class Car extends Machine { //when you say "Car extends Machine", you are making a very strong statement that "Car is a machine.
- @Override
- public void start() {
- System.out.println("Starting camera.");
- }
- @Override
- public void doStuff() {
- System.out.println("Do stuff in car.");
- }
- @Override
- public void shutUp() {
- System.out.println("Shut up Optimus Prime.");
- }
- }
- //---------------------------------------------------------------------------------------------------------------------------------------
- /*Run Results:
- Starting camera.
- Do stuff in car.
- Shut up Optimus Prime.
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement