0% found this document useful (0 votes)
13 views6 pages

Assignment 4 Oop

The document provides an overview of constructors in Java, detailing their characteristics such as having the same name as the class, no return type, and the ability to be overloaded. It also explains the final keyword, static keyword, access modifiers, and includes examples of Java classes like Rectangle and Calculator, demonstrating the use of constructors and methods. Additionally, it discusses the use of the 'this' keyword for referencing the current object and resolving naming conflicts.

Uploaded by

ritikashewale24
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)
13 views6 pages

Assignment 4 Oop

The document provides an overview of constructors in Java, detailing their characteristics such as having the same name as the class, no return type, and the ability to be overloaded. It also explains the final keyword, static keyword, access modifiers, and includes examples of Java classes like Rectangle and Calculator, demonstrating the use of constructors and methods. Additionally, it discusses the use of the 'this' keyword for referencing the current object and resolving naming conflicts.

Uploaded by

ritikashewale24
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
You are on page 1/ 6

1. Define constructor.

What are the characteristics of


constructor. Explain it with an example.
A constructor in Java is a special method used to initialize an object immediately after it is
created. It has the same name as the class and no return type (not even void). Constructors
are typically used to set initial values for object fields or to perform startup procedures.

Characteristics of a Constructor

1. Same Name as Class: The name of the constructor must be exactly the same as the
class name.
2. No Return Type: Constructors do not have any return type—not even void.
3. Automatic Invocation: A constructor is automatically called when you create an
object using new.
4. Can Be Overloaded: A class can have multiple constructors with different parameter
lists (constructor overloading).
5. Cannot Be Inherited: Constructors are not inherited by subclasses, although a
subclass can call a superclass constructor explicitly using super().

Example
public class Car {
private String model;
private int year;

// Default (no-argument) constructor


public Car() {
model = "Unknown Model";
year = 0;
}

// Parameterized constructor
public Car(String model, int year) {
this.model = model;
this.year = year;
}

public void displayInfo() {


System.out.println("Model: " + model + ", Year: " + year);
}
}

// Usage in main:
public class Main {
public static void main(String[] args) {
Car car1 = new Car(); // calls default constructor
Car car2 = new Car("Toyota", 2021); // calls parameterized
constructor

car1.displayInfo();
car2.displayInfo();
}
}
2. Give an example of constructor overloading.
public class Person {
private String name;
private int age;

// 1) Default constructor
public Person() {
this.name = "No name provided";
this.age = 0;
}

// 2) Constructor with one parameter


public Person(String name) {
this.name = name;
this.age = 0;
}

// 3) Constructor with two parameters


public Person(String name, int age) {
this.name = name;
this.age = age;
}

public void display() {


System.out.println("Name: " + name + ", Age: " + age);
}
}

3. Explain the final Keyword in Java


In Java, final can be applied to variables, methods, or classes:

1. final Variable
o A final variable cannot be reassigned once it has been assigned a value.
o This is useful for making constants.
o For example:
o final double PI = 3.14159;
2. final Method
o A final method cannot be overridden by subclasses.
o Useful if you want to maintain the same method implementation across all
subclasses.
3. final Class
o A final class cannot be extended (inherited).
o For example, public final class String { ... } in the Java standard
library cannot be subclassed.

4. State the Use of static Keyword in Java


The static keyword in Java can be applied to variables, methods, nested classes, and
static blocks:

1. static Variable
o A static variable (also known as a class variable) is shared among all instances
of the class.
o For example, a static counter field could keep track of the number of instances
created:
o public class Employee {
o private static int count = 0;
o private String name;
o
o public Employee(String name) {
o this.name = name;
o count++;
o }
o }
2. static Method
o A static method can be called without creating an instance of the class.
o For example, Math.random() is a static method in Java’s Math class.
3. static Block
o A static block is used to initialize static variables when the class is loaded into
memory.
o It is executed only once (the first time the class is loaded).
4. static Nested Class
o A static class defined inside another class. It does not require an instance of
the outer class to be instantiated.

5. Explain All Access Modifiers and Their Visibility as


Class Members
Java has four main access modifiers:

1. public
o Accessible from everywhere (inside the class, within the same package,
outside the package, and by subclasses).
2. private
o Accessible only within the same class.
o Not accessible from outside the class or by subclasses.
3. protected
o Accessible within the same package.
o Also accessible in subclasses, even if they are in different packages.
4. default (also known as package-private, when no modifier is specified)
o Accessible within the same package only.
o Not accessible outside the package if there is no inheritance relationship.
6. Design a java class Rectangle which contains following
field and methods:
(i) Field: length, width: int
(ii) Default Constructor: initialize all fields with 0 value
(iii) Method: int getArea() will return area of rectangle.
Implementation
public class Rectangle {
private double length;
private double width;

// Default constructor
public Rectangle() {
this.length = 0.0;
this.width = 0.0;
}

// Parameterized constructor (optional but often useful)


public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}

// Method to calculate area


public double getArea() {
return this.length * this.width;
}

// Getter and Setter methods (optional)


public double getLength() {
return length;
}

public void setLength(double length) {


this.length = length;
}

public double getWidth() {


return width;
}

public void setWidth(double width) {


this.width = width;
}
}

7. Design a java class Calculator which contains following


field and methods:
(i) Field: num1, num2
(ii) Default and parameterised constructor
(iii) Method: addition(), subtract(), division(),
multiplication()
Implementation
public class Calculator {
private double num1;
private double num2;

// Default constructor
public Calculator() {
this.num1 = 0.0;
this.num2 = 0.0;
}

// Parameterized constructor
public Calculator(double num1, double num2) {
this.num1 = num1;
this.num2 = num2;
}

// Method to add num1 and num2


public double addition() {
return num1 + num2;
}

// Method to subtract num2 from num1


public double subtract() {
return num1 - num2;
}

// Method to divide num1 by num2


public double division() {
if (num2 == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
return num1 / num2;
}

// Method to multiply num1 and num2


public double multiplication() {
return num1 * num2;
}

// Getter and Setter methods (optional)


public double getNum1() {
return num1;
}
public void setNum1(double num1) {
this.num1 = num1;
}
public double getNum2() {
return num2;
}

public void setNum2(double num2) {


this.num2 = num2;
}
}

8. Explain the Use of the this Keyword


In Java, the this keyword is a reference to the current object. It is primarily used for:

1. Referring to Instance Variables: When parameter names and instance variables


overlap, use this.variable to avoid ambiguity.
2. Invoking Other Constructors: You can call one constructor from another
constructor in the same class using this(...).
3. Returning the Current Object: Methods can return the current object reference to
allow method chaining.
4. Passing the Current Object: Sometimes you need to pass the current object as an
argument to another method.

Example
public class Point {
private int x;
private int y;

// Using 'this' to differentiate parameter names from instance


variables
public Point(int x, int y) {
this.x = x; // 'this.x' is the instance variable, while 'x' is the
parameter
this.y = y;
}

// Using 'this' to call another constructor


public Point() {
this(0, 0); // calls the parameterized constructor
}

// A method demonstrating returning 'this' for chaining


public Point setX(int x) {
this.x = x;
return this; // return the current object
}

public Point setY(int y) {


this.y = y;
return this;
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy