Abstract classes

From Knowledge Kitchen
Jump to navigation Jump to search


Call-to-action

Put your own notes about abstract classes and methods here - email them to me. Use wiki syntax to format them.

The Oracle Java Tutorials offer some usefull notes, if you refuse to read your textbook!

E.Y., Spring 2019

Theory

For every group of objects, there's an imaginary abstract version of that same object

EXAMPLE:

  • There are several different breeds of big cats, like lions, tigers, and cheetahs.
  • Based on all of these cats, you can imagine a sort of "abstract cat" that comes from all of the big cats
  • This cat will have both similar characteristics of each cat (normal methods), and different elements (abstract methods)

As you can see from the example above, abstract classes are imaginary, just like the "abstract cat," therefore, they can't be instantiated

Execution

An abstract class is just like a normal concrete class, except for:

  • abstract class can contain abstract methods, and therefore,
  • it cannot be instantiated

Abstract methods are like normal methods but

  • without any curly braces{}, and
  • have the modifier abstract.
  • This method must then be implemented in any child classes.

USAGE:

  • In code, you want to use an abstract class like a super class,
  • Think of all the abstract methods as "contracts" that all the child classes have to implement
  • Abstract classes are useful if you want your child classes to implement somethings the same (normal method) and somethings different (abstract method)

Unlike an interface,

  • an abstract class can contain normal methods, so if all child objects have an identical normal method, it's better to use an abstract class
  • a child class can only inherit from one abstract class, whereas it can inherit from multiple interfaces

Coding Example:

Example Abstract Class

package edu.nyu.cs.exy205.sample;

public abstract class BigCat {
	//An Abstract Class, the child class must implement this class, but each individual child class can do so in different ways
	public abstract void hunt();
	
	//A Normal Class, this class will be inherited to be identical in all the child classes
	public void purr() {
		System.out.println("meow");
	}
}

Example of two child classes that inherit from the Abstract Class

package edu.nyu.cs.exy205.sample;

public class Lion extends BigCat {
	//Implementing the abstract class, hunt
	public void hunt() {
		System.out.println("Ambushing prey"); //This can very between different classes
	}
}
package edu.nyu.cs.exy205.sample;

public class Cheetah extends BigCat {
	//Implementing an abstract class, hunt
	public void hunt() {
		System.out.println("Chasing prey"); 
	}
}

Test Polymorphism

package edu.nyu.cs.exy205.sample;

public class TestCats {

	public static void main(String[] args) {
		BigCat simba = new Lion();
		BigCat cheatah = new Cheetah();
		
		//Using polymorphism to put all the bigCats into one array
		BigCat[] bigCats = {
			simba, 
			cheatah
		};
		
		//You can then batch call all the bigCats, so you can immediatly have every cat hunt, even if the method is different
		for (BigCat breed : bigCats) {
			breed.hunt();
			breed.purr();
		}
		
	}

}

K.R., Spring 2019

What are Abstract Classes?

-A java Abstract class is used to provide common method implementation to all the subclasses or to provide default implementation. -The Abstract keyword is used to create abstract classes in java (Class declared as abstract). -They cannot be instantiated (will need a constructor), but can be subclassed. -They may include abstract methods, but this is not neccesary for an abstract class. -a Subclass of an abstract class in java must implement all abstract methods unless the subclass is an abstract class as well.

Example of a abstract class:

//Notice the ABSTRACT keyword before class
public abstract class GotCharacter {
   private String name;
   private String Family;
   private int age;

   public GotCharacter(String name, String Family, int age) {
      System.out.println("Constructing an GotCharacter");
      this.name = name;
      this.Family = Family;
      this.age = age;
   }
   
   public void Introduction() {
      System.out.println("I am... " + this.name + "of house" + this.Family);
   }

   public String toString() {
      return name + " " + Family + " " + age;
   }

   public String getName() {
      return name;
   }
 
   public String getFamily() {
      return Family;
   }
   // In case of marriage
   public void setFamily(String newFamily) {
      Family = newFamily;
   }
 	
   public int getAge() {
      return age;
   }
}

...To inherit the properties of this class you must do...

public class Gold extends GotCharacter{
	private int gold; //too purchase a good ale

	public Gold(String name, String Family, int age, int gold) {
      super(name, Family, age);
      setGold(gold);
   }
   public int getGold() {
      return gold;
   }
   public void goldDelivery() {
      System.out.println("Within Dragon delivery zone ");
      System.out.println("Dropping" + getName() + "'s " + gold + "pieces of gold");
   }

}


...Trying to instantiate the GotCharacter class like below will result in an error...

public class AbstractPractice {

   public static void main(String [] args) {
      // Following would raise an error because GotCharacter cannot be instantiated 
      //you cannot create instances of abstract classes using the new operator.
      GotCharacter Jon = new GotCharacter("Aegon Targaryen", "Targaryen", 22);
      System.out.println("Created Jon.....");
      Jon.Introduction();
   }
}

Abstract Methods

-A method that is declared without any implementation -If abstract methods are used, the class itself must be declared as abstract, or the code will not compille:

abstract public class AbstractClass
	{abstract public void abstractMethod();
}

...If you wish to implement the code above you must do...

public class ImplementingTheAbstractClass extends AbstractClass
{
    public void abstractMethod() { System.out.print("we are using the abstractMethod()"); }
}

..Trying to implement the like example below will result in an error...

public class ImplementingTheAbstractClass extends AbstractClass
{
    // This will give an error
}



Abstract classes with no abstract methods

-Creates classes that cannot be instantiated. -These classes can only be inherited. -Example:

// An abstract class without no abstract method 
abstract class Winterfell {    
    void Stark() { System.out.println("Got Stark() called...Winter is coming"); } 
} 
   
class Got extends Winterfell { } 
   
class Main { 
    public static void main(String args[]) {  
        Got Arya = new Got(); 
        Arya.Stark(); 
    } 
}

Output: Got Stark() called...Winter is coming


Abstract classes with Final Methods

-Abstract classes can also have final methods as well
-Example:
// An abstract class with a final method
abstract class Winterfell {    
    final void Stark() { System.out.println("Got Stark() called...Winter is coming"); } 
} 
   
class Got extends Winterfell { } 
   
class Main { 
    public static void main(String args[]) {  
       	Winterfell Sansa = new Got(); 
        Sansa.Stark(); 
    } 
}

Output: Got Stark() called...Winter is coming

Overall rules of Abstract methods

1) Abstract methods DO NOT have a body, they only have their method signature 2) If a class has a abstract method, the class itself should be declared abstract 3) a regular class extends an abstract class it must implement all the abstract methods of the parent class or it must be declared abstract too.


What links here

What links here