You are on page 1of 6

BIRLA INSTITIUTE OF TECHNOLOGY AND SCIENCE PILANI

Hyderabad Campus
Second Semester 2019-20
Object-Oriented Programming System (CS F213)
LAB 5

This lab introduces abstract classes and abstract methods in Java.

Abstraction: Hides the implementation details, shows only functionality.

Abstract method: the body (implementation of the method) is not provided; uses abstract keyword. For
example, the following is an abstract method:
abstract void func(int);

Abstract class: It is also written using abstract keyword. For example:


abstract class A {
/* other code */
}

An abstract class may contain one or more abstract methods. For example:
abstract class A {
/* other code */
abstract void func(int);
void anotherFunc() {
/*implementation */
}
}

An abstract class cannot be instantiated (objects cannot be created). So,


A obj = new A(); // error
results in error.

A class that contains an abstract method must be declared abstract. The following class must be abstract as it
contains an abstract method.
class B { //error, must be abstract as it contains abstract method
/* other code */
abstract void func(int);
void anotherFunc() {
/*implementation */
}
}

An abstract class is inherited and the child class must provide implementation of the abstract methods or else
declare themselves to be abstract. The following class Bike is abstract and contains abstract method run().
Hence its child class Hero and KTM must provide implementation of run () as we want to create objects of
Hero and KTM (else the children classes also need to be declared as abstract).

Example 1

abstract class Bike{


abstract void run();
Bike(){
System.out.println(“Bike’s constructor”);
}
void changeGear(){
System.out.println("gear changed");
}
}

class Hero extends Bike {


void run(){
System.out.println("avg speed 70 kmph");
}
}

class KTM extends Bike {


void run(){
System.out.println("avg speed 100 kmph");
}
}

class TestBike {
public static void main(String[] args){
Bike obj;
obj = new Hero();
obj.changeGear();
obj.run();
obj = new KTM();
obj.run();
}
}

Example 2

abstract class Bank {


abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest(){
return 4;
}
}
class AxisBank extends Bank {
int getRateOfInterest(){
return 7;
}
}
class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new AxisBank();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}
}

Even though abstract class cannot be instantiated, it may contain constructors. These constructors are called
first whenever a child object is created.
Example 3

abstract class Bank {


String country;
Bank() {
country="India";
}
abstract int getRateOfInterest();
String getCountry(){
return country;
}
}
class SBI extends Bank{
int getRateOfInterest(){
return 4;
}
}
class AxisBank extends Bank {
int getRateOfInterest(){
return 7;
}
}
class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new AxisBank();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
System.out.println("Country: " + b.getCountry());

}
}

Exercise 1: Consider Dog class and its subclasses from Lab 4. Since avgBreedWeight() is common
to all breeds of dogs, it makes sense to put it in the Dog class. However, Dog class, without any
breed, cannot have avgBreedWeight() method. How can avgBreedWeight () be made available in
Dog class?

//Dog.java
public class Dog {
protected String name;
public Dog(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String speak() {
return "Woof";
}
}

//Labrador.java
public class Labrador extends Dog {
private String colour; //black, yellow, or chocolate?
private static int breedWeight = 35; //kgs
public Labrador(String name, String colour) {
this.colour = colour;
}

public String speak() {


return "WOOF"; //big woof
}

public static int avgBreedWeight() {


return breedWeight;
}
}

//Yorkshire.java
public class Yorkshire extends Dog {

public Yorkshire(String name) {


super(name);
}

public String speak() {


return "woof"; //small woof
}
}

//Test.java
public class Test {
public static void main(String[] args) {
Dog dog = new Dog("dog");
System.out.println(dog.getName()+" says " + dog.speak());
}
}

Exercise 2: Implement an abstract class Shape that contains abstract method calcArea(). Now create child
classes of Shape called Square and Circle that implement calcArea().

Exercise 3: Create an abstract class Person in a package called oops.java.mypack. It contains private members
name and gender, a constructor Person(String name, String gender), an abstract method typeWork(). Create
two subclass of Person called Student and Employee. Student contains private string studID and Employee
contains private string empID. They implement typeWork() to print “studies” and “works”. Now extend
Employee to Staff and Faculty classes that override typeWork() to print “Non teaching work” and “Teaching
work”, respectively.

Examples of private, public, protected and default access specifiers.

Subclass
Access Class Package outside Others
package
Private Y - - -
Public Y Y Y Y
Protected Y Y Y -
Package Y Y - -

Private:
Example 4
class A {
private int pr;
private void prMethod() {
System.out.println("private method");
}
}

class B {
void func() {
A a = new A();
a.pr = 1; // error
a.prMethod(); // error
}
}
From object of B, private methods of A cannot be accessed, as can be seen above.

However, the following is fine:


Example 5
class A {
private int pr;
void setpr(int i) {
pr = i; //fine
}
void demoMethod(A a) {
System.out.println(a.pr); //fine, no error
}

public static void main(String[] args) {


A obj = new A();
obj.setpr(10);
A obj2 = new A();
obj2.demoMethod(obj);
}
}

So, objects of the same type can access each other’s private members. Above, obj2 accessed obj’s private
member pr.

Public:
Everyone has access to public members - even in different packages. Easiest to understand and use.

Protected:
All classes in the same package can access it. Additionally, subclasses in other packages can also access it.
However, there is a specific scenario when subclass is in a different package that you should remember. It is
made clear with the help of the following example.
Example 6
//file A.java
package mypack1;
public class A {
protected int prot;
protected void protMethod() {
System.out.println("protected method");
}
}
//file B.java
package mypack2;
import mypack1.*;

class B extends A {
public static void main(String[] args) {
A a = new A();
B b = new B();
a.prot=10; // error
a.protMethod(); //error
b.prot=10;
b.protMethod();
}
}

In the above example, protected members are accessible in class B that is in different package, but only using
its own object. It cannot access protected members using A’s object.

Package:
Default access. Class or members accessible only within the package.

Exercise 4: You need to calculate the percent of marks scored by a student in three subjects (each out of 100),
and by another student in four subjects (each out of 100). Create an abstract class Marks with an abstract method
getPercent(). It is inherited by two classes A and B. Classes A and B each have a method with the same name
which returns the percent marks scored by a student. The constructor of A takes the marks in three subjects as
its parameters and the marks in four subjects as its parameters for B. Create an object for each of the two classes
and print the percentage of marks for both the students.

Exercise 5: You need to calculate the area of a rectangle, a square and a circle. Create an abstract class Shape
with three abstract methods namely RectArea() taking two parameters (length and breadth), SquareArea() and
CircleArea() taking one parameter each (length and radium, resp.). Create another class Area implementing all
the three methods RectArea(), SquareArea() and CircleArea() of Shape class for printing the area of rectangle,
square and circle respectively. Create an object of class Area and call all the three methods.

Exercise 6: Given the Book class below, create its child class MyBook (in MyBook.java file) that has a
parameterized constructor that takes three parameters: title, author and price. It implements the abstract display()
method to print title, author and price of the book. Take title, author and price as input from the user, create an
object of MyBook and call its display() method.

abstract class Book {


String title;
String author;
Book(String t, String a) {
title = t;
author = a;
}
abstract void display();
}

You might also like