0% found this document useful (0 votes)
38 views36 pages

Java Assignment 1

Uploaded by

Dipesh Thakur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
38 views36 pages

Java Assignment 1

Uploaded by

Dipesh Thakur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 36

Texas College of Management and IT

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;

public class Main1{

int var1 = 2;

public static void main(string[]args){

System.out.println(“Hello world”);

Main1 myObj = new Main1();

System.out.println(myObj.var1);

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 allow 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 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.

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 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.

public class Person {

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

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:
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:
Tricky Question!!

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:
8. Write examples of static and non-static/ instance variables.

Answer:

Static Variable:

public class Main{

static int var = 1;

public static void main(String args[]){

System.out.println(var);

Non-static Variable:

public class NonStaticExample {


int instanceVar = 10;

public static void main(String[] args) {


NonStaticExample obj = new NonStaticExample();
System.out.println("Instance Variable: " + obj.instanceVar);
}
}

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

Answer:

import java.util.Scanner;

public class Main{

int var;

Main(int var){

this.var = var;

static void display(){//Static method

System.out.println("I am static!");

void display_1(){//Non-static method

System.out.println("I am non-static and I print: "+var);

public static void main(String args[]){

int var_1;

Scanner myObj_1 = new Scanner(System.in);

System.out.print("Enter an integer: ");

var_1 = myObj_1.nextInt();

Main myObj_2 = new Main(var_1);

display();

myObj_2.display_1();
}

10. Write a program of Class Student which has:

private data member (name)

Setter method (setName)

Getter method (getName)

Answer:

11. Write an example of read-only and write-only class that has:

private data member

only setter method

only getter method

Answer:
12. 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:
Chapter 2 - Inheritance and Polymorphism

Theory portion

1. What is Inheritance? Explain different types of inheritance in Java with examples?


Answer: Inheritance is the mechanism where one parent inherited their off-spring from one
generation to another generation. It allows for code reuse and the creation of a hierarchical
relationship between classes.and there are five types of inheritance in java as:

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.

Answer: In java, Method overriding is when a subclass provides a specific implementation of


method that is already provided by its parent class.

Method overriding is when a subclass provides a specific implementation of a method that is


already provided by its parent class. This allows the subclass to have a specialized version of a
method that is already defined in its superclass but method overloading is when multiple
methods in the same class have the same name but different parameters. This allows methods to
have the same name but different signatures,distinguishing them based on the number of types of
parameters they accept.

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.

Default:It allows access only within the same package.

Private:It restricted access to the class,method,or variable only within the same class.

4. What is the interface? How does it differ from abstract 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.

5. Highlight the purposes of making the class and method final.

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

1. Write a program which contains:

Animal as super class


Color white (instance variable of super class)
Dog as subclass of Animal
Color black (instance variable of subclass)
Print white color using super keyword
Printblack color.
Answer:
2. Write a program which contain:

Person as super class o Method getName() (instance method of super class)

Student as subclass of Person

method getRoll() (instance method of subclass)


call getName() method using super keyword

call getRoll() method

Answer:

3. Write a program which contains


Human as super class

it’s constructor

Man as sub class of Human

call parent class constructor immediately on its own constructor

Answer:

4. Write a program which contains


Computer as super class and it has a Method info()

Laptop as subclass of Computer and Method info()

Computer reference and object

Computer reference but Laptop object

Call info() method of Computer reference and object.

Call info() method of Computer reference but Laptop object.

Note: (Example of method overriding)

Answer:
5. Write a program which contains

Language as abstract class and Method display(){}

Main as subclass of Language

Object of Main

access method of abstract class using object of Main class

Note: (Example of accessing method from the abstract class)

Answer:
6. Write a program which contains

Vehicle as abstract class o abstract method speed()

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

Note: (Example of using abstract methods).

Answer:
7. Implement the following UML in java code:

Answer:
8. Write a program which contain:
interface Pet o method test()

implement Pet in class Dog

Answer:
9. Write a program which contains

interface Result

method area ()

implement Result in class Rectangle

provide length o

provide breadth

Answer:
10. Write a program which contains

Class MethodOverloading

method display ()

method display (int a)

method display (int a, int b)

MethodOverloading objects m1, m2, m3

call all methods

Note: (Example of method overloading)

Answer:
11. Write a simple program of Upcasting and Downcasting?

Answer:

You might also like