Abstract Classes

An abstract class is a class that is declared as abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed/referenced..
An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon).

Syntax: public abstract void methodname(args);

Abstract methods are usually declared where two or more subclasses are expected to do a similar thing in different ways through different implementations. These subclasses extend the same Abstract class and provide different implementations for the abstract methods.

Organization Chart

If the class is having at least one abstract method then that class should be an abstract.
Abstract class can contain normal methods and abstract methods.
An abstract class may have static fields and static methods. You can use these static members with a class reference

Program to find the sum of 2nos using abstract methods

abstract class abc
{
int a,b;
public void get(int x,int y)
{
a=x;
b=y;

}
public abstract void put();
}
class xyz extends abc
{
public void put()
{
System.out.println("Sum of 2bnos "+(a+b));

}
public void put1()
{
System.out.println("Sub of 2nos"+(a-b));

}
}
public class abs1 {

            public static void main(String[] args) {
// TODO Auto-generated method stub
xyz x=new xyz();
x.get(30, 43);
x.put();
x.put1();

//          abc y=new abc();  --- illegal
abc y=new xyz(); // polymorphisam/reference
y.get(21, 12);
y.put();
//y.put1() -- not accesable
}

}

 

 

 

Program on Abstract methods and hierarchical inheritance.

abstract class engine
{
int modalno,year;
String make;
public engine(int m,int y,String mk)
{
modalno=m;
year=y;
make=mk;
}
public abstract void put();
}
class maruthi extends engine
{
public maruthi(int m,int y,String mk)
{
super(m,y,mk);
}         
public void put()
{
System.out.println("Engineno:"+modalno+"Year : "+year+"Make : "+make);
}
}

class honda extends engine
{
public honda(int m,int y,String mk)
{
super(m,y,mk);
}
public void put()
{
System.out.println("Engineno:"+modalno+"Year : "+year+"Make : "+make);
}
}
class benz extends engine
{
public benz(int m,int y,String mk)
{
super(m,y,mk);
}

public void put()
{
System.out.println("Engineno:"+modalno+"Year : "+year+"Make : "+make);
}
}

 

class sample
{
public static void main(String args[])
{
maruthi m=new maruthi(101,2015,"2Cylinder");
honda n=new honda(102,2014,"4Cylinder");
benz o=new benz(103,2013,"1Cylinder");
m.put();
n.put();
o.put();

                                    //  Poly morphisam

                                    engine x;
x=m;
x.put();
x=n;
x.put();
x=o;
x.put();
}
}

 

For
Online Classes

Contact Us: 9885348743