0% found this document useful (0 votes)
44 views10 pages

Java Lab: Student Class Implementations

The document contains the code for various Java programming assignments. It includes code to create a Student class with methods to initialize student data and print it, code for a Dimension class to calculate volume and area, code for a Book class to store book details, and code for a BankAccount class to perform deposit and withdrawal transactions. Test code is provided to demonstrate the usage of these classes.

Uploaded by

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

Java Lab: Student Class Implementations

The document contains the code for various Java programming assignments. It includes code to create a Student class with methods to initialize student data and print it, code for a Dimension class to calculate volume and area, code for a Book class to store book details, and code for a BankAccount class to perform deposit and withdrawal transactions. Test code is provided to demonstrate the usage of these classes.

Uploaded by

Wake Up
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Program Name :BCS

Course Code: CSC 2513

Course Name: Programming Fundamentals

Lab Sheet: 4

Date of Submission: 5th May 2021

Submitted By: Submitted To:

Student Name: Udit Kumar Mahato Faculty Name: Mr. Prakash Chandra

IUKL ID: 042002900006 Department: PO office

Semester: Second Semester

Intake: Sept 2020


[Link] a class named Student. This class should contain some member variable(such as: name, age,
rollno...). Define two method as mentioned below

[Link](): This method will initialize object by taking all required variable as argument and
assign it to the member variables.
[Link](): this method will print all the data of student in formatted output format.

Ans:-

class Student{
String name;
int age;
int rollno;
void initializeStudent(String n,int a,int r){
name=n;
age=a;
rollno=r;
}
void printData(){
[Link]("Name : "+name);
[Link]("Age : "+age);
[Link]("Roll no : "+rollno);
}
}
public class StudentClass {
public static void main(String[] args) {
Student stu=new Student();
[Link]("Princu",9,1);
[Link]();
}
}

Output:-

[Link] a class Student as described below:


Instance variables:

name, age, marks in three subjects (m1, m2, m3), maximum and average.

Methods:
i. A parameterized constructor to initialize the instance variables.

ii. To accept the details of a student.

iii. To compute the average and minimum out of the three marks.

iv. To display the name, age, marks in the three subjects, minimum and average.

v. Write a main method to create an object of the class and call the above methods.

Ans:-

class Students{
String name;
double age,marks1,marks2,marks3,minimum,average;
Students(String n,double a,double m1,double m2,double m3){
name=n;
age=a;
marks1=m1;
marks2=m2;
marks3=m3;
}
void getAvg(){
average=(marks1+marks2+marks3)/3;
[Link]("Average of the marks : "+average);
}
void getMin(){
minimum = [Link]([Link](marks1,marks2),marks3);
[Link]("Minimum marks : "+minimum);
}
void display(){
[Link]("Name : "+name);
[Link]("Age : "+age);
[Link]("Marks 1 : "+marks1);
[Link]("Marks 2 : "+marks2);
[Link]("Marks 3: "+marks3);
}
}
public class StudMark {
public static void main(String[] args) {
Students s=new Students("sumit",15,57,98,52);
[Link]();
[Link]();
[Link]();
}
}

Output:
[Link] a class Circle with a parameterized constructor. If no parameters are passed then its default
constructor should be invoke parameterized constructor with default values. A circle is defined using
radius and circumference.
Ans:-

import [Link].*;
class Circle{
double radius;
double circumference;
Circle(){
radius=7.98;
[Link]("Default Radius Value :
"+radius+"\n"+"Circumference taking default radius value :
"+2*[Link]*radius);
}
Circle(double r){
radius=r;
[Link]("Given Radius Value : "+radius+"\n"+"Circumference
taking given radius value : "+2*[Link]*radius);
}
}
public class circleCircum {
public static void main(String[] args) {
Circle s1=new Circle();
Circle s2=new Circle(198.7);
}
}

Output:-

4 .Write a program to implement a Book class that stores the details of a book namely, bookcode,
name of the book, name of the author(s) and price. The class has methods to display any of the details
individually.
Ans:-
class Book{
int bookcode;
String bookname;
String bookauthor;
double price;
void bookDetails(int bc,String bn,String ba,double p){
bookcode=bc;
bookname=bn;
bookauthor=ba;
price=p;
}
void getBookCode(){
[Link]("BOOK CODE : "+bookcode);
}
void getBookName() {
[Link]("BOOK NAME : "+bookname);
}
void getBookAuthor(){
[Link]("BOOK AUTHOR : "+bookauthor);
}
void getBookPrice(){
[Link]("BOOK PRICE : "+price);
}
}
public class bookClass {
public static void main(String[] args) {
Book d1=new Book();
[Link](73547,"The power of subconscious mind","Dr. Joseph
Murphy",4500);
[Link]();
[Link]();
[Link]();
[Link]();
}
}

Output:

[Link] a class called Dimension based on the following information:


Constructors

Dimension(double length, double width, double height)


Dimension(double side)

Methods

double volume() // length*width*height

double area() // 2*(length*width+width*height+height*length)

6 .Make all the instance variables private so that they can be accessed only by the methods defined
within the class. Make the methods public. Test your program.

7 .Modify the implementation of area() given in the previous question using private
methods, faceArea(), topArea() and sideArea(). [Often private methods are helping methods that
public methods use, but are not to be used outside the class.] Test your program.

[Link] a new constructor to the Dimension class created in question 1 as


Dimension(Dimension dim)

This constructor creates a new Dimension object with identical dimensions as the old

Dimension object. The old object is not changed.

Ans:-

//No .6,7 and 8 are coded in single program below


class Dimension{
private double length;
private double width;
private double height;
private double side;
Dimension(double l,double w,double h){
length=l;
width =w;
height=h;
}
Dimension(double s){
side=s;
}
Dimension(Dimension dim){
length=4;
width=25;
height=50;
[Link]("Volume while values are default :"+ length *
width * height);
[Link]("Area while values are default :"+
2*(length*width+width*height+height*length);
}
public double volume(){
double volume = length * width * height;
return volume;
}
public double area(){
double area=2*(length*width+width*height+height*length);
return area;
}
private double toparea(){
return(length*height);
}
private double facearea(){
return(length*width);
}
private double sidearea(){
return(width*height);
}

}
public class Dimen {
public static void main(String[] args) {
Dimension d1= new Dimension(25,45,67);
Dimension d2 = new Dimension();
[Link]("Volume : "+[Link]()+"\n"+"Area : "+ [Link]());
[Link]("Volume : "+[Link]()+"\n"+"Area : "+
[Link]());
[Link]("Volume : "+[Link]()+"\n"+"Area : "+
[Link]());
[Link]("Volume : "+[Link]()+"\n"+"Area : "+
[Link]());
[Link]([Link]());
}
}

Output:-

9. Design a class to represent a bank account. Include the following members:


Fields/Data members

Name of the depositor


Account number

Type of account

Balance amount in the account

Methods

Constructor(s)

To assign initial values

To deposit an amount

To withdraw an amount after checking balance

To display the name and balance.

Test the bank account class by performing all actions defined in BankAccount class.

Ans:

import [Link];
class Data{
String name;
double accountnum;
String type;
double amount;
double depositemoney;
double withdraw;

void Data(String name,double accountnum, String type, double amount){


[Link]= name;
[Link] =accountnum;
[Link] = type;
[Link]= amount;
}
void deposite(double depositemoney){
[Link] = depositemoney;
double newmoney = [Link]+[Link];
[Link](newmoney);
[Link] =newmoney;
[Link]("your new balance is"+ ""+ newmoney);
}

void withdraw(){

double newmoneys =[Link]-withdraw;


[Link] = newmoneys;
[Link]("your new amount "+newmoneys);

}
void details(){
[Link]("account holder name is:" + [Link]);
[Link]("");
[Link]("your account type:"+ [Link]);
[Link]("");
[Link]("your current money:"+[Link]);
[Link]("");

public class bankAcc {


public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

Data obj = new Data();

[Link] ="Sagar";
[Link]=123;
[Link] ="saving";
[Link] = 5000;

[Link]("enter your pin number");


int pin =[Link]();

if (pin==123){
char choice;
do{
while(true)
{
[Link]("Automated Teller Machine");
[Link]("Choose 1 for Withdraw");
[Link]("Choose 2 for Deposit");
[Link]("Choose 3 for Check Balance");
[Link]("choose 4 details");
[Link]("Choose 5 for EXIT");
[Link]("Choose the operation you want to
perform:");
int n = [Link]();
switch(n)
{

case 1:
if ([Link]>=[Link]){
[Link]("enter the anount you want
to withdraw");
[Link] = [Link]();
[Link]();

}
else{
[Link]("low balance");

}
break;
case 2:
[Link]("enter the money you want to
deposite");
[Link] = [Link]();
[Link]([Link]);
break;

case 3:
[Link]("your balane is"+[Link]);
[Link]("");

break;

case 4:
[Link]("your details is");
[Link]();
break;

case 5:
[Link](0);

}
[Link]("do you want to continue(y/N)");
choice =[Link]().charAt(0);
}

}while(choice=='y'||choice =='Y');

else{
[Link]("sorry");
}
}
}
output:

Common questions

Powered by AI

Using customizable classes like Student and Circle in teaching programming fundamentals offers educational benefits by illustrating key object-oriented concepts such as encapsulation, inheritance, and polymorphism in a practical and relatable manner. These classes provide clear examples of how data structures are used and manipulated, enhancing understanding of abstraction and data encapsulation. However, potential drawbacks include overwhelming beginners with complex syntax or design patterns that may detract from fundamental understanding if not paced appropriately. Additionally, without proper guidance, students might focus on syntax mechanics rather than underlying object-oriented principles, which could hinder their ability to apply these concepts across various scenarios .

Using a class constructor to initialize objects offers the advantage of ensuring that objects are fully constructed with all necessary fields at the time of creation, which helps maintain object integrity and prevents incomplete or inconsistent states. Constructors provide a clear and concise way to enforce that required properties are set and can aid in improving code readability and maintainability. In contrast, using separate methods for initialization can lead to more flexible object creation, allowing properties to be set and modified post-instantiation. However, this approach may increase the risk of objects being used in a partially initialized or inconsistent state if not managed carefully .

Implementing methods to calculate average and minimum marks, such as getAvg() and getMin(), enhances the Students class's functionality by providing important metrics that are often needed in educational contexts for evaluating student performance. The average represents an overall assessment of a student's capabilities across subjects, while the minimum mark highlights areas that may require improvement. Integrating these calculations directly within the class streamlines the assessment process, enabling efficient data processing and reporting without the need for external computation .

The implementation of private methods like faceArea(), topArea(), and sideArea() ensures that these methods are not accessible outside the class, thus preserving the integrity and security of the internal operations. These methods act as helper functions that simplify the implementation of complex public methods by breaking down calculations into manageable parts. This modularization makes the code easier to maintain, debug, and extend without affecting external components or exposing sensitive logic. By using private methods, the class design adheres to encapsulation principles, protecting internal data from unwanted modification .

Parameterized methods like initializeStudent() allow for more flexibility and control when initializing objects because they can set specific values at the time of initialization based on provided arguments. This approach avoids the rigidity of default constructors, which would typically initialize fields to default values or require additional method calls to set proper values. This facilitates better object configuration and data integrity, ensuring that all necessary properties are correctly assigned before an object is used .

Using a parameterized constructor in the Circle class for calculating properties like radius and circumference enables dynamic object configuration with user-defined values, enhancing flexibility. By accepting a radius value as a parameter, the class allows for precise and context-specific circle creation, facilitating tailored calculations of circumference based on varying radius lengths. This design supports efficient use of object-oriented features to encapsulate the logic for property calculations within the class, reducing redundancy and potential errors caused by external calculations and promoting reusability of the class in different contexts .

Using the main method to test a Book class's functionality provides a straightforward environment to validate the behavior of the class methods, such as bookDetails() and its different retrieval methods. This approach facilitates immediate feedback on method implementations, allowing developers to detect and correct errors during early stages of development. Additionally, it serves as an informal way to perform initial unit testing, ensuring methods perform as expected with sample input without the overhead of setting up a formal testing suite. This testing provides confidence in the correctness of class operations before deploying or integrating them with larger applications .

The ATM system in the bank account management program handles user interactions by providing a menu-driven console application, prompting the user to select operations like withdrawal, deposit, and balance inquiry. It ensures secure transactions by requiring a PIN for access, which verifies the identity of the user and allows only authenticated users to perform sensitive operations like withdrawals. The integration of conditionals and loops ensures that the system checks account balances before allowing withdrawals, thus preventing overdrafts and maintaining account integrity .

Encapsulation in bank account management systems involves hiding critical data and operations, such as balances and transaction processes, behind well-defined interfaces. By making instance variables private, access is restricted to only those methods that are part of the public interface, like deposit and withdraw. This minimizes the risk of unauthorized data manipulation and increases the robustness of the code by forcing external classes to interact with the data only through controlled methods. Consequently, encapsulation enhances data integrity and system reliability .

The duplication constructor in the Dimension class, Dimension(Dimension dim), illustrates the 'copy constructor' design pattern by allowing the creation of a new object that is a copy of an existing object. This pattern is useful when you need to replicate the state of an object for purposes such as maintaining history, implementing undo functionality, or simply having multiple instances with the same state. By copying only the values of the original object's fields without affecting them, the copy constructor supports object independence and encapsulation, as any changes to the new object's fields do not impact the original object .

You might also like