Week 11
Week 11
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.
4. What is an interface?
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 method
public abstract void sound();
// Non-abstract method
public void printName() {
System.out.println("Name: " + name);
}
}
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();
}
// Constructor
public Bike(int speed, int gear) {
this.speed = speed;
this.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
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
// Constructor
public Circle(double radius) {
this.radius = radius;
}
// Constructor
public Rectangle(double length, double width) {
this.length = length;
this.width = 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);
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.
// Constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
// 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;
}
// Subclass Circle
class Circle extends Point {
private int radius;
// Constructor
public Circle(int x, int y, int radius) {
super(x, y);
this.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;
}
// 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;
}
}
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{
}
}
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
// Constructor
public Shape(int numSides) {
this.numSides = numSides;
}
// Constructor
public Rectangle(double width, double height) {
super(4); // Rectangle has 4 sides
this.width = width;
this.height = height;
}
// Constructor
public RtTriangle(double width, double height) {
super(3); // Right Triangle has 3 sides
this.width = width;
this.height = height;
}
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();
}
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.
Output
Sum of integers: 8
Sum of doubles: 6.2