Java Assignment 1
Java Assignment 1
Java Programming
Explore, Learn and Excel
Assignment 1
Submitted By:
Nikita Rayamajhi
BIT, Semester-2
Section-F
LCID:LC00017002695
Chapter 1
Theoretical Portion:
1. Introduce classes and objects. 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.
Here is an example which illustrates how the class and object will work and be used;
int var1 = 2;
System.out.println(“Hello world”);
System.out.println(myObj.var1);
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 objects 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.
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.
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 exposing 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 due 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.
return name;
this.name = name;
return age;
this.age = age;
} else {
System.out.println("Age cannot be negative.");
person.setName("Alice");
person.setAge(30);
person.setAge(-5);
Explanation
1. Instance Variables:
These are declared as private to restrict direct access from outside the class.
2. Getter Methods:
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 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.
Ans: Constructor chaining is the chaining which when 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
// Default constructor
public Person () {
// Parameterized constructor
public Person (String name, int age) {
this.name = name;
this.age = age;
// Getters
return name;
return age;
Subclass: Employee
// Default constructor
public Employee () {
// Parameterized constructor
this.department = department;
System.out.println("Employee parameterized constructor called");
// Getter
return department;
Explanation:
Superclass: Person
● 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.
Practical Portion
1. Write a program of Student and initializes it through Reference Variable that contains:
Student id
Student name
Answer:
2. Write a program of Employee and initializes it through Reference Variable that contains:
Employee empId
Employee salary
Answer:
Car name
Car color
Car price
Answer:
4. Write a program of Rectangle and initializes it through Method that contains:
Rectangle length
Rectangle breadth
Answer:
Cuboid length
Cuboid breadth
Cuboid height
Answer:
6. Write a program of Circle and initializes it through Constructor that contains:
Circle radius
Answer:
Tricky Question!!
Account name
.Account amount
Answer:
8. Write examples of static and non-static/ instance variables.
Answer:
Static Variable:
System.out.println(var);
Non-static Variable:
Answer:
import java.util.Scanner;
int var;
Main(int var){
this.var = var;
System.out.println("I am static!");
int var_1;
var_1 = myObj_1.nextInt();
display();
myObj_2.display_1();
}
Answer:
Answer:
12. Create Class Car and create four Constructor which has
default constructor
four objects of Car (c1, c2, c3, c4) that calls respective constructor
Answer:
Chapter 2 - Inheritance and Polymorphism
Theory portion
Single-level inheritance
The fundamental concept where a subclass inherits from only one superclass. This means that the
subclass can acquire the properties and methods of the superclass, enabling code reuse and the
extension of existing functionality.
Multi-level Inheritance
It allows a class to inherit properties and behaviors from another class, which in turn inherits
from another class, forming a "chain" of inheritance. This mechanism enables a class to inherit
methods and fields from multiple ancestors but in a direct line, where each class in the chain
inherits from one class directly above it.
Hierarchical Inheritance
It occurs when one base class (superclass) is inherited by multiple subclasses. In this type of
inheritance, all the features that are common in child classes are included in the base class. This
way, the code becomes more manageable and reusable.
Multiple Inheritance
It refers to a feature in object-oriented programming where a class can inherit properties and
methods from more than one parent class. This concept allows a subclass to inherit behaviors and
attributes from multiple base (or super) classes, creating a rich, multifaceted hierarchy.
Hybrid Inheritance
It is a combination of two or more types of inheritance, such as hierarchical, multiple, multilevel,
or single inheritance. It integrates various inheritance mechanisms to achieve a specific design or
functionality.
Here is an example of inheritance;
class Animal {
String species;
Animal(String species){
this.species=species;
}
void makesound(){
System.out.println("Some generic sound");
}
class Dog extends Animal{
String name;
Dog(String name){
super("Dog");
this.name=name;
}
void makeSound(){
System.out.println("woof");
}
public class Main{
public static void main(String[]args) {
Animal animal = new Animal("Cat");
animal.makesound();
}
Dog dog=new Dog("Buddy");
dog.makeSound();
System.out.println(dog.species);
System.out.println(dog.name);
}
}
}
2. What is method overriding? How does it differ from method overloading? Explain.
3. Define abstract class and method. Explain different types of Access controls available in
java.
Answer: In java,an abstract class is a class that cannot be instantiated on its own and may
contain abstract methods which are mentioned without a body. Abstract methods meant to be
implemented by subclasses.
Access control in java determines the visibility of classes,methods, and variables to other classes
and there are different types of access control available in java:
public:It allows unrestricted access to the class,method, or variable from any other class.
Protected:It provides access to the class,method or variable within the same package or by
subclass in different packages.
Private:It restricted access to the class,method,or variable only within the same class.
Answer:In java, an interface is like a contract which defines a set of methods that a class must
implement and which specifies what a class can do but not how it does it.
The main difference between interface and abstract is that a class can implement multiple
interfaces but can only inherit from one abstract class. Similarly, in an interface all methods are
public and abstract by default.
Answer: Making a class or method final in java serves the purpose of preventing the class from
being subclass or the method from being overridden. When a class is declared final, it cannot be
extended by any subclass. Similarly, when a method is marked as final, it cannot be overridden
by subclasses,ensuring that the method’s implementation remains unchanged.
Practical Portion
Answer:
it’s constructor
Answer:
Answer:
5. Write a program which contains
Object of Main
Answer:
6. Write a program which contains
Car as sub class of Vehicle and Implement abstract method speed() for Vehicle.
Bike as sub class of Vehicle and it implements abstract method speed () for Vehicle
Answer:
7. Implement the following UML in java code:
Answer:
8. Write a program which contain:
interface Pet o method test()
Answer:
9. Write a program which contains
interface Result
method area ()
provide length o
provide breadth
Answer:
10. Write a program which contains
Class MethodOverloading
method display ()
Answer:
11. Write a simple program of Upcasting and Downcasting?
Answer: