0% found this document useful (0 votes)
3 views20 pages

Week 11

The document provides an overview of abstract classes, methods, and interfaces in Java, explaining their purpose and usage. It includes examples of abstract classes like Animal and Shape, as well as interfaces like Vehicle and AdvancedArithmetic, demonstrating polymorphism and code reusability. Additionally, it covers the implementation of these concepts through concrete classes and methods, showcasing how to create and manipulate objects in Java.

Uploaded by

nammalwarsai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views20 pages

Week 11

The document provides an overview of abstract classes, methods, and interfaces in Java, explaining their purpose and usage. It includes examples of abstract classes like Animal and Shape, as well as interfaces like Vehicle and AdvancedArithmetic, demonstrating polymorphism and code reusability. Additionally, it covers the implementation of these concepts through concrete classes and methods, showcasing how to create and manipulate objects in Java.

Uploaded by

nammalwarsai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

1. What is the purpose of abstract method in Java?

Abstract methods in Java provide a way to define method signatures


without implementation details. They are declared in abstract classes or
interfaces and serve as placeholders to be implemented by concrete
subclasses or classes that implement the interface. Abstract methods
enable polymorphism and enforce a contract that subclasses must adhere
to, promoting code extensibility and flexibility.

2. How is final variable being different from a regular variable?

Final variables, once assigned, cannot be reassigned a new value. They act
as constants, maintaining their initial value throughout the program's
execution. In contrast, regular variables can have their values modified at
any time during execution. Final variables promote immutability, provide
clarity in code, and prevent accidental modification, enhancing code
robustness and maintainability.

3. What is an abstract class?

An abstract class in Java is a class that cannot be instantiated on its own


and may contain abstract methods—methods without implementation
details. It serves as a blueprint for other classes and often defines
common behavior and characteristics shared among its subclasses.
Abstract classes can also have concrete methods, providing default
implementations that subclasses may override. They facilitate code reuse,
polymorphism, and abstraction in object-oriented programming.

4. What is an interface?

An interface in Java is a reference type that defines a set of method


signatures without providing implementations. It acts as a contract that classes
can implement, specifying the behavior they must adhere to. Interfaces facilitate
loose coupling by allowing unrelated classes to interact based on shared
behavior rather than inheritance. They promote code flexibility, modularity, and
multiple inheritances of type.

5. Can a class implement multiple interfaces?

Yes, a class in Java can implement multiple interfaces. This feature allows
the class to inherit and provide implementations for all the methods
specified in each interface it implements. Implementing multiple interfaces
enables a class to exhibit behavior from multiple sources, promoting
flexibility and code reuse.
InLab
The Animal class is an abstract class that has an abstract method sound() and a constructor
that takes the name of the animal. The Cat and Dog classes are concrete classes that extend
the Animal abstract class and implement the sound() method. The Main class shows how to
create objects of the concrete classes and invoke the abstract and non-abstract methods.

abstract class Animal{


private String name;
// Constructor
public Animal(String name) {
this.name = name;
}

// Abstract method
public abstract void sound();

// Non-abstract method
public void printName() {
System.out.println("Name: " + name);
}
}

class Cat extends Animal {


// Constructor
public Cat(String name) {
super(name);
}

// Implementation of abstract method


@Override
public void sound() {
System.out.println("Meow");
}
}

class Dog extends Animal {


// Constructor
public Dog(String name) {
super(name);
}

// Implementation of abstract method


@Override
public void sound(){
System.out.println("Woof");
}
}

public class Main{


public static void main(String[] args) {
// Creating objects of concrete classes
Animal cat = new Cat("Fluffy");
Animal dog = new Dog("Buddy");

// Invoking abstract and non-abstract methods


cat.sound();
cat.printName();

dog.sound();
dog.printName();
}
}

Output
Meow
Name: Fluffy
Woof
Name: Buddy

2. A Java interface can only contain method signatures and fields. The interface can be used
to achieve polymorphism. In this problem, you will practice your knowledge on
interfaces.You are given an interface AdvancedArithmetic which contains a method signature
intdivisor_sum(int n). You need to write a class called MyCalculator which implements the
interface. divisorSum function just takes an integer as input and return the sum of all its
divisors. For example, divisors of 6 are 1, 2, 3 and 6, so divisor_sum should return 12. The
value of n will be at most 1000. Read the partially completed code in the editor and
complete it. You just need to write the MyCalculator class only.

import java.util.*;
interface AdvancedArithmetic{
int divisor_sum(int n);
}
class MyCalculator implements AdvancedArithmetic {
public int divisor_sum(int n) {
int sum = 0;
for (int i = 1; i <= n / 2; i++) {
if (n % i == 0) {
sum += i;
}
}
sum += n; // Adding n itself as a divisor
return sum;
}
}

class Solution{
public static void main(String []args){
MyCalculator my_calculator = new MyCalculator();
System.out.print("I implemented: ");
ImplementedInterfaceNames(my_calculator);
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.print(my_calculator.divisor_sum(n) + "\n");
sc.close();
}
/*
* ImplementedInterfaceNames method takes an object and prin
ts the name of the interfaces it implemented
*/
static void ImplementedInterfaceNames(Object o){
Class[] theInterfaces = o.getClass().getInterfaces();
for (int i = 0; i < theInterfaces.length; i++){
String interfaceName = theInterfaces[i].getName();
System.out.println(interfaceName);
}
}
}

Input (stdin)

 6
Expected Output
I implemented: AdvancedArithmetic
12

3.Create an interface Vehicle includes 2 classes Bicycle and Bike. Both Bicycle and Bike classes
implement the Vehicle interface, provides implementations for the methods defined in the
interface. Both classes have attributes for speed and gear, and they provide implementations
for changing gear, speeding up, applying brakes, and printing states. The main class creates
an instances of Bicycle and Bike, performs operations on them, and prints their present
states

// Interface
interface Vehicle {
void changeGear(int newGear);
void speedUp(int increment);
void applyBrakes(int decrement);
void printStates();
}

// Bicycle class implementing Vehicle interface


class Bicycle implements Vehicle {
int speed;
int gear;
// Constructor
public Bicycle(int speed, int gear) {
this.speed = speed;
this.gear = gear;
}

// Implementing methods from Vehicle interface


public void changeGear(int newGear) {
gear = newGear;
}

public void speedUp(int increment) {


speed += increment;
}

public void applyBrakes(int decrement) {


speed -= decrement;
}

public void printStates() {


System.out.println("Bicycle present state:");
System.out.println("Speed: " + speed + " Gear: " + gear);
}
}

// Bike class implementing Vehicle interface


class Bike implements Vehicle {
int speed;
int gear;

// Constructor
public Bike(int speed, int gear) {
this.speed = speed;
this.gear = gear;
}

// Implementing methods from Vehicle interface


public void changeGear(int newGear) {
gear = newGear;
}

public void speedUp(int increment) {


speed += increment;
}

public void applyBrakes(int decrement) {


speed -= decrement;
}
public void printStates() {
System.out.println("Bike present state:");
System.out.println("Speed: " + speed + " Gear: " + gear);
}
}

// Main class
public class Main {
public static void main(String[] args) {
// Creating instances of Bicycle and Bike
Bicycle bicycle = new Bicycle(20, 1);
Bike bike = new Bike(30, 2);

// Performing operations
bicycle.changeGear(3);
bicycle.speedUp(10);
bicycle.applyBrakes(5);
bicycle.printStates();

System.out.println();

bike.changeGear(4);
bike.speedUp(15);
bike.applyBrakes(7);
bike.printStates();
}
}

Output
Bicycle present state:
Speed: 25 Gear: 3

Bike present state:


Speed: 38 Gear: 4
PostLab

1.The Shape class is an abstract class that defines a method calculateArea() as an abstract
method. It also provides a non-abstract method displayArea(). The Circle and Rectangle
classes are concrete classes that extend the Shape abstract class and implement the
calculateArea() method. The Main class shows how to create objects of the concrete classes
and invoke the abstract and non-abstract methods

// Abstract Shape class


abstract class Shape {
// Abstract method to calculate area
public abstract double calculateArea();

// Non-abstract method to display area


public void displayArea() {
System.out.println("Area: " + calculateArea());
}
}

// Concrete Circle class extending Shape


class Circle extends Shape {
private double radius;

// Constructor
public Circle(double radius) {
this.radius = radius;
}

// Implementation of calculateArea() method


@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
// Concrete Rectangle class extending Shape
class Rectangle extends Shape {
private double length;
private double width;

// Constructor
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}

// Implementation of calculateArea() method


@Override
public double calculateArea() {
return length * width;
}
}

// Main class
public class Main {
public static void main(String[] args) {
// Creating objects of concrete classes
Circle circle = new Circle(5);
Rectangle rectangle = new Rectangle(4, 6);

// Invoking abstract and non-abstract methods


circle.displayArea();
rectangle.displayArea();
}
}

Output
Area: 78.53981633974483
Area: 24.0
2. Will the following code compile successfully? If yes, what will be the output of program?

public abstract class A { abstract void m1(A a); } public class B extends A
{ void m1(A a) { System.out.println("One"); } } public class C extends B
{ void m1(B b) { System.out.println("Two"); super.m1(new B()); } } public
class Test { public static void main(String[] args) { C c = new C();
c.m1(new B()); } }

Output
Two
One

Skill Session
1.Define an abstract base class Point that includes protected data members for the (x, y)
position of a shape, a public method to move a shape, and a public abstract method show ()
to output a shape.Derive subclasses- line, circle, and rectangle. You can represent a line as
two points, a circle as acenter and a radius, and a rectangle as two points on diagonally
opposite corners. Test the classesby selecting ten random objects of the derived classes, and
then invoking the show () method for each.

// Abstract base class Point


abstract class Point {
protected int x;
protected int y;

// Constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}

// Method to move the shape


public void move(int deltaX, int deltaY) {
x += deltaX;
y += deltaY;
}

// Abstract method to output a shape


public abstract void show();
}

// Subclass Line
class Line extends Point {
private int x2;
private int y2;

// Constructor
public Line(int x1, int y1, int x2, int y2) {
super(x1, y1);
this.x2 = x2;
this.y2 = y2;
}

// Implementing the show() method for Line


public void show() {
System.out.println("Line: (" + x + ", " + y + ") to (" + x2 + ", " + y2
+ ")");
}
}

// Subclass Circle
class Circle extends Point {
private int radius;
// Constructor
public Circle(int x, int y, int radius) {
super(x, y);
this.radius = radius;
}

// Implementing the show() method for Circle


public void show() {
System.out.println("Circle: Center(" + x + ", " + y + "), Radius: " +
radius);
}
}

// Subclass Rectangle
class Rectangle extends Point {
private int x2;
private int y2;

// Constructor
public Rectangle(int x1, int y1, int x2, int y2) {
super(x1, y1);
this.x2 = x2;
this.y2 = y2;
}

// Implementing the show() method for Rectangle


public void show() {
System.out.println("Rectangle: (" + x + ", " + y + ") to (" + x2 + ", "
+ y2 + ")");
}
}

// Test class
public class Test {
public static void main(String[] args) {
// Creating ten random objects of the derived classes and invoking
the show() method for each
Point[] shapes = new Point[10];
for (int i = 0; i < 10; i++) {
int choice = (int) (Math.random() * 3);
switch (choice) {
case 0:
shapes[i] = new Line(i, i+1, i+2, i+3);
break;
case 1:
shapes[i] = new Circle(i, i+1, i+2);
break;
case 2:
shapes[i] = new Rectangle(i, i+1, i+2, i+3);
break;
}
}

// Invoking the show() method for each shape


for (Point shape : shapes) {
shape.show();
}
}
}

Output
Line: (0, 1) to (2, 3)
Circle: Center(1, 2), Radius: 3
Rectangle: (2, 3) to (4, 5)
Line: (3, 4) to (5, 6)
Rectangle: (4, 5) to (6, 7)
Rectangle: (5, 6) to (7, 8)
Circle: Center(6, 7), Radius: 8
Line: (7, 8) to (9, 10)
Rectangle: (8, 9) to (10, 11)
Circle: Center(9, 10), Radius: 11

2.A Java abstract class is a class that can't be instantiated. That means you cannot create new
instances of an abstract class. It works as a base for subclasses. You should learn about Java
Inheritance before attempting this challenge. Following is an example of abstract class:
abstract class Book{ String title; abstract void setTitle(String s); String getTitle(){ return
title; } } If you try to create an instance of this class like the following line you will get an
error: Book new_novel=new Book (); You must create another class that extends the abstract
class. Then you can create an instance of the new class. Notice that setTitle method is
abstract too and has no body. That means you must implement the body of that method in
the child class. In the editor, we have provided the abstract Book class and a Main class. In
the Main class, we created an instance of a class called MyBook. Your task is to write just the
MyBook class

import java.util.*;
abstract class Book{
String title;
abstract void setTitle(String s);
String getTitle(){
return title;
}

}
class MyBook extends Book{
void setTitle(String s) {
title=s;
}
}
public class Main{

public static void main(String []args){


//Book new_novel=new Book(); This line prHMain.java:25: e
rror: Book is abstract; cannot be instantiated
Scanner sc=new Scanner(System.in);
String title=sc.nextLine();
MyBook new_novel=new MyBook();
new_novel.setTitle(title);
System.out.println("The title is: "+new_novel.getTitle())
;
sc.close();

}
}

Output
[User Input]
Harry Potter

[Output]
The title is: Harry Potter
3. Write an abstract class Shape with the following. • Data members: numSides •
Constructor: initialize numSides • Concrete method: get method for numSides • Abstract
methods: getArea(), getPerimeter() Write a concrete subclass Rectangle with the following. •
Data members: width, height Write a concrete subclass RtTriangle with the following. • Data
members: width, height

abstract class Shape {


protected int numSides;

// Constructor
public Shape(int numSides) {
this.numSides = numSides;
}

// Concrete method to get numSides


public int getNumSides() {
return numSides;
}

// Abstract methods to get area and perimeter


public abstract double getArea();
public abstract double getPerimeter();
}
class Rectangle extends Shape {
private double width;
private double height;

// Constructor
public Rectangle(double width, double height) {
super(4); // Rectangle has 4 sides
this.width = width;
this.height = height;
}

// Implementation of getArea() method for Rectangle


public double getArea() {
return width * height;
}

// Implementation of getPerimeter() method for Rectangle


public double getPerimeter() {
return 2 * (width + height);
}
}

class RtTriangle extends Shape {


private double width;
private double height;

// Constructor
public RtTriangle(double width, double height) {
super(3); // Right Triangle has 3 sides
this.width = width;
this.height = height;
}

// Implementation of getArea() method for RtTriangle


public double getArea() {
return 0.5 * width * height;
}

// Implementation of getPerimeter() method for RtTriangle


public double getPerimeter() {
double hypotenuse = Math.sqrt(width * width + height * height);
return width + height + hypotenuse;
}
}

public class Main {


public static void main(String[] args) {
Rectangle rectangle = new Rectangle(4, 5);
RtTriangle triangle = new RtTriangle(3, 4);
System.out.println("Rectangle:");
System.out.println("Number of sides: " + rectangle.getNumSides());
System.out.println("Area: " + rectangle.getArea());
System.out.println("Perimeter: " + rectangle.getPerimeter());

System.out.println("\nRight Triangle:");
System.out.println("Number of sides: " + triangle.getNumSides());
System.out.println("Area: " + triangle.getArea());
System.out.println("Perimeter: " + triangle.getPerimeter());
}
}

Output

Rectangle:
Number of sides: 4
Area: 20.0
Perimeter: 18.0

Right Triangle:
Number of sides: 3
Area: 6.0
Perimeter: 12.0
4.Create an interface named Drawable with an abstract method draw(). Two classes, Circle
and Rectangle, implement the Drawable interface and provide their own draw()
implementations. create instances of Circle and Rectangle, called the draw() method on each
object, and the associated messages are printed on the console. The Drawable interface
defines the abstract behavior (draw()), and concrete classes implement that behavior with
their own specific logic.

// Interface Drawable
interface Drawable {
void draw();
}

// Circle class implementing Drawable interface


class Circle implements Drawable {
public void draw() {
System.out.println("Drawing a Circle");
}
}

// Rectangle class implementing Drawable interface


class Rectangle implements Drawable {
public void draw() {
System.out.println("Drawing a Rectangle");
}
}

public class Main {


public static void main(String[] args) {
// Creating instances of Circle and Rectangle
Circle circle = new Circle();
Rectangle rectangle = new Rectangle();

// Calling draw() method on each object


circle.draw();
rectangle.draw();
}
}

Output
Drawing a Circle
Drawing a Rectangle

5.Create a generic class called AddNumbers that takes two parameters of any data type that
extends the Number class. The add() method checks the type of the parameters and returns
their sum. In the main method, create instances of the class with integer and double
parameters, and print the results of the addition.

class AddNumbers<T extends Number, U extends Number> {


public T add(T a, U b) {
if (a instanceof Integer && b instanceof Integer) {
return (T) Integer.valueOf(a.intValue() + b.intValue());
} else if (a instanceof Double && b instanceof Double) {
return (T) Double.valueOf(a.doubleValue() + b.doubleValue());
} else {
throw new IllegalArgumentException("Unsupported data types");
}
}
}

public class Main {


public static void main(String[] args) {
AddNumbers<Integer, Integer> addIntegers = new AddNumbers<>();
System.out.println("Sum of integers: " + addIntegers.add(5, 3));

AddNumbers<Double, Double> addDoubles = new AddNumbers<>();


System.out.println("Sum of doubles: " + addDoubles.add(2.5, 3.7));
}
}

Output

Sum of integers: 8
Sum of doubles: 6.2

You might also like