0% found this document useful (0 votes)
9 views5 pages

Java OOP Concepts: Classes & Methods

Uploaded by

sampath oruganti
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)
9 views5 pages

Java OOP Concepts: Classes & Methods

Uploaded by

sampath oruganti
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

2-BTECH-CSE:: I SEM

OOPS THROUGH JAVA PROGRAMMING LAB


EXPERIMENT: 3
3(A)- AIM: Write a JAVA program to implement class mechanism. –
Create a class, methods and invoke them inside main method.
Java Class and Objects
Java is an object-oriented programming language. The core concept of the object-oriented
approach is to break complex problems into smaller objects.
An object is any entity that has a state and behavior. For example, a bicycle is an object. It
has
 States: idle, first gear, etc
 Behaviors: braking, accelerating, etc.

Java Class
A class is a blueprint for the object. Before we create an object, we first need to define the
class.
Create a class in Java
We can create a class in Java using the class keyword. For example,

class ClassName {
// fields
// methods
}

Java Objects
An object is called an instance of a class. For example, suppose Bicycle is a class
then MountainBicycle, SportsBicycle, TouringBicycle, etc can be considered as objects of
the class.
Creating an Object in Java
Here is how we can create an object of a class.

className object = new className();

// for Bicycle class


Bicycle sportsBicycle = new Bicycle();

Bicycle touringBicycle = new Bicycle();


PROGRAM:

class Box
{
double width;
double height;
double depth;
double volume()
{
return (width * height * depth);
}
}
class Main
{
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
// assign values to mybox1's instance variables
[Link] = 10;
[Link] = 20;
[Link] = 15;
/* assign different values to mybox2's instance variables */
[Link] = 3;
[Link] = 6;
[Link] = 9;
// display volume
double vol1= [Link]();
[Link]("Volume of Box1 :: "+vol1);
double vol2=[Link]();
[Link]("Volume of Box2 :: "+vol2);
} // main() ends
} // class ends

OUTPUT:

Volume of Box1 :: 3000.0


Volume of Box2 :: 162.0
3(B) AIM: Write a JAVA program implement method overloading.
import [Link].*;
class Overloading
{
int addition(int a,int b)
{
int res;
res=a+b;
return res;
}
int addition(int a,int b,int c)
{
int res;
res=a+b+c;
return res;
}
int addition(int c)
{
int res;
res=c+1;
return res;
}
}
public class OverloadingDemo
{
public static void main(String[] args)
{
Overloading obj=new Overloading();
[Link]("Method Overloading Demo");
Scanner scr=new Scanner([Link]);
[Link]("Enter Three Integer values for a,b,c:");
int a=[Link]();
int b=[Link]();
int c=[Link]();
[Link]("Addition Method with two parameters:"+[Link](a, b));
[Link]("Addition Method with Three Parameters:"+[Link](a, b, c));
[Link]("Addition Method with one parameter:"+a+"+1:"+[Link](a));
}
}

OUTPUT:
3 c) Write a JAVA program to implement constructor.

PROGRAM:
import [Link];
class Sports_person
{
int height=164;
int weight=62;
// constructor method
public Sports_person()
{
Scanner in=new Scanner([Link]);
[Link]("Enter Height?");
height=[Link]();
[Link]("Enter Weight?");
weight=[Link]();
[Link]("Height of the sports person is:"+height+"CM");
[Link]("Weight of the sports person is:"+weight+"KG");
}
}

public class Olimpics {


public static void main(String[] args) {
Sports_person s=new Sports_person();
}
}

OUTPUT:
3 d) Write a JAVA program to implement constructor overloading
PROGRAM:
class Student
{
int sno;
String sname;
float fee;

public Student()
{
}
public Student(int sn,String snm,float f)
{
sno=sn;
sname=snm;
fee=f;
}

public void display()


{
[Link]("Sno : "+sno);
[Link]("Sname : "+sname);
[Link]("Fees : "+fee);
}
}

public class ConsOvl


{
public static void main(String[] args)
{
// overloading zero arg constructor
Student s=new Student();
[Link]();
//overloading parameterized constructor
Student s1=new Student(100, "Raj",500);
[Link]();
//anonymous object
new Student().display();
}
}

OUTPUT:
Sno : 0
Sname : null
Fees : 0.0
Sno : 100
Sname : Raj
Fees : 500.0

Sno : 0
Sname : null
Fees : 0.0

Common questions

Powered by AI

Method and constructor overloading in Java provide several advantages, including enhanced code readability by using the same method name for different functionalities based on parameter variations. Overloading facilitates clearer logical grouping of related operations and enhances programming productivity by reducing the risk of error through method differentiation by parameter patterns. Constructors benefit from overloading by allowing varied object initializations, accommodating different data availability without the need for multiple distinct method identifiers. This flexibility is particularly advantageous for complex applications where polymorphic behaviors are required .

Java constructors and methods demonstrate encapsulation by allowing the bundling of data (fields) with the methods that operate on that data, thereby restricting direct access to some of an object's components. For example, in the 'Sports_person' class, constructors are used to initialize the height and weight attributes, guiding how these fields are set. Abstraction is exemplified through the method 'display' in the 'Student' class, which presents a simplified interface to the user to view data without detailing the internal workings like default constructor values. These encapsulate and abstract the functionalities, ensuring that users interact with objects at a higher level of simplicity and security .

Java's object-oriented structure supports code reusability and modularity through inheritance and class interfaces. Inheritance enables new classes to reuse and extend attributes and methods from existing classes, reducing redundancy. The use of abstract classes and interfaces provides high-level frameworks or blueprints that can be fleshed out in subclass implementations, promoting consistent design patterns. Modularity is achieved as each class can be independently developed, tested, replaced, or clumped together organically within diverse applications, thus fostering scalable and manageable code structures .

Constructor overloading allows a class to have multiple constructors with different parameter lists. This flexibility permits object instantiation with varying setups without needing a separate initialization setup. For instance, the 'Student' class uses overloaded constructors to initialize student data either with default values or specific inputs, like student number, name, and fee. This leads to a robust initialization process that caters to different scenarios and reduces potential errors during object creation, as developers can choose appropriate object states at the time of instantiation based on the available data .

Java's class and object implementation can be utilized in system design to decompose complex problems into manageable units through the encapsulation of data and behaviors into classes. By mapping real-world entities into objects, Java allows for a modular approach to system design, where different classes address specific aspects of functionality and interact through defined interfaces or messages. For instance, in designing a transport management system, classes like 'Vehicle', 'Route', and 'Ticket' can encapsulate functional details, thereby maintaining a clean separation of concerns, ensuring higher adaptability to changes, and promoting a clearer architecture .

The 'new' keyword in Java triggers object creation by allocating memory for a new instance, invoking the class's constructor, and returning a reference to the newly allocated object. It essentially manages memory through the heap, where objects reside, and is crucial for initializing and constructing objects. Memory management is implicitly handled by the Java Garbage Collector, which recycles memory when objects are no longer in use. This serves to maximize efficiency and prevent memory leaks, supporting Java's automatic memory management model .

Method overloading in Java is implemented by defining multiple methods with the same name but different parameters within the same class. This allows for versatility in invoking methods based on the number and type of arguments passed. For example, in the class 'Overloading', there are three 'addition' methods, each differing by their parameters: two integers, three integers, and a single integer. Such implementation not only enhances program readability by unifying logic under a single method name but also increases flexibility in performing varied operations with different data inputs. This technique supports polymorphism, a core tenet of object-oriented programming .

Java embodies the principles of polymorphism and inheritance through its class-based structure. Inheritance allows one class to inherit fields and methods from another, promoting code reuse and hierarchical classification. This is seen in how subclasses can override methods of their parent classes to provide specific behaviors. Polymorphism enables objects to be treated as instances of their parent class, allowing for dynamic method invocation at runtime. For instance, a superclass 'Animal' can have subclasses such as 'Dog' and 'Cat', each with specific implementations of a method like 'makeSound', while a single reference of type 'Animal' can point to either, enabling flexible and maintainable code .

Object-oriented programming in Java is fundamentally about creating classes that serve as blueprints for objects. A class defines the data properties (states) and behaviors (methods) of objects. For instance, the class 'Bicycle' reflects the properties like gears, and behaviors like braking. The object, which is an instance of a class, will embody these attributes and methods based on the class design. In a Java program, a class is created using the 'class' keyword, following which objects can be instantiated. For example, an object of Bicycle class could be 'MountainBicycle'. These objects encapsulate states and behaviors specific to their class definition .

Encapsulation in Java conceals the internal state of objects and restricts access to their data by providing access modifiers like private, protected, and public to class fields and methods. This limits external classes from altering internal data arbitrarily, thus securing data and enhancing program robustness. Encapsulation promotes method hiding by allowing methods to be defined and accessed in a controlled manner—only through well-defined interfaces. This paradigm shifts focus from implementation details to usability, thereby preserving elegance and integrity in a program's architecture .

You might also like