Core Java Tutorial

Core Java Tutorial

What is Java Abstract Classes and Methods

Abstract class:

Abstract class be used if you want to share code among several closely related classes, the class that has common code can be declared as abstract class.

Abstract Method:

An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:

abstract void salary(double basicPay);

Rules for defining abstract class

Abstract classes cannot be instantiated (creating object will thow an error).

Abstract class may or may not include abstract methods, but they can be subclassed.

Example:

abstract class User

{

 String name;

 int age;

 long ph;

 void salary()

 {

  System.out.println("salary");

 }

}


class Employee extends User

{

 String specialization;

}


class Manager extends User

{

 String department;

}

 

class Main

{

 public static void main(String[] args)

 {

  User u1 = new User(); // throws an error

  Employee e1 = new Employee();

  e1.name = "Candid";

  e1.age = 22;

  e1.ph = 123456789 l;

  e1.specialization = "Java";

  Manager m1 = new Manager();

  m1.name = "java";

  m1.age = 25;

  m1.ph = 345789 l;

  m1.department = "HR";

  System.out.println(e1.name);

  System.out.println(e1.age);

  System.out.println(e1.ph);

  System.out.println(e1.specialization);

  System.out.println(m1.name);

  System.out.println(m1.age);

  System.out.println(m1.ph);

  System.out.println(m1.department);

 }

}