Studyon Minte9.com
Head First (Java)




Abstract



* The problem

	It make sense to creat a Wolf object or a Hippo object, but what exactly is an Animal object? 
	What shape is it? What color, size ...

	%java

		package testingapp;
		public class TestingApp {
		    public static void main(String[] args) {
			
			Dog d = new Dog("gray");
			Cat c = new Cat("red");

			Animal a = new Animal("???");
		    }
		}
		class Animal {
		    protected String color;
		    public Animal(String c) {
			color = c;
		    }
		}

		class Dog extends Animal {
		    public Dog(String c) {
			super(c);
		    }
		}

		class Cat extends Animal {
		    public Cat(String c) {
			super(c);
		    }
		}
	
* Abstract class

	There is a simple way to prevent a class from beeing instantiated, by marking the class as abstract.

	%java

		package testingapp;
		public class TestingApp {
		    public static void main(String[] args) {
			Dog d = new Dog();
			Cat c = new Cat();
			Animal a = new Animal();
			    // Compile error: Abstract class can't be instantiated
		    }
		}
		abstract class Animal {
		}

		class Dog extends Animal {
		}

		class Cat extends Animal {
		}


* Abstract method

	An abstract class means the class must be extended.
	An abstract method means the method must be overridden.

	%java

		package testingapp;
		public class TestingApp {
		    public static void main(String[] args) {
			Dog d = new Dog();
		    }
		}
		abstract class Animal {
		    public abstract void eat();
		}

		class Dog extends Animal {
		   
		    @Override
		    public void eat() {}
		}

	An abstract class could implement non-abastract methods

	%java
		
		package testingapp;
		public class TestingApp {
		    public static void main(String[] args) {
			Dog d = new Dog();
		    }
		}
		abstract class Animal {
		    
		    public abstract void eat();
			// abstract method

		    public void setName(){}
			// non-abstact method (with {} implementation)
		}

		class Dog extends Animal {
		    @Override
		    public void eat() {}
		}