JAVA PROGRAMS
Access modifier in java-
In a class if any method become abstact then that class also become abstarct.
- abstract method are define in derived class.
- we cannot created an object of a abstract class.
- object is created of the class which is derived from it.
- abstract method is also called pure virtual function in c++.
Q1)define a abstract class shape with the abstract method area and volume. write a java program to calculate area and volumme of cone, cylinder.
---->
abstract class Shape
{
abstract void area();
abstract void volume();
}
class Cone extends Shape
{
void area(float r,float h)
{
System.out.println("area of cone is"+3.14*r*h);
}
void volume(float r,float h)
{
System.out.println("volume of cone is"+(1/3)*3.24*r*r*h);
}
}
class Cylinder extends Shape
{
void area()
{
System.out.println("area of cylinder is"+2*3.14*r*h);
}
void volume(float r,float h)
{
System.out.println("volume of cylinder is"+3.14*r*h);
}
}
class Main
{
public static void main(String ar[])
{
Cone co=new Cone();
Cylinder cy=new Cylinder();
co.area(2.1,2.4f);
co.volume(3.3,3.4f);
cy.area(3.1,6.2);
cy.volume(4.3,6,4);
}
}
{
abstract void area();
abstract void volume();
}
class Cone extends Shape
{
void area(float r,float h)
{
System.out.println("area of cone is"+3.14*r*h);
}
void volume(float r,float h)
{
System.out.println("volume of cone is"+(1/3)*3.24*r*r*h);
}
}
class Cylinder extends Shape
{
void area()
{
System.out.println("area of cylinder is"+2*3.14*r*h);
}
void volume(float r,float h)
{
System.out.println("volume of cylinder is"+3.14*r*h);
}
}
class Main
{
public static void main(String ar[])
{
Cone co=new Cone();
Cylinder cy=new Cylinder();
co.area(2.1,2.4f);
co.volume(3.3,3.4f);
cy.area(3.1,6.2);
cy.volume(4.3,6,4);
}
}
--------------------------------------------------------------------------------------------
Q2) Define an abstract class “Staff” with members name and address. Define two subclass
of this class – “FullTimeStaff” (department, salary) and
partTimeStaff(number_of_hours, rate_per_hour). Define appropriate constructors.
Create “n” objects which could be of either FullTimeStaff or PartTimeStaff class by
asking the user‟s choice Display details of all “FullTimeStaff” objects and all
“PartTimeStaff” objects.
Q2) Define an abstract class “Staff” with members name and address. Define two subclass
of this class – “FullTimeStaff” (department, salary) and
partTimeStaff(number_of_hours, rate_per_hour). Define appropriate constructors.
Create “n” objects which could be of either FullTimeStaff or PartTimeStaff class by
asking the user‟s choice Display details of all “FullTimeStaff” objects and all
“PartTimeStaff” objects.
---->
import java.io.BufferedReader;
import java.io.InputStreamReader;
abstract class Staff{
String name,address;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public abstract void accept();
public abstract void display();
}
class FullTimeStaff extends Staff{
String dept;
float sal;
public void accept() {
try{
System.out.println("Enter Name:\t");
name=br.readLine();
System.out.println("Enter Address:\t");
address=br.readLine();
System.out.println("Enter Department:\t");
dept=br.readLine();
System.out.println("Enter Salary:\t");
sal=Float.parseFloat(br.readLine());
}catch(Exception e){
System.out.println(e.getLocalizedMessage());
}
}
public void display() {
System.out.println("-------------------------------------------------------");
System.out.println("Name:\t"+name);
System.out.println("Address:\t"+address);
System.out.println("Department:\t"+dept);
System.out.println("Salary:\t"+sal);
System.out.println("-------------------------------------------------------");
}
}
class PartTimeStaff extends Staff{
int no_of_hrs;
float rate_per_hr;
public void accept() {
try{
System.out.println("Enter Name:\t");
name=br.readLine();
System.out.println("Enter Address:\t");
address=br.readLine();
System.out.println("Enter No of hours:\t");
no_of_hrs=Integer.parseInt(br.readLine());
System.out.println("Enter Rate per hour:\t");
rate_per_hr=Float.parseFloat(br.readLine());
}catch(Exception e){
System.out.println(e.getLocalizedMessage());
}
}
public void display() {
System.out.println("-------------------------------------------------------");
System.out.println("Name:\t"+name);
System.out.println("Address:\t"+address);
System.out.println("No of Hours:\t"+no_of_hrs);
System.out.println("Rate Per Hour:\t"+rate_per_hr);
System.out.println("-------------------------------------------------------");
}
}
public class DemoStaff {
public static void main(String[] args) {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try{
System.out.println("Enter No of staff member?:\t");
int n=Integer.parseInt(br.readLine());
int ch;
int i=1;
Staff s;
if(n>=0){
do{
System.out.println("1.Full Time Staff");
System.out.println("2.Part Time Staff");
System.out.println("Enter Choice:\t");
ch=Integer.parseInt(br.readLine());
switch (ch) {
case 1:
s=new FullTimeStaff();
s.accept();
s.display();
break;
case 2:
s=new PartTimeStaff();
s.accept();
s.display();
break;
}
}while(i<=n);
}else {
System.out.println("N cant be less than 1");
}
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
Q3)Create an abstract class shape. Derive three classes sphere, cone and cylinder from
it. Calculate area and volume of all (use method overriding).
package slip1;
abstract class Shape{
final float pi=3.142f;
abstract public float area();
abstract public float volume();
}
class Sphere extends Shape{
float Radius;
public Sphere(float r) {
// TODO Auto-generated constructor stub
Radius=r;
}
@Override
public float area() {
// TODO Auto-generated method stub
//4pir2
return 4*pi*(Radius*Radius);
}
@Override
public float volume() {
// TODO Auto-generated method stub
//(4/3)pir3
return (4/3)*pi*(Radius*Radius);
}
}
class Cylinder extends Shape{
float Radius,Height;
public Cylinder(float r,float h) {
// TODO Auto-generated constructor stub
Radius=r;
Height=h;
}
@Override
public float area() {
// TODO Auto-generated method stub
//2pirh
return 2*pi*Radius*Height;
}
@Override
public float volume() {
// TODO Auto-generated method stub
//pir2h
return pi*(Radius*Radius)*Height;
}
}
class Cone extends Shape{
float Radius,Height,Side;
public Cone(float r,float h,float s) {
// TODO Auto-generated constructor stub
Radius=r;
Height=h;
Side=s;
}
@Override
public float area() {
// TODO Auto-generated method stub
//pirside
return pi*Radius*Side;
}
@Override
public float volume() {
// TODO Auto-generated method stub
//(1/3)pir2h
return (1/3)*pi*(Radius*Radius)*Height;
}
}
public class AbstractClass {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Shape s=new Sphere(2.2f);
System.out.println("Sphere Area:\t"+s.area());
System.out.println("Sphere Volume:\t"+s.volume());
Shape s1=new Cylinder(4.2f,3.4f);
System.out.println("Cylinder Area:\t"+s1.area());
System.out.println("Cylinder Volume:\t"+s1.volume());
Shape s2=new Cone(42.2f,1.1f,10.4f);
System.out.println("Cone Area:\t"+s2.area());
System.out.println("Cone Volume:\t"+s2.volume());
}
}
----------------------------------------------------------------------------------------------------
constructor
- constructor is a special member function or method whose class name and function name is same.
- constructor is use to initiliase the value.
- constructor should always be public.
- constructor does not return any value.
- more than one constructor in class is called multiple constructor.
- more than one constructor having different parameter is called constructor overloading.
type of constructor -
- default constructor
- parametrized constructor
- copy constructor
- dynamic constructor
- super constructor
but java support only two constructor default or parametrized
e.g -
class A
{
A()
A()
{
}
A(int a,int b)
}
A(int a,int b)
{
}
}
void show(int x,int y)
{
}
}
class B
{
public static void main(String args[])
public static void main(String args[])
{
A x=new A();
A x=new A();
A y=new A(2,3);
y.show(3,2);
}
}
EXAMPLES -
Q1)Define a class SavingAccount (acno, name, balance). Define appropriate
constructors and operations withdraw(), deposit(), and viewbalance(). The
minimum balance must be 500. Create an object and perform operations. Raise user
defined “InsufficientFundsException” when balance is not sufficient for withdraw
operation.
--->
import java.io.*;
class InsufficientFundsException extends Exception
{
}
class SavingAccount
{
int acNo;
String name;
int bal;
SavingAccount(int n,String na,int b)
{
this.acNo=n;
this.bal=b;
this.name=na;
}
void viewCreditAmount()
{
System.out.println("Balance is:--"+this.bal);
}
void withdraw(int add)
{
try
{
bal-=add;
if(bal<500)
{
bal+=add;
throw new InsufficientFundsException();
}
}
catch(Exception e)
{
System.out.println("balance is not sufficient for withdraw operation");
}
viewCreditAmount();
}
void deposit(int add)
{
bal+=add;
viewCreditAmount();
}
void show()
{
System.out.println("Name is:--"+this.name);
System.out.println("No is:--"+this.acNo);
viewCreditAmount();
}
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter no of objects:--");
int r=Integer.parseInt(br.readLine());
for(int i=0;i<r;i++)
{
System.out.println("Enter name:--");
String name=br.readLine();
System.out.println("Enter no:--");
int n=Integer.parseInt(br.readLine());
System.out.println("Enter Balance:--");
try
{
int n1=Integer.parseInt(br.readLine());
if(n1<500)
{
throw new InsufficientFundsException();
}
else
{
SavingAccount s=new SavingAccount(n,name,n1);
System.out.println("Enter amount to deposite:--");
int n5=Integer.parseInt(br.readLine());
s.deposit(n5);
System.out.println("\nEnter amount to withdraw:--");
int n2=Integer.parseInt(br.readLine());
s.withdraw(n2);
s.show();
}
}
catch(Exception e)
{
System.out.println("Balance is no sufficient:--");
}
}
}
}
-----------------------------------------------------------------------------------------
Q2)Define a class MyNumber having one private integer data member. Write a default
constructor to initialize it to 0 and another constructor to initialize it to a value (use
this). Write methods isNegative, isPositive, isZero, isOdd, isEven. Create an object
in main. Use command line arguments to pass a value to the object and perform the
above tests.
-->
public class MyNumber {
private int num;
public MyNumber() {
num=0;
}
public MyNumber(int num) {
this.num=num;
}
public int isNegative(){
if(num<0) return 1;
if(num==0) return 0;
else return 2;
}
public int isPossitve(){
if(num>0) return 1;
if(num==0) return 0;
else return 2;
}
public boolean isZero(){
if(num==0) return true;
else return false;
}
public boolean isOdd(){
if(num%2!=0) return true;
else return false;
}
public boolean isEven(){
if(num%2==0) return true;
else return false;
}
public static void main(String[] args) {
if(args.length==1){
try{
MyNumber num=new MyNumber(Integer.parseInt(args[0]));
int check=num.isNegative();
System.out.print("Number is Negative:\t");
if(check==1) System.out.println("true");
else if(check==0) System.out.println("is Zero");
else System.out.println("false");
check=num.isPossitve();
System.out.print("Number is Positive:\t");
if(check==1) System.out.println("true");
else if(check==0) System.out.println("is Zero");
else System.out.println("false");
System.out.println("Number is Zero:\t"+num.isZero());
System.out.println("Number is Odd:\t"+num.isOdd());
System.out.println("Number is Even:\t"+num.isEven());
}catch(Exception e){
System.out.println(e.getMessage());
}
}if(args.length==0) System.out.println("Give no through command line");
}
}
----------------------------------------------------------------------------------------------
Q3)Define Student class (roll number, name, percentage). Define a default and
parameterized constructor. Keep a count of object created. Create objects using
parameterized constructor and display the object count after each object is created.
(Use static member and method). Also display the contents of each object. Modify
program to create “n” objects of the Student class. Accept details for each object.
Define static method “sortStudent” which sorts the array on the basis of percentage.
--->
import java.io.*;
class Student
{
static int cnt;
int rno;
String name;
float percent;
{
rno = ++cnt;
}
Student ()
{
percent = 0;
name = "";
}
Student (float pr, String nm)
{
percent = pr;
name = nm;
}
void setData () throws IOException
{
BufferedReader br =
new BufferedReader (new InputStreamReader (System.in));
System.out.println ("Enter Name:");
this.name = br.readLine ();
System.out.println ("Enter Percentage:");
this.percent = Float.parseFloat (br.readLine ());
}
public static void sort (Student a[])
{
Student temp = new Student ();
for (int i = 0; i < a.length; i++)
{
for (int j = i + 1; j < a.length; j++)
{
if (a[i].percent < a[j].percent)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
public String toString ()
{
return "RollNumber : " + rno + "\nName :" + name + "\nPercentage :" +
percent;
}
}
class Studentobjtest1
{
public static void main (String[]args) throws IOException
{
int i = 0, j = 0, n;
BufferedReader br =
new BufferedReader (new InputStreamReader (System.in));
System.out.println ("Enter total number of student");
n = Integer.parseInt (br.readLine ());
Student[] objstud = new Student[n];
for (i = 0; i < n; i++)
{
objstud[i] = new Student ();
objstud[i].setData ();
}
Student.sort (objstud);
for (i = 0; i < n; i++)
{
System.out.println (objstud[i]);
}
}
}
-------------------------------------------------------------------------------------------
Q4)Write a program to create a super class Vehicle having members Company and
price. Derive two different classes LightMotorVehicle(mileage) and
HeavyMotorVehicle (capacity_in_tons). Accept the information for “n” vehicles and
display the information in appropriate from. While taking data, ask user about the
type of vehicle first.
-->
// as 3 set a3
import java.util.*;
import java.io.*;
class Vehicle
{
private String company;
private double price;
Vehicle()
{
company="";
price=0;
}
Vehicle(String company,double price)
{
this.company=company;
this.price=price;
}
public void accept() throws IOException
{
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
System.out.println ("Enter name of the company");
company = br.readLine ();
System.out.println ("Enter price in lakhs");
price = Double.parseDouble(br.readLine ());
}
public void display()
{
System.out.println("Company name= "+company+"\t price(in lakhs)= "+price);
}
}
class LightMotorVehicle extends Vehicle
{
private float milage;
LightMotorVehicle()
{
milage=0;
}
LightMotorVehicle(float mil)
{
milage=mil;
}
public void accept() throws IOException
{
super.accept();
Scanner sc=new Scanner(System.in);
System.out.println("\tEnter milage: ");
milage=sc.nextFloat();
}
public void display()
{ super.display();
System.out.println("\tMilage is: "+milage);
}
}
class HeavyMotorVehicle extends Vehicle
{
private double capacity;
HeavyMotorVehicle()
{
capacity=0;
}
HeavyMotorVehicle(double capac)
{
capacity=capac;
}
public void accept() throws IOException
{
super.accept();
Scanner sc=new Scanner(System.in);
System.out.println("Enter capacity in tons:");
capacity=sc.nextDouble();
}
public void display()
{
super.display();
System.out.println("Capacity :"+capacity);
}
}
public class TestVehicle
{
public static void main(String args[]) throws IOException
{
int i,n,ch;
Scanner sc=new Scanner(System.in);
System.out.println("Enter number of vehicals:");
n=sc.nextInt();
Vehicle v[]=new Vehicle[n];
for(i=0;i<n;i++)
{
System.out.println("1 : Light Motor Vehical");
System.out.println("2 : Heavy Motor Vehical");
System.out.println("Enter Choice/type of the vehicle");
ch=sc.nextInt();
switch(ch)
{
case 1:
{
v[i]=new LightMotorVehicle();
v[i].accept();
v[i].display();
}
break;
case 2:
{
v[i]=new HeavyMotorVehicle();
v[i].accept();
v[i].display();
}
break;
default:
{
i--;
System.out.println("Invalid choice");
}
}
}
}
}
-------------------------------------------------------------------------------------------------
Q5)Define a class Employee having members – id, name, department, salary. Define
default and parameterized constructors. Create a subclass called Manager with
private member bonus. Define methods accept and display in both the classes.
Create “n” objects of the Manager class and display the details of the manager
having the maximum total salary (salary + bonus).
-->
import java.io.*;
class Employee1
{
private int id;
private String name;
private String depa;
private float sal;
Employee1(){}
Employee1(int id,String name,String depa,float sal)
{
this.id=id;
this.name=name;
this.depa=depa;
this.sal=sal;
}
public float getsal()
{
return sal;
}
public void accept() throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter id");
id=Integer.parseInt(br.readLine());
System.out.println("Enter Name");
name=(br.readLine());
System.out.println("Enter Department name");
depa=(br.readLine());
System.out.println("Enter sal");
sal=Integer.parseInt(br.readLine());
}
public void display()
{
System.out.println("Id is:"+id);
System.out.println("Name of employee is:"+name);
System.out.println("Name of Department is:"+depa);
System.out.println("Sal is:"+sal);
}
}
class Manager extends Employee1
{
private float bonus;
Manager()
{
super();
bonus=0;
}
Manager(int id,String name,String depa,float sal,float bonus)
{
super(id,name,depa,sal);
this.bonus=bonus;
}
public void accept() throws IOException
{
super.accept();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Bonus");
bonus=Float.parseFloat(br.readLine());
}
public void display()
{
super.display();
System.out.println("Bonus is"+bonus);
}
static void maxsal(Manager m[])
{
float total=0,max=0;
for(int i=0;i<m.length;i++)
{
total=m[i].getsal()+m[i].bonus;
if(total>max)
max=total;
}
System.out.println("Maximum Sal is:"+max);
System.out.println("Id is:"+id);
System.out.println("Name of employee is:"+name);
System.out.println("Name of Department is:"+depa);
System.out.println("Sal is:"+sal);
System.out.println("Bonus is"+bonus);
}
}
class Employee
{
public static void main(String []a) throws IOException
{
int n;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("\nHow many Employee:");
n=Integer.parseInt(br.readLine());
//float max=0;
Manager[] m=new Manager[n];
for(int i=0;i<n;i++)
{ m[i]=new Manager();
m[i].accept();
m[i].display();
}
Manager.maxsal(m);
}
}
------------------------------------------------------------------------------------------------------------
INTERFACE - it contains set of methods and variables.
e.g -
Interface A
{
public void add (int a,int b)
{
}
}
Interface B
{
public void display()
public void display()
{
}
}
class C implements A,B
}
}
class C implements A,B
{
public static void main(String args[])
public static void main(String args[])
{
}
}
}
}
EXAMPLES
Q)Create an interface “CreditCardInterface” with methods: viewCreditAmount(),
useCard(), payCard(), and increaseLimit(). Create a class “SolverCardCustomer”
(name, cardnumber(16digit), creditamount-initialized to 0, creditLimit-set to 50,000)
whch implements above interface. Inherit class GoldCardCustomer from
SilverCardCustomer having same methods but creditLimit of 1,00,000. Create an
object of each class and perform operations. Display appropriate messages for
success or failure of transction. (Use method overloading) [30]
a) useCard() method increase the creditAmount by a specific amount upto
creaditLimit.
b) payCreadit() reduces the creditAmount by a specific amount.
c) increaseLimit() increases the creaditLimit for GoldCardCustomers (only 3 times,
not more than 5000 rupees each time.)
----->
import java.io.*;
interface CreditCardInterface
{
abstract void viewCreditAmount();
abstract void useCard(int n);
abstract void payCredit(int n);
abstract void increaseLimit(int m);
}
class SilverCC implements CreditCardInterface
{
String name;
String no;
int Cno;
int creditAmt=0;
int cLimit;
SilverCC(int l)
{
cLimit = l;
}
void set(String n,String name)
{
if(n.length()==16)
{
this.no=n;
this.name=name;
}
else
{
System.out.println("Wrong no ");
System.exit(0);
}
}
void show()
{
System.out.println("Name is "+this.name);
System.out.println("No is "+this.no);
viewCreditAmount();
}
public void viewCreditAmount()
{
System.out.println("Credit Amount is " + this.creditAmt);
}
public void useCard(int add)
{
creditAmt+=add;
if(creditAmt>cLimit)
{
System.out.println("Cant be added... more than Credit limit");
creditAmt-=add;
}
else
viewCreditAmount();
}
public void payCredit(int add)
{
if(add>creditAmt)
System.out.println("no enough credit");
else
{
creditAmt-=add;
if(creditAmt<0)
creditAmt=0;
viewCreditAmount();
}
}
public void increaseLimit( int m)
{
}
}
class GoldCC extends SilverCC
{
static int n;
GoldCC(int l)
{
super(l);
}
void set(String n,String name1)
{
super.set(n, name1);
}
void show()
{
super.show();
}
public void viewCreditAmount()
{
super.viewCreditAmount();
}
public void useCard(int add)
{
super.useCard(add);
}
public void payCredit(int add)
{
super.payCredit(add);
}
public void increaseLimit(int amt)
{
while(n<3)
{
if(amt<5000)
{
this.cLimit=this.cLimit+amt;
System.out.println("new credit limit is :"+cLimit);
}
else
System.out.println("Cant be more than 5000");
n++;
}
}
public static void main(String a[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter no of objects :");
int r= Integer.parseInt(br.readLine());
SilverCC g[]=new SilverCC[r];
for(int i=0;i<r;i++)
{
System.out.println("Enter type of card (S or G)");
String ch=br.readLine();
if(ch.equals("S"))
{
g[i] =new SilverCC(50000);
System.out.println("Enter name :");
String name= br.readLine();
System.out.println("Enter no :");
String n= br.readLine();
g[i].set(n,name);
g[i].viewCreditAmount();
System.out.println("Enter amount to add");
int n1 = Integer.parseInt(br.readLine());
g[i].useCard(n1);
System.out.println("Enter amount to remove");
int n2 = Integer.parseInt(br.readLine());
g[i].payCredit(n2);
g[i].show();
}
else
{
if(ch.equals("G"))
{
g[i] =new GoldCC(100000);
System.out.println("Enter name :");
String name= br.readLine();
System.out.println("Enter no :");
String n=br.readLine();
g[i].set(n,name);
g[i].viewCreditAmount();
System.out.println("Enter amount to add");
int n3 = Integer.parseInt(br.readLine());
g[i].useCard(n3);
System.out.println("Enter amount to remove");
int n4 = Integer.parseInt(br.readLine());
g[i].payCredit(n4);
System.out.println("Enter amount to increase credit Limit :");
int n5 = Integer.parseInt(br.readLine());
g[i].increaseLimit(n5);
g[i].show();
}
}
}
}
}
0 Comments