0% found this document useful (0 votes)
3 views11 pages

Java Object-Oriented Programming Examples

The document contains multiple Java programs demonstrating object-oriented programming concepts such as classes, objects, method overloading, constructor overloading, and passing objects as arguments. Each program includes a class definition, methods for input and output, and examples of how to create and manipulate objects. The programs cover scenarios like managing student records, library books, distance calculations, area calculations, and box dimensions.

Uploaded by

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

Java Object-Oriented Programming Examples

The document contains multiple Java programs demonstrating object-oriented programming concepts such as classes, objects, method overloading, constructor overloading, and passing objects as arguments. Each program includes a class definition, methods for input and output, and examples of how to create and manipulate objects. The programs cover scenarios like managing student records, library books, distance calculations, area calculations, and box dimensions.

Uploaded by

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

/*Program to show classes and objects using Student Class

Reg no: 231810*/


import [Link].*;
class student{
String name;
int regno;

void get(){
Scanner sc=new Scanner([Link]);
name=[Link]();
regno=[Link]();
}
void put(){
[Link]("Student name="+name);
[Link]("Register number"+regno);
}
}
class studentobj{
public static void main (String[] args) {
student S[]=new student[5];
for(int i=0;i<5;i++){
S[i]=new student();
S[i].get();
} for(int i=0;i<5;i++){
S[i].put();
}
}
}
Output:
Rakshith 01
Deeksha 02
Keerthi 03
Kiran 04
Nithesh 05
Student name= Rakshith
Register number= 1
Student name= Deeksha
Register number= 2
Student name= Keerthi
Register number= 3
Student name= Kiran
Register number= 4
Student name= Nithesh
Register number= 5

Process completed.

/*
Program to show arrary of objects using Library class
Register no.231810
*/
import [Link].*;
class Library{
int Accno, noofcopies;
String Title;
double Price;

void get(){
Scanner sc= new Scanner([Link]);
[Link]("Enter Account number");
Accno= [Link]();
[Link]("Enter the number of copies");
noofcopies= [Link]();
[Link]("Enter the Title of book");
Title= [Link]();
[Link]("Enter the price of book");
Price= [Link]();
}
void put(){
[Link]("Accession Number: " +Accno);
[Link]("Number of copies: " +noofcopies);
[Link]("Title: " +Title);
[Link]("Price: " +Price);
}
}
class Librayclass{
public static void main (String[] args) {
Library L[]= new Library[3]; //create array and objects
for(int i=0;i<3;i++){
L[i]= new Library(); //instantiate an object
L[i].get();
}
for(int i=0; i<3;i++){
L[i].put();
}
}
}

Output

Enter Account number


123
Enter the number of copies
3
Enter the Title of book
Untold Story Of Me
Enter the price of book
1320
Enter Account number
231
Enter the number of copies
4
Enter the Title of book
TRUST
Enter the price of book
1500
Enter Account number
145
Enter the number of copies
5
Enter the Title of book
Silence
Enter the price of book
500
Accession Number: 123
Number of copies: 3
Title: Untold Story Of Me
Price: 1320.0
Accession Number: 145
Number of copies: 4
Title: TRUST
Price: 1500.0
Accession Number: 145
Number of copies: 5
Title: Silence
Price: 500.0

Process completed.
/*
Program to illustrate passing objects as arguments to methods and returning
objects using Distance class for function calls D3=[Link](D2) and [Link](D2)
*/

import [Link].*;
class Distance{
int feet,inches;

void get(){
Scanner sc=new Scanner([Link]);
[Link]("Enter the feet and inches");
feet=[Link]();
inches=[Link]();
}
void put(){
[Link]("feet=" +feet);
[Link]("inches= " +inches);
}
void Sum(Distance D2){
int a=[Link]+[Link];
int b=[Link]+[Link];
[Link]("total feet= "+a+ "total inches= "+b);

}
Distance Max(Distance D2){
int totD1=[Link]*12+[Link];
int totD2=[Link]*12+[Link];
if(totD1>totD2)
return this;
else
return D2;
}
}
class Distanceobj{
public static void main (String[] args) {
Distance D1=new Distance();
Distance D2=new Distance();
Distance D3=new Distance();
[Link]();
[Link]();
[Link]();
[Link]();
[Link](D2);
[Link]("Maximum Distance is " );
D3=[Link](D2);
[Link]();
}
}

Enter the feet and inches


2
1
Enter the feet and inches
2
11
feet=2
inches= 1
feet=2
inches= 11
total feet= 4total inches= 12
Maximum Distance is
feet=2
inches= 11

Process completed.

/*
Program to illustrate method overloading
Register no.231810
*/
class Area{

void areacal(int s){ // area of square


[Link]("Area of square is" +(s*s));

}
void areacal(int l,int w){ //area of rectangle
[Link]("Area of Rectangle is" +(l*w));

}
void areacal(double b, double h){ //area of triangle
[Link]("Area of triangle is" +(0.5*b*h));
}
}
class Method{
public static void main (String[] args) {
Area A1=new Area();
[Link](10);
[Link](15,30);
[Link](5.5,8.5);

}
}

Area of square is100


Area of Rectangle is450
Area of triangle is23.375

Process completed.

/*
Program to illustrate constructor overloading
Register no.231810
*/
class Box{
int l,b,h;
String shape;

Box(){
l=10;
b=5;
h=9;
shape= "rectangle";
}
Box(int p,int q,int r, String s){ //parameterised
l=p;
b=q;
h=r;
shape=s;
}
Box(int x){ // parameterised constructor
l=b=h=x;
}
Box(Box B){ //copy constructor
this.l= B.l;
this.b= B.b;
this.h= B.h;
}
void put(){
[Link](" Length= " + l);
[Link](" Breadth= " +b);
[Link](" Height= " +h);
[Link](" Shape= " +shape);
}
}
class Boxobj{
public static void main (String[] args) {
Box B1= new Box();
[Link]();
Box B2= new Box(10,20,30," rectangle");
[Link]();
Box B3= new Box(10);
[Link]();
Box B4= new Box(B2);
[Link]();
}
}
Output

Length= 10
Breadth= 5
Height= 9
Shape= rectangle
Length= 10
Breadth= 20
Height= 30
Shape= rectangle
Length= 10
Breadth= 10
Height= 10
Shape= null
Length= 10
Breadth= 20
Height= 30
Shape= null

Process completed.

Common questions

Powered by AI

Not closing the Scanner object in the given Java programs could lead to resource leaks, particularly when dealing with system resources like input streams. Without closing the Scanner, the underlying input stream remains open, which could eventually exhaust file descriptors for applications with heavy input operations. While the automatic garbage collector in Java helps manage memory and resource cleanup, explicit closure ensures immediate resource deallocation, improving program efficiency and robustness .

Using only integer types for dimensions and measurements in the code examples simplifies calculations and reduces computational overhead, as integer operations are generally faster and require less memory than floating-point operations. However, this restricts the precision of the measurements, potentially leading to inaccuracies in applications requiring fine granularity, such as scientific computations or graphics where decimal precision is necessary. The lack of fractional measurement capability could lead to rounding errors and less realistic representations of real-world measurements, highlighting a trade-off between efficiency and precision .

The use of an array of objects in the 'Library' class enhances the program's structure by enabling efficient management and processing of multiple 'Library' instances. This structure provides scalability, allowing easy addition of more books without significant code changes. The array facilitates operations like batch input and output through iterative loops, streamlining code by managing each 'Library' instance within a concise, uniform framework. This improves both the readability and maintainability of the code, showcasing the array's utility in organizing and manipulating collections of related objects in Java .

Copy constructors in the 'Box' class provide the benefit of creating a new instance with the same state as an existing object, which can be useful for preserving object states without reference dependencies. This ensures that changes to the copy do not affect the original object. However, potential drawbacks include additional overhead in terms of memory and performance for duplicating object data, which can be significant for complex objects with large state data. Additionally, copy constructors must be carefully implemented to avoid shallow copying, which can inadvertently couple the original and copied objects through reference fields. Therefore, while providing controlled duplication, they require thoughtful implementation to avoid unintended side effects .

The 'Distance' class demonstrates encapsulation by encapsulating the fields 'feet' and 'inches' and providing controlled access via the 'get', 'put', and calculation methods such as 'Sum' and 'Max'. This encapsulates distance operations within the class, shielding implementation details from external code and allowing modifications without impacting dependent code. The abstraction is achieved through method definitions that hide the complexities of operations like summation and comparison, providing a simple interface for these functionalities. This design exemplifies the core object-oriented principles of restricting direct access to data and operations to abstract complex processes .

Constructor overloading in the 'Box' class is applied by defining multiple constructors with different parameter lists, allowing object creation with varying initial states. The class includes a default constructor, a parameterized constructor for specifying dimensions and shape, a parameterized constructor with a single integer (assigning it to all dimensions as a cube), and a copy constructor that duplicates another 'Box' object. This approach improves flexibility by enabling the creation of 'Box' instances with different initial setups, demonstrating how overloading enhances the extensibility and maintainability of Java applications .

Method overloading in the 'Area' class illustrates polymorphism by allowing multiple methods with the same name, 'areacal', to coexist in the same class. Each overloaded method is differentiated by its parameter list, such as parameters for calculating areas of a square, rectangle, or triangle. This form of polymorphism lets the same method name be used to perform different tasks depending on the context or input type, exemplifying compile-time polymorphism where the method invocation is determined at compile time .

The 'Student' and 'Distance' classes represent distinct applications of class and object structures, showing both similarities and differences in their design and functionality. Both classes encapsulate properties (name and regno for 'Student', feet and inches for 'Distance') and provide methods for input/output operations. However, 'Distance' extends functionality with methods to perform operations and comparisons, illustrating an application beyond simple data storage by manipulating and returning data. The 'Student' class is primarily used for encapsulation of data and basic input/output operations, whereas 'Distance' demonstrates more complex functionalities like arithmetic operations and comparison of objects, showcasing a higher level of abstraction and application in problem-solving. These design choices reflect varying objectives: 'Student' focuses on managing entity data, while 'Distance' illustrates functional applications of object-oriented principles .

The 'studentobj' class serves as the driver class in the provided Java program, which is responsible for creating and manipulating objects of the 'student' class. It initializes an array of 'student' objects, then iterates through this array to invoke the 'get' method to input student data (name and register number) and subsequently calls the 'put' method to output this data. The separation of input/output functionality between these two classes exemplifies encapsulation, where data operations are managed within the 'student' class, and control flow is managed within 'studentobj' .

The method 'Max(Distance D2)' in the 'Distance' class demonstrates decision-making by using a conditional statement to compare total distances, calculated as the sum of feet and inches converted into a single unit. By computing the total inches for 'this' object and 'D2', it decides which object represents a greater distance based on these calculated totals. This decision-making capability is fundamental in Java programming for implementing logic that varies behavior depending on specific conditions. It illustrates basic algorithmic thinking, allowing the program to selectively return one of two possible 'Distance' objects based on the comparison .

You might also like