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

Hands On Inheritance, Polymorphism, Abstract Class, Interface

1. The document contains code snippets for different OOP concepts like inheritance, polymorphism, abstraction, interface etc. 2. The snippets include code for a Doctor class inheriting from a Person class, a Multiplier class with overloaded methods, an abstract Person class, a Printer interface implemented by a LaserPrinter class, a Hosteller class extending Student class, a Passenger class, and Employee classes calculating salary. 3. The code provides examples to demonstrate OOP concepts with classes, objects, inheritance, polymorphism etc.

Uploaded by

voreka
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
0% found this document useful (0 votes)
220 views20 pages

Hands On Inheritance, Polymorphism, Abstract Class, Interface

1. The document contains code snippets for different OOP concepts like inheritance, polymorphism, abstraction, interface etc. 2. The snippets include code for a Doctor class inheriting from a Person class, a Multiplier class with overloaded methods, an abstract Person class, a Printer interface implemented by a LaserPrinter class, a Hosteller class extending Student class, a Passenger class, and Employee classes calculating salary. 3. The code provides examples to demonstrate OOP concepts with classes, objects, inheritance, polymorphism etc.

Uploaded by

voreka
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1/ 20

--PersonIsADoctor-Inheritance

public class Person


{
//include the attribute specified in the question
String name;

public class Doctor extends Person // inherit name from Person in Doctor class
{
String specializationType;
//inlcude the required attribute and method as per the problem statement
public String displayDetails(){
return name + "is a " + specializationType;
}

public class Driver


{
public static void main(String[] args)
{
//create a object for Doctor, set the name and specialization, invoke the method
and print the result
Doctor doc= new Doctor();
doc.displayDetails();
}

}
-------------------------------------------------------------

Multiplier - Overloading

public class Multiplier{

//include the overloaded methods and perform the logic as specified in the
problem statement
public static int multiply(int x,int y){
return(x*y);
}
public static int multiply(int x,int y,int z){
return(x*y*z);
}
public static double multiply(double x,double y){
return(x*y);
}
}

public class Driver{

public static void main(String[] args){

//create the object of Multiplier and invoke the overloaded methods

Multiplier m = new Multiplier();


System.out.println(m.multiply(10,20));
System.out.println(m.multiply(10,20,30));
System.out.println(m.multiply(11,20));
}

----------------------------------------------------------------
PersonIsADoctor-Abstract

abstract public class Person


{
//include the attribute specified in the question
String name;

public Person(String name){


this.name=name;
}
public String getName(){
return name;
}

public class Doctor extends Person// inherit name from Person in Doctor class
{
//inlcude the required attribute and method as per the problem statement
String specializationType;
public Doctor(String name,String specializationType){
super(name);
this.specializationType=specializationType;
}
public String getSpecializationType(){
return specializationType;
}
public String displayDetails(){
return super.getName()+" is a "+getSpecializationType();
}
}

public class Driver


{
public static void main(String[] args)
{
//create a object for Doctor, set the name and specialization, invoke the method
and print the result
Doctor p= new Doctor("xxx","student");
System.out.println(p.displayDetails());
}

-----------------------------------------------------------------------------------
-----------------------
Printer-Interface

//Create a interface Printer with an abstract method print


//print method signature: public String print()
interface Printer{
public String print();
}

//create a class ,override the print() method and return the String as expected in
the problem statement
class LaserPrinter implements Printer{

public String print(){


return "Laser Printer Printing";
}

public class Driver{

public static void main(String[] args)


{
//create an object of LaserPrinter with reference as Printer and invoke the
print method and display the result
LaserPrinter l = new LaserPrinter();
l.print();

}
-----------------------------------------------------------------------------------
------------------------

Contact Details of Hosteller

public class Student{


protected int studentId;
protected String name;
protected int departmentId;
protected String gender;
protected String phone;

public int getStudentId(){


return studentId;
}
public void setStudentId(int studentId){
this.studentId=studentId;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public int getDepartmentId(){
return departmentId;
}
public void setDepartmentId(int departmentId){
this.departmentId=departmentId;
}
public String getGender(){
return gender;
}
public void setGender(String gender){
this.gender=gender;
}
public String getPhone(){
return phone;
}
public void setPhone(String phone){
this.phone=phone;
}

public class Hosteller extends Student{


private String hostelName;
private int roomNumber;

public String getHostelName(){


return hostelName;
}
public void setHostelName(String hostelName){
this.hostelName=hostelName;
}
public int getRoomNumber(){
return roomNumber;
}
public void setRoomNumber(int roomNumber){
this.roomNumber=roomNumber;
}
}

import java.util.Scanner;
public class Main{
public static Hosteller getHostellerDetails()
{
Hosteller h=new Hosteller();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Details:");
System.out.println("Student Id");
int a=sc.nextInt();
System.out.println("Student Name");
sc.nextLine();
String b=sc.nextLine();
System.out.println("Department Id");
int c=sc.nextInt();
System.out.println("Gender");
sc.nextLine();
String d=sc.nextLine();
System.out.println("Phone Number");
String e=sc.nextLine();
System.out.println("Hostel Name");
String f=sc.nextLine();
System.out.println("Room Number");
int g=sc.nextInt();
h.setStudentId(a);
h.setName(b);
h.setDepartmentId(c);
h.setGender(d);
h.setPhone(e);
h.setHostelName(f);
h.setRoomNumber(g);
System.out.println("Modify Room Number(Y/N)");
char i=sc.nextLine().charAt(0);
if(i=='Y'){
System.out.println("New Room Number");
int x=sc.nextInt();
h.setRoomNumber(x);
}
System.out.println("Modify Phone Number(Y/N)");
char j=sc.nextLine().charAt(0);
if(j=='Y'){
System.out.println("New Phone Number");
sc.nextLine();
String y=sc.nextLine();
h.setPhone(y);
}
return h;
}
public static void main(String args[])
{
Hosteller h1=new Hosteller();
h1=getHostellerDetails();
System.out.println("The Student Details");
System.out.println(h1.getStudentId()+" "+h1.getName()+"
"+h1.getDepartmentId()+" "+h1.getGender()+" "+h1.getPhone()+" "+h1.getHostelName()
+" "+h1.getRoomNumber());
}

-----------------------------------------------------------------------------------
----------------------------------------------------------------

PassengerDetails

public class Passenger{


private int ticketid;
private String name;
private String gender;
private String address;

public Passenger (int ticketid, String name, String gender, String address){
this.ticketid=ticketid;
this.name=name;
this.gender=gender;
this.address=address;
}

@Override
public String toString(){
return
"ticketid:"+ticketid+",name:"+name+",gender:"+gender+",address:"+address;

}
public int getTicketid(){
return ticketid;
}
public void setTicketid(int ticketid){
this.ticketid=ticketid;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public String getGender(){
return gender;
}
public void setGender(String gender){
this.gender=gender;
}
public String getAddress(){
return address;
}
public void setAddress(String address){
this.address=address;
}
}

import java.util.*;
import java.util.Scanner;
import java.util.ArrayList;
public class Main{

public static void main(String agrs[]){


ArrayList bookingList=new ArrayList();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the no.of passengers:");
int number = sc.nextInt();
for(int i=1;i<=number;i++){
System.out.println("Passenger"+i);
System.out.println("Enter the ticketid:");
int a=sc.nextInt();
System.out.println("Enter the name:");
sc.nextLine();
String b = sc.nextLine();
System.out.println("Enter the gender:");
sc.nextLine();
String c = sc.nextLine();
System.out.println("Enter the address:");
sc.nextLine();
String d = sc.nextLine();

Passenger p = new Passenger(a,b,c,d);


System.out.println(p.toString());

}
}

-----------------------------------------------------------------------------------
--------
PF and Salary Calculation

public class Employee{


private String name;
private float salary;
private float netsalary;
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setSalary(float salary){
this.salary=salary;
}
public float getSalary(){
return salary;
}
public void setNetsalary(float netsalary){
this.netsalary=netsalary;
}
public float getNetsalary(){
return netsalary;
}
}

public class PermanentEmployee extends Employee{

private float pfpercentage;


private float pfamount;
public void setPfpercentage(float pfpercentage){
this.pfpercentage=pfpercentage;
}
public float getPfpercentage(){
return pfpercentage;
}
public void setPfamount(float pfamount){
this.pfamount=pfamount;
}
public float getPfamount(){
return pfamount;
}
public void findNetSalary(){
float x=0;
pfamount=(super.getSalary()*pfpercentage)/100;
x=super.getSalary() - pfamount;
setNetsalary(x);
}
public boolean validateInput(){
System.out.println("salary" + super.getSalary() + "percentage" +
pfpercentage );
if((super.getSalary()>0) && (pfpercentage>=0))
return true;
else
return false;
}
}
import java.util.Scanner;
public class Main{
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
System.out.println("Enter the name:");
String a =sc.nextLine();
System.out.println("Enter the salary:");
float b =sc.nextFloat();
System.out.println("Enter the pfpercentage:");
float c =sc.nextFloat();
boolean d= true;
PermanentEmployee p = new PermanentEmployee();
p.setName(a);
p.setSalary(b);
p.setPfpercentage(c);
d=p.validateInput();
if(d==false){
System.out.println("Error!!! Unable to calculate the NetSalary.");
}
else{
p.findNetSalary();
System.out.println("Employee Name:"+p.getName());
System.out.println("PF Amount:"+String.format("%.2f",p.getPfamount()));

System.out.println("NetSalary:"+String.format("%.2f",p.getNetsalary()));
}
}
}

-----------------------------------------------------------------------------------
------------------

Check for Existence of Customer - equals method

public class Customer{


private String name;
private String panno;
private String emailid;
private int salary;

public Customer(String name,String panno,String emailid,int salary){


this.name=name;
this.panno=panno;
this.emailid=emailid;
this.salary=salary;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public String getPanno(){
return panno;
}
public void setPanno(String panno){
this.panno=panno;
}
public String getEmailid(){
return emailid;
}
public void setEmailid(String emailid){
this.emailid=emailid;
}
public int getSalary(){
return salary;
}
public void setSalary(int salary){
this.salary=salary;
}
public boolean equals (Object o){
Customer c = (Customer) o;
if(c.panno.equals(this.panno) && c.emailid.equals(this.emailid))
return true;
else
return false;
}
}

import java.util.Scanner;
public class Main{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter the name:");
sc.nextLine();
String a =sc.nextLine();
System.out.println("Enter the panno:");
sc.next();
String b =sc.nextLine();
System.out.println("Enter the emailid:");
sc.next();
String c =sc.nextLine();
System.out.println("Enter the salary:");
int d =sc.nextInt();
System.out.println("Enter the name:");
sc.nextLine();
String e =sc.nextLine();
System.out.println("Enter the panno:");
sc.next();
String f =sc.nextLine();
System.out.println("Enter the emailid:");
sc.next();
String g =sc.nextLine();
System.out.println("Enter the salary:");
int h =sc.nextInt();
Customer a1=new Customer(a,b,c,d);
Customer a2=new Customer(e,f,g,h);
boolean a3= true;
a3=a1.equals(a2);
if(a3==true)
System.out.println("Both the objects are equal.");
else
System.out.println("Both the objects are not equal.");

}
}
-----------------------------------------------------------------------------------
----------------------------

Area Calculation - abstract class

abstract public class Shape{


abstract public double calculateArea();
}

import java.lang.Math;
public class Circle extends Shape{
private float radius;
public Circle(float radius){
this.radius=radius;
}
@Override
public double calculateArea(){
return Math.PI*(radius*radius);
}
}

public class Rectangle extends Shape{


private float length;
private float breadth;
public Rectangle(float length,float breadth){
this.length=length;
this.breadth=breadth;
}
@Override
public double calculateArea(){
return length*breadth;
}
}

public class Triangle extends Shape{


private float base;
private float height;
public Triangle(float base,float height){
this.base=base;
this.height=height;
}
@Override
public double calculateArea(){
return 0.5*base*height;
}
}

import java.util.Scanner;

public class Main{


public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the shape:");
String shape = sc.nextLine();
if(shape=="Circle"){
System.out.println("Enter the radius:");
float a = sc.nextFloat();
Circle c= new Circle(a);
double circlearea = c.calculateArea();
System.out.println("The area of Circle is : "+circlearea);
}
else if (shape=="Rectangle"){
System.out.println("Enter the length:");
float b = sc.nextFloat();
System.out.println("Enter the breadth:");
float d = sc.nextFloat();
Rectangle r= new Rectangle(b,d);
double rectanglearea = r.calculateArea();
System.out.println("The area of Circle is : "+rectanglearea);
}
else if (shape=="Triangle"){
System.out.println("Enter the base:");
float e = sc.nextFloat();
System.out.println("Enter the height:");
float f = sc.nextFloat();
Triangle t= new Triangle(e,f);
double trianglearea = t.calculateArea();
System.out.println("The area of Circle is : "+trianglearea);
}

-----------------------------------------------------------------------------------
---------------------

Account Manipulation - Abstract class

public class Customer {

//Attributes
private int customerId;
private String customerName;
private String emailId;

//Constructor
public Customer(int customerId, String customerName, String emailId) {
super();
this.customerId = customerId;
this.customerName = customerName;
this.emailId = emailId;
}

//Getters and Setters


public int getCustomerId() {
return customerId;
}

public void setCustomerId(int customerId) {


this.customerId = customerId;
}

public String getCustomerName() {


return customerName;
}

public void setCustomerName(String customerName) {


this.customerName = customerName;
}

public String getEmailId() {


return emailId;
}

public void setEmailId(String emailId) {


this.emailId = emailId;
}

abstract public class Account {

protected int accountNumber;


protected Customer customerObj;
protected double balance;

public Account(int accountNumber,Customer customerObj,double balance){


this.accountNumber=accountNumber;
this.customerObj=customerObj;
this.balance=balance;
}
abstract public boolean withdraw(double amount);

//Uncomment the getters and setters after writing the attributes

public int getAccountNumber() {


return accountNumber;
}

public void setAccountNumber(int accountNumber) {


this.accountNumber = accountNumber;
}

public Customer getCustomerObj() {


return customerObj;
}

public void setCustomerObj(Customer customerObj) {


this.customerObj = customerObj;
}

public double getBalance() {


return balance;
}

public void setBalance(double balance) {


this.balance = balance;
}

}
public class SavingsAccount extends Account{
private double minimumBalance;

public SavingsAccount(int accountNumber,Customer customerObj,double


balance,double minimumBalance){
/* super.accountNumber = accountNumber;
super.customerObj = customerObj;
super.balance = balance;*/
super(accountNumber,customerObj,balance);
this.minimumBalance=minimumBalance;
}

//Uncomment the getters and setters after writing the attributes

public double getMinimumBalance() {


return minimumBalance;
}

public void setMinimumBalance(double minimumBalance) {


this.minimumBalance = minimumBalance;
}
public boolean withdraw(double amount){
if((super.balance-amount)>minimumBalance){
super.balance=(super.balance - amount);
return true;
}
else {
return false;
}
}

public class Main{

public static void main(String args[]){


Customer cust = new Customer(123,"xx","xxxxxxxxxxxx@gmail.com");
SavingsAccount savacc = new SavingsAccount(1236,cust,100000,1000);

boolean output=savacc.withdraw(20000);
System.out.println(output);
}
}

-----------------------------------------------------------------------------------
-----------------------------------------

Vehicle-Loan-Insurance - Use Interface

public class Vehicle implements Loan, Insurance{

private String vehicleNumber;


private String modelName;
private String vehicleType;
private double price;

public String getVehicleNumber() {


return vehicleNumber;
}
public void setVehicleNumber(String vehicleNumber) {
this.vehicleNumber = vehicleNumber;
}
public String getModelName() {
return modelName;
}
public void setModelName(String modelName) {
this.modelName = modelName;
}

public String getVehicleType() {


return vehicleType;
}
public void setVehicleType(String vehicleType) {
this.vehicleType = vehicleType;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}

public Vehicle(String vehicleNumber, String modelName, String


vehicleType,double price) {

this.vehicleNumber = vehicleNumber;
this.modelName = modelName;
this.vehicleType=vehicleType;
this.price = price;
}
@Override
public double issueLoan(){
if (vehicleType.startsWith("4")){
return price*80.0/100.0;
}
else if (vehicleType.startsWith("3")){
return price*75.0/100.0;
}
else if (vehicleType.startsWith("2")){
return price*50.0/100.0;
}

return 0;
}
@Override
public double takeInsurance(){
if(price<=150000){
return 3500;
}
else if(price>150000 && price<=300000){
return 4000;
}
else if(price>300000){
return 5000;
}
return 0;
}

public interface Loan{


abstract double issueLoan();
}

public interface Insurance{


abstract double takeInsurance();
}

import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Vehicle Vehi = new Vehicle("AS1234","Hero","2 wheeler",300000);
System.out.println(Vehi.issueLoan());
System.out.println(Vehi.takeInsurance());

}
}

-----------------------------------------------------------------------------------
--------------------------------------

Employee Loan Eligibility - Polymorphism

public abstract class Employee


{
protected int employeeId;
protected String employeeName;
protected double salary;

//Getters and Setters


public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}

//Write a public 2 argument constructor with arguments – employeeId,and


employeeName
public Employee(int employeeId,String employeeName){
this.employeeId=employeeId;
this.employeeName=employeeName;
}

//Write a method - public void calculateSalary()


abstract public void calculateSalary();
//Make this method as abstract

//Make this class inherit the Employee class

public class PermanentEmployee extends Employee


{
private double basicPay;

// Getters and Setters

public double getBasicPay() {


return basicPay;
}

public void setBasicPay(double basicPay) {


this.basicPay = basicPay;
}

//1. Write a public 3 argument constructor with arguments – employeeId,


employeeName and basicPay.
public PermanentEmployee(int employeeId,String employeeName,double basicPay){
super(employeeId,employeeName);
this.basicPay=basicPay;
}

//2. Implement the - public void calculateSalary() - method


@Override
public void calculateSalary(){
double pfamount = basicPay*0.12;
salary = basicPay - pfamount;
setSalary(salary);
}

//Make this class inherit the Employee class


public class TemporaryEmployee extends Employee{

private int hoursWorked;


private int hourlyWages;

// Getters and Setters

public int getHoursWorked() {


return hoursWorked;
}
public void setHoursWorked(int hoursWorked) {
this.hoursWorked = hoursWorked;
}
public int getHourlyWages() {
return hourlyWages;
}
public void setHourlyWages(int hourlyWages) {
this.hourlyWages = hourlyWages;
}

//1. Write a public 4 argument constructor with arguments – employeeId,


employeeName, hoursWorked and hourlyWages.
public TemporaryEmployee(int employeeId,String employeeName,int
hoursWorked,int hourlyWages){
super(employeeId,employeeName);
this.hoursWorked=hoursWorked;
this.hourlyWages=hourlyWages;
}

//2. Implement the - public void calculateSalary() - method


@Override
public void calculateSalary(){
double salary= hourlyWages*hoursWorked;
setSalary(salary);
}

public class Loan {

//Implement the below method

//public double calculateLoanAmount(Employee employeeObj) {

//}
public double calculateLoanAmount(Employee employeeObj){
double loan =0.0;
if(employeeObj instanceof PermanentEmployee){
loan=employeeObj.getSalary()*15.0/100.0;
}
if(employeeObj instanceof TemporaryEmployee){
loan=employeeObj.getSalary()*10.0/100.0;
}
return loan;
}

import java.util.Scanner;
public class Main{

public static void main(String[] args){


Scanner sc=new Scanner(System.in);
PermanentEmployee perem=new PermanentEmployee(101,"xxx",10000);
TemporaryEmployee temem=new TemporaryEmployee(102,"xxxxx",5,100);

Loan ln= new Loan();


double peremloan = ln.calculateLoanAmount(perem);
double tememloan = ln.calculateLoanAmount(temem);

System.out.println(peremloan);
System.out.println(tememloan);

-----------------------------------------------------------------------------------
-----------------------------------

Date Validation - Use SimpleDateFormat

import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.ParseException;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
SimpleDateFormat sf = new SimpleDateFormat("dd/MM/yyyy");

sf.setLenient(false);
//String date= "31/08/2020";
String date=sc.next();

try{
sf.parse(date);
System.out.println(date+" is a valid date");
}
catch(ParseException e){
System.out.println(date+" is not a valid date");
}
//FILL THE CODE

-----------------------------------------------------------------------------------
-------------------

Calculate Expiry Date - Use Calendar

import java.util.*;
import java.text.*;

public class Main {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
try{
SimpleDateFormat d= new SimpleDateFormat("dd/MM/yyyy");
//DateFormat date_con = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
String date = sc.next();
Date d2 = d.parse(date);

int months = sc.nextInt();


Calendar c = Calendar.getInstance();
c.setTime(d2);
c.add(Calendar.MONTH,months);
Date d6 = c.getTime();
System.out.println(d.format(d6));

}
catch(ParseException e){
System.out.println(e);
}
//FILL THE CODE

-----------------------------------------------------------------------------------
-----------------------------

Calculate Years of Experience

import java.util.Scanner;
import java.text.*;

import java.util.*;

public class Main {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);

//FILL THE CODE


try{
SimpleDateFormat date = new SimpleDateFormat("dd/MM/yyyy");
String d4 = ("15/12/2020");
Date d1 = date.parse(d4);
String d3 = sc.next();
Date d2 =date.parse(d3);
long diff = d1.getTime()-d2.getTime();
long diff2 = diff/1000;
System.out.println(diff2/31536000+" years");
}
catch(ParseException e){
System.out.println(e);
}

}
------------------------------------------------------
*--------------------------------------------------------

You might also like