Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java Assignment

Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

Theory Portion:

1. Introduce class and object. Explain the major four features of object-oriented
programming?

Ans: Class is a blueprint or template for creating objects. It defines how objects will work in
the class which organizes code and reusable components. For example, consider a car as a
class which defines the attributes such as color, model, break, acceleration and turn methods.

An example to illustrate how class and objects are created and used is given below:

public class Example_1 {

public void display(){

System.out.println("Hello World!");

public static void main(String args[]){

Example_1 myObj = new Example_1();

myObj.display();

Four major features of object-oriented programming are: Encapsulation, Inheritance,


Polymorphism, and Abstraction.

● Encapsulation: Encapsulation allows bundling data and methods which operate on


the data into single units. It helps in data hiding and protecting data integrity.
● Inheritance: Inheritance helps to inherit a new type from an existing one and which
also helps to reuse code and create a hierarchical relationship between classes.
● Polymorphism: Polymorphism means many forms which allows methods to do
different things based on the object it is acting upon.
● Abstraction: Abstraction means hiding the complex implementation details of
methods and only showing the necessary features of an object.

2. Differentiate between structured programming and object-oriented programming


language.
Ans: The difference between structured and object-oriented programming language are:

Structured programming language Object- oriented programming language


1.Structured programming language is the 1.Object-oriented programming language is the
language which divides a program into language which creates objects that contain
smaller, manageable functions which leads both data and methods.
to easily executed programs.

2.They used to break big complex problems 2.They used a methodology where you start to
into smaller steps of procedures. create object to build complex systems.
3.They emphasize the use of control 3.The emphasizes the use of class, and object,
structures like loops, conditional, and encapsulation, inheritance, and polymorphism.
subroutines.
4.They passed the data to function as 4.They accessed the data and modified it
arguments and return types. through methods.
5.Once the code is reused, it leads to less Reusability of code is achieved through
flexibility. inheritance and polymorphism.
6.They are easy to use, understand and 6.They are suitable for large and complex
maintainable for small programs. programs.

3. In what ways static data members are different from instance Data members?

Ans: Static data members are different from instance data members because static data members
belong to the class itself rather than a particular instance. They are shared across all instances of
the class. When objects of its class are created, they share the same copy of the static field. When
a class member is declared as static it can be accessed without creating any object of its class.

4. Explain encapsulation. Explain four advantages of encapsulation.

Ans: Encapsulation means wrapping a code and data together that operate on the data into a
single unit. It is achieved by using access modifiers (private, public, protected and default). They
are hidden from other classes and can only be accessed by the methods of the class in which they
are found. Encapsulation is an object-oriented procedure of combining data members and data
methods of the class inside the user defined class which is necessary to declare as private.

Four advantages of encapsulation are:

1. Encapsulation allows us to control the access to the data by making class variables
private and providing public getter and setter methods to access and update the values.
2. Encapsulation helps to hide the implementation details and expose only necessary
methods.
3. Encapsulation enhances the security of application by reducing the risk of data being
corrupted and unauthorized access which enhances the data remains constant and secure.
4. Encapsulation improves code maintainability, readability, and security.
5. Why do we make data members private? Explain the use of getter and setter
methods with examples.

Ans: We make data members private to ensure encapsulation. It helps in restricting direct access
to the data from outside the class, promoting data security and better control over how the data is
accessed and modified.

Here we create a class person with private instance variables: name, age by using getter and
setter methods.

public class Person {

// Private instance variables

private String name;

private int age;

// Getter for 'name'

public String get Name () {

return name;

// Setter for 'name'

public void set Name(String name) {

this.name = name;

// Getter for 'age'

public int getAge() {

return age;

}
// Setter for 'age'

public void setAge(int age) {

if (age >= 0) { // Adding validation

this.age = age;

} else {

System.out.println("Age cannot be negative.");

public static void main (String[] args) {

// Creating an object of the Person class

Person person = new Person ();

// Using setters to set values

person.setName("Alice");

person.setAge(30);

// Using getters to access values

System.out.println("Name: " + person.getName());

System.out.println("Age: " + person.getAge());

// Attempting to set a negative age to demonstrate validation

person.setAge(-5);

}
Explanation

1. Instance Variables:

o private String name;

o private int age;

These are declared as private to restrict direct access from outside the class.

2. Getter Methods:

o public String getName(): Returns the value of the name variable.

o public int getAge(): Returns the value of the age variable.

3. Setter Methods:

o public void setName(String name): Sets the value of the name variable.

o public void setAge(int age): Sets the value of the age variable, with a validation
check to ensure age is not negative.

4. Main Method:

o An object person of the Person class is created.

o The setName and setAge methods are used to set the values of name and age.

o The getName and getAge methods are used to retrieve and print the values of
name and age.

o An attempt to set a negative age demonstrates the validation logic in the setAge
method.

6.Explain constructor chaining. Give an example of constructor chaining using “this”


“super” keywords.

Ans: Constructor chaining is the chaining where one constructor calls another constructor in the
same class which helps to reduce redundancy and maintain a clean codebase. This process is
used when we want to perform multiple tasks rather than creating a code for each task in a
single constructor.

Here's an example demonstrating constructor chaining using the super keyword in Java. We'll
create two classes: Person (superclass) and Employee (subclass).

Superclass: Person
public class Person {

private String name;

private int age;

// Default constructor

public Person () {

this ("Unknown", 0);

System.out.println("Person default constructor called");

// Parameterized constructor

public Person (String name, int age) {

this.name = name;

this.age = age;

System.out.println("Person parameterized constructor called");

// Getters

public String getName() {

return name;

public int getAge() {

return age;

}
}

Subclass: Employee

public class Employee extends Person {

private String department;

// Default constructor

public Employee () {

this ("Unknown", 0, "Unknown");

System.out.println("Employee default constructor called");

// Parameterized constructor

public Employee (String name, int age, String department) {

super (name, age); // Calling superclass (Person) constructor

this.department = department;

System.out.println("Employee parameterized constructor called");

// Getter

public String getDepartment() {

return department;

public static void main (String [] args) {

// Creating an object using the default constructor


Employee employee1 = new Employee ().

System.out.println("Name: " + employee1.getName() + ", Age: " + employee1.getAge()


+ ", Department: " + employee1.getDepartment()).

// Creating an object using the parameterized constructor

Employee employee2 = new Employee ("John Doe", 30, "Engineering");

System .out.println("Name: " + employee2.getName() + ", Age: " +


employee2.getAge() + ", Department: " + employee2.getDepartment());

Explanation:

 Superclass: Person

● Default Constructor: Calls the parameterized constructor with default values.

● Parameterized Constructor: Initializes name and age attributes and prints a message
indicating it has been called.

 Subclass: Employee

● Default Constructor: Calls the parameterized constructor with default values and prints
a message.

● Parameterized Constructor: Calls the parameterized constructor of the superclass


(Person) using super (name, age) and initializes the department attribute. It then prints a
message indicating it has been called.

 Main Method:

● Creates two Employee objects using the default and parameterized constructors. The
output shows the order in which constructors are called due to chaining:

o For employee1, it calls the Employee default constructor, which calls the
Employee parameterized constructor, which in turn calls the Person parameterized
constructor.

o For employee2, it directly calls the Employee parameterized constructor, which


calls the Person parameterized constructor.
Practical Portion:

1. Write a program of Student and initializes it through Reference Variable that

contains:

Student id

Student name

Method to display Student name and id

Answer:

public class program1{


int Student_id;
String Student_name;
public program1(int Student_id,String Student_name){
this.Student_id = Student_id;
this.Student_name = Student_name;
}
public void display(){
System.out.println("Student ID: "+Student_id+"\nStudent Name: "+Student_name);
}
public static void main(String args[]){
program1 myObj = new program1(1,"Nikita");
myObj.display();

}
}

2. Write a program of Employee and initializes it through Reference Variable that

contains:

Employee empId

Employee salary

Method to display Employee empId and salary

Answer:
3. Write a program of Car and initializes it through Method that contains:

Car name

Car color

Car price

Method to display Car name and price

Answer:
4. Write a program of Rectangle and initializes it through Method that contains:

Rectangle length

Rectangle breadth

Method to display area and perimeter of Rectangle

Answer:

5. Write a program of Cuboid and initializes it through Constructor that contains:

Cuboid length

Cuboid breadth

Cuboid height

Method to display perimeter and volume of Cuboid.

Answer:
6. Write a program of Circle and initializes it through Constructor that contains:

Circle radius

Constructor to display Circle radius

Method to calculate Circle diameter, perimeter and area.

Answer:
7. Write a program of Account and initializes it through Constructor that contains:
Account name

Account amount

Method to withdraw amount

Method to deposit amount

Method to display Account name and amount

Answer:

public class Account {

private String accountName;

private double accountAmount;

public Account(String accountName, double accountAmount) {

this.accountName = accountName;

this.accountAmount = accountAmount;

public void withdraw(double amount) {

if (amount > 0 && amount <= accountAmount) {

accountAmount -= amount;

System.out.println("Withdrawn: " + amount);

} else {

System.out.println("Invalid withdraw amount.");

public void deposit(double amount) {

if (amount > 0) {

accountAmount += amount;

System.out.println("Deposited: " + amount);


} else {

System.out.println("Invalid deposit amount.");

public void displayAccountInfo() {

System.out.println("Account Name: " + accountName);

System.out.println("Account Amount: " + accountAmount);

public static void main(String[] args) {

Account account = new Account("John Doe", 500.00);

account.displayAccountInfo();

account.deposit(150.00);

account.displayAccountInfo();

account.withdraw(100.00);

account.displayAccountInfo();

account.withdraw(600.00);

account.displayAccountInfo();

8. Write an example of static and non-static/ instance variables.

Answer:

public class StaticExample {

// Static variable
static int staticCounter = 0;

// Instance variable

int instanceCounter = 0;

// Constructor

public StaticExample() {

staticCounter++;

instanceCounter++;

public static void main(String[] args) {

// Creating first instance

StaticExample obj1 = new StaticExample();

System.out.println("After creating obj1:");

System.out.println("Static Counter: " + StaticExample.staticCounter); // Output: 1

System.out.println("Instance Counter (obj1): " + obj1.instanceCounter); // Output: 1

// Creating second instance

StaticExample obj2 = new StaticExample();

System.out.println("After creating obj2:");

System.out.println("Static Counter: " + StaticExample.staticCounter); // Output: 2

System.out.println("Instance Counter (obj2): " + obj2.instanceCounter); // Output: 1

// Creating third instance


StaticExample obj3 = new StaticExample();

System.out.println("After creating obj3:");

System.out.println("Static Counter: " + StaticExample.staticCounter); // Output: 3

System.out.println("Instance Counter (obj3): " + obj3.instanceCounter); // Output: 1

9. Write an example of static and non-static/ instance Method.

Answer:

public class Example_2 {

static int var = 0;

int var_1 = 0;

public static int method_1(){

return ++var;

public int method_2(){

return ++var_1;

public static void main(String args[]){

Example_2 myObj = new Example_2();

System.out.println(Example_2.method_1());

System.out.println(myObj.method_2());

}
Explanation: In this program, we can utilize static methods without the creation of an instance
since it belongs to the class itself. But to utilize the non-static method, we needed to create an
object.

10. Write a program of Class Student which has:

private data member (name)

Setter method (setName)

Getter method (getName)

Answer:

public class Student{

private String name;

public void setName(String name){

this.name = name;

public String getName(){

return name;

public static void main(String argos[]{

Student myObj = new Student();

myObj.setName(“Dipesh”);

System.out.println(myObj.getName());

11. Create Class Car and create four Constructor which has

default constructor
one parameterized constructor < name >

two parameterized constructor < name and color >

three parameterized constructor < name, color and price >

four objects of Car (c1, c2, c3, c4) that calls respective constructor

Answer:

public class Car {

private String name;

private String color;

private double price;

// Default constructor

public Car() {

this.name = "Unknown";

this.color = "Unknown";

this.price = 0.0;

// One parameterized constructor <name>

public Car(String name) {

this.name = name;

this.color = "Unknown";

this.price = 0.0;

// Two parameterized constructor <name, color>


public Car(String name, String color) {

this.name = name;

this.color = color;

this.price = 0.0;

// Three parameterized constructor <name, color, price>

public Car(String name, String color, double price) {

this.name = name;

this.color = color;

this.price = price;

// Method to display Car details

public void displayDetails() {

System.out.println("Car Name: " + name);

System.out.println("Car Color: " + color);

System.out.println("Car Price: $" + price);

// Main method to test the Car class

public static void main(String[] args) {

// Creating Car objects with different constructors

Car c1 = new Car();

Car c2 = new Car("Toyota");


Car c3 = new Car("Honda", "Red");

Car c4 = new Car("BMW", "Black", 50000.0);

// Display details of each Car object

System.out.println("Details of Car c1:");

c1.displayDetails();

System.out.println();

System.out.println("Details of Car c2:");

c2.displayDetails();

System.out.println();

System.out.println("Details of Car c3:");

c3.displayDetails();

System.out.println();

System.out.println("Details of Car c4:");

c4.displayDetails();

You might also like