Week 6 of OOP in JAVA
Write a Java program using an interface Shape that declares a method area(). Implement the interface in two classes Circle and Rectangle to calculate their respective areas.
interface Shape{
void area();
}
class Circle implements Shape{
double radius;
Circle(double r){
radius = r;
}
public void area(){
double a = 3.14 * radius * radius;
System.out.println("Area of Circle = " + a);
}
}
class Rectangle implements Shape{
double length, breadth;
Rectangle(double l, double b){
length = l;
breadth = b;
}
public void area(){
double a = length * breadth;
System.out.println("Area of Rectangle = " + a);
}
}
public class ShapeInterfaceDemo{
public static void main(String[] args){
Circle c = new Circle(5);
Rectangle r = new Rectangle(4,6);
c.area();
r.area();
}
}
Write a Java program where two interfaces InternalMarks and ExternalMarks declare methods for accepting marks. A class Result implements both interfaces and calculates the total marks.
interface InternalMarks{
void setInternal(int m);
}
interface ExternalMarks{
void setExternal(int m);
}
class Result implements InternalMarks, ExternalMarks{
int internal, external;
public void setInternal(int m){
internal = m;
}
public void setExternal(int m){
external = m;
}
void total(){
System.out.println("Internal Marks = " + internal);
System.out.println("External Marks = " + external);
System.out.println("Total Marks = " + (internal + external));
}
}
public class ResultDemo{
public static void main(String[] args){
Result r = new Result();
r.setInternal(40);
r.setExternal(55);
r.total();
}
}
Write a Java program using an interface Bank that contains methods deposit() and withdraw(). Implement this interface in a class Account to simulate basic banking operations.
import java.util.Scanner;
interface Bank{
void deposit(double amount);
void withdraw(double amount);
}
class Account implements Bank{
double balance = 0;
public void deposit(double amount){
balance += amount;
System.out.println("Deposited: " + amount);
System.out.println("Balance: " + balance);
}
public void withdraw(double amount){
if(amount > balance){
System.out.println("Insufficient balance");
}
else{
balance -= amount;
System.out.println("Withdrawn: " + amount);
System.out.println("Balance: " + balance);
}
}
}
public class BankDemo{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Account acc = new Account();
System.out.print("Enter deposit amount: ");
double d = sc.nextDouble();
acc.deposit(d);
System.out.print("Enter withdraw amount: ");
double w = sc.nextDouble();
acc.withdraw(w);
}
}
Comments