0% found this document useful (0 votes)
10 views

Oops Through Java Unit-2

The document explains key concepts of Object-Oriented Programming (OOP) in Java, including inheritance, multilevel inheritance, method overriding, interfaces, and access protection. It provides example programs to illustrate these concepts, such as a Vehicle and Car class for inheritance, and an Animal interface for implementing behaviors. Additionally, it discusses the differences between abstract classes and interfaces, the concept of class paths, and the importance of packages in organizing Java code.

Uploaded by

m7zxff777
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Oops Through Java Unit-2

The document explains key concepts of Object-Oriented Programming (OOP) in Java, including inheritance, multilevel inheritance, method overriding, interfaces, and access protection. It provides example programs to illustrate these concepts, such as a Vehicle and Car class for inheritance, and an Animal interface for implementing behaviors. Additionally, it discusses the differences between abstract classes and interfaces, the concept of class paths, and the importance of packages in organizing Java code.

Uploaded by

m7zxff777
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

OOPS THROUGH JAVA

UNIT-2
1. Explain implementation of inheritance with an example program

Inheritance in Java:
In Java, inheritance is implemented using the extends keyword. A subclass inherits fields and methods
from a superclass, allowing for code reuse and extending functionality.

Example Program:
In this example, we'll create a Vehicle class as the parent class and a Car class as the child class that
inherits from Vehicle.
// Parent Class (Superclass)
class Vehicle {
// Fields (Attributes)
String make;
String model;
int year;

// Constructor
public Vehicle(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}

// Method to display vehicle information


public void displayInfo() {
System.out.println(year + " " + make + " " + model);
}
}

// Child Class (Subclass) that inherits from Vehicle


class Car extends Vehicle {
// Additional attribute specific to Car
int doors;

1
// Constructor for Car class
public Car(String make, String model, int year, int doors) {
// Call the parent class constructor
super(make, model, year);
this.doors = doors;
}

// Method specific to Car class


public void carInfo() {
displayInfo(); // Call the inherited method from Vehicle class
System.out.println("Number of doors: " + doors);
}
}

// Main class to test inheritance


public class Main {
public static void main(String[] args) {
// Create an object of the Car class
Car myCar = new Car("Toyota", "Corolla", 2020, 4);

// Call the carInfo method


myCar.carInfo();
}
}
Explanation:
1. Parent Class (Vehicle):
o This class has three fields: make, model, and year, representing basic information about the
vehicle.
o The constructor initializes these fields when a new Vehicle object is created.
o The displayInfo () method is used to print out the vehicle's details.
2. Child Class (Car):
o This class extends Vehicle using extends Vehicle, meaning Car inherits the fields and methods
from Vehicle.
o The Car class introduces a new field door to specify how many doors the car has.
o The constructor of the Car class calls the constructor of the Vehicle class using super(...) to
initialize the inherited fields (make, model, and year).
2
o The carInfo () method in Car displays both the inherited vehicle information and the number
of doors specific to the car.
3. Main Class:
o In the Main class, we create an instance of Car, passing in the required parameters (make,
model, year, and number of doors).
o The carInfo () method is then called on the myCar object, which prints both the vehicle's
information and the number of doors.
Output:
2020 Toyota Corolla
Number of doors: 4
Key Points:
extends: In Java, a subclass is defined using the extends keyword to inherit from a superclass.
super (): The super () keyword is used in the subclass constructor to call the constructor of the
superclass.
The subclass inherits all public and protected members (fields and methods) from the superclass and
can also introduce its own specific fields and methods.
2. Illustrate how to implement multilevel inheritance with an example program.
In Java, multilevel inheritance occurs when a class is derived from another class, which is itself derived
from another class. In other words, a class inherits from a class that is already a subclass of another
class. This forms a chain of inheritance.

Example of Multilevel Inheritance:


Let’s consider a situation where we have three classes:

Animal (the parent class)


Mammal (a subclass of Animal)
Dog (a subclass of Mammal)
Java Program:
// Parent Class (Superclass)
class Animal {
// Field
String name;

// Constructor
public Animal(String name) {
this.name = name;
3
}

// Method to describe an animal


public void eat() {
System.out.println(name + " is eating.");
}
}

// Child Class (Subclass) - Inheriting from Animal


class Mammal extends Animal {
// Constructor for Mammal class
public Mammal(String name) {
// Calling the parent class constructor
super(name);
}

// Method specific to Mammal


public void sleep() {
System.out.println(name + " is sleeping.");
}
}

// Grandchild Class (Subclass of Mammal) - Inheriting from Mammal


class Dog extends Mammal {
// Constructor for Dog class
public Dog(String name) {
// Calling the parent class (Mammal) constructor
super(name);
}

// Method specific to Dog


public void bark() {
System.out.println(name + " is barking.");
}
}

4
// Main Class
public class Main {
public static void main(String[] args) {
// Creating an object of Dog class
Dog dog = new Dog("Buddy");

// Calling methods from all levels of the inheritance chain


dog.eat(); // Inherited from Animal
dog.sleep(); // Inherited from Mammal
dog.bark(); // Specific to Dog
}
}
Explanation:
Parent Class (Animal):

This class has a field name and a constructor to initialize it.


The eat () method is defined to represent eating behavior common to all animals.
Child Class (Mammal):

The Mammal class inherits from Animal using extends Animal. This means Mammal inherits the name
field and the eat () method.
It has a constructor that calls the Animal constructor using super(name).
Additionally, the Mammal class introduces a sleep () method.
Grandchild Class (Dog):

The Dog class extends Mammal, which means it inherits both the fields and methods from Animal
(through Mammal).
The constructor of the Dog class calls the Mammal constructor using super(name), which further
invokes the Animal constructor.
The Dog class introduces a bark () method, which is specific to dogs.
Main Class:

An object dog of type Dog is created. This object can call methods from all the parent classes: eat ()
(from Animal), sleep () (from Mammal), and bark() (from Dog).
Output:
Buddy is eating.

5
Buddy is sleeping.
Buddy is barking.
3. Explain method overriding and usage of super keyword.
Method Overriding occurs when a subclass provides its specific implementation of a method that is
already defined in its superclass. The method in the subclass must have the same name, return type,
and parameter list as the method in the superclass.

Overriding allows the subclass to modify or extend the behavior of the superclass method, providing
a more specific implementation.
Usage of the super Keyword:
The super keyword in Java is used to refer to the immediate parent class of the current class. It has
several uses:

Accessing Parent Class Methods: You can use super to call a method of the parent class, even if it is
overridden in the child class.
Accessing Parent Class Constructor: You can use super () to call the parent class constructor.
Accessing Parent Class Fields: You can use super to refer to parent class fields, particularly if they are
hidden by fields in the subclass.
Example of super Keyword:
// Parent Class
class Animal {
// Method to be overridden
public void sound() {
System.out.println("Animal makes sound");
}
}

// Child Class
class Dog extends Animal {
// Overriding the sound() method
@Override
public void sound() {
super.sound(); // Calling the method of the parent class (Animal)
System.out.println("Dog barks");
}
}
6
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound(); // Calling the overridden method in Dog
}
}
Output:
Animal makes sound
Dog barks
4. Describe concept of interfaces.
An interface in Java is a reference type, similar to a class, that can contain only abstract methods
(methods without body) and constant variables (public, static, and final). An interface specifies a
contract or blueprint for the classes that implement it. In other words, it defines a set of behaviors
(methods) that the implementing classes must provide. Interfaces are used to represent a "what" an
object can do, without specifying how it does it.

Interfaces are crucial in Java for achieving abstraction and multiple inheritance.
Key Characteristics of Interfaces:
Abstract Methods: All methods in an interface are implicitly abstract (i.e., they don’t have a body).
From Java 8 onwards, interfaces can also have default methods with a body and static methods.
Constants: Variables declared in an interface are implicitly public, static, and final. They must be
initialized when declared.
Multiple Inheritance: A class can implement multiple interfaces, which allows Java to support
multiple inheritance of behavior (since a class can only extend one class but can implement multiple
interfaces).
No Constructor: Interfaces cannot have constructors, as they cannot be instantiated directly.
interface MyInterface {
// Abstract method
void myMethod();

// Constants (implicitly public, static, and final)


int MAX_VALUE = 100;

// Default method (Java 8 onwards)


default void defaultMethod() {
7
System.out.println("This is a default method.");
}

// Static method (Java 8 onwards)


static void staticMethod() {
System.out.println("This is a static method in interface.");
}
}
5. Define an interface.
An interface in Java is a reference type that defines a contract or blueprint for other classes to
implement. It specifies a set of abstract methods (methods without a body) that the implementing
classes must provide. An interface can also contain constants, default methods (with a body), and static
methods (introduced in Java 8).

Interfaces are used to define what a class can do, but not how it does it. They provide a way to achieve
abstraction and multiple inheritance of behavior in Java.
Example of Using an Interface:
// Defining an Interface
interface Animal {
// Abstract method
void sound();

// Default method
default void sleep() {
System.out.println("Animal is sleeping.");
}
}

// Implementing the Interface


class Dog implements Animal {
// Implementing the abstract method
@Override
public void sound() {
System.out.println("Dog barks");
}
}
8
public class Main {
public static void main(String[] args) {
// Creating an object of Dog class
Animal dog = new Dog();

// Calling implemented method


dog.sound(); // Output: Dog barks

// Calling default method from the interface


dog.sleep(); // Output: Animal is sleeping.
}
}
6. Differences between abstract classes and interface.

7. Explain how to implement interfaces with sample program.


In Java, an interface defines a contract or blueprint for the methods that a class should implement. A
class implements an interface, and in doing so, it must provide the actual implementation for all the
abstract methods defined in the interface. An interface cannot have any method bodies (except for

9
default or static methods introduced in Java 8), and the implementing class must fill in the behavior of
those methods.

Steps to Implement an Interface:


Define the Interface: Create an interface with abstract methods (methods without a body) that will
define the contract.
Implement the Interface: A class uses the implements keyword to implement the interface and
provide the actual method bodies.
Create an Object: Instantiate the class that implements the interface and use its methods.
Example of Implementing an Interface in Java
Let's create a simple example to demonstrate the concept:

1. Define the Interface:


// Defining an Interface
interface Animal {
// Abstract method (no body)
void sound();

// Default method (from Java 8)


default void sleep() {
System.out.println("This animal is sleeping.");
}

// Static method (from Java 8)


static void breathe() {
System.out.println("This animal is breathing.");
}
}
OUTPUT:
The dog barks
The dog is sleeping peacefully.
8. Define a package.
In Java, a package is a mechanism for organizing Java classes, interfaces, and sub-packages into
namespaces. It helps to group related classes and interfaces together, making it easier to maintain and
manage large applications. Packages provide a way to avoid naming conflicts and to control access to
classes and interfaces.
10
Types of Packages:
Built-in Packages: These are predefined in the Java API. For example, java.util, java.io, java.lang,
etc.
User-defined Packages: These are packages created by the developer to organize classes into a logical
grouping for their specific application.
Key Benefits of Using Packages:
Namespace Management: Packages help avoid class name conflicts by distinguishing between
classes with the same name that belong to different packages.
Access Control: Packages help in controlling the access to classes, methods, and variables.
Modularity: Packages allow you to break down large software projects into smaller, manageable
pieces.
Reusability: Code within packages can be easily reused in different parts of the program or in other
programs.
import java.util.ArrayList;

public class Example {


public static void main (String[] args) {
// Using ArrayList from java.util package
ArrayList<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");

for (String item : list) {


System.out.println(item);
}
}
}
9. Explain the concept of class path.
The class path in Java is a parameter (either an environment variable or a command-line argument)
that tells the Java Virtual Machine (JVM) and Java compiler where to find the class files (compiled
.class files) that are required for running a Java program. It essentially defines the location of classes
and libraries that the JVM needs in order to execute a program.

11
When you run a Java program or compile Java code, the JVM or the Java compiler looks through the
directories and JAR (Java ARchive) files specified in the class path to locate the necessary classes. If
a class is not found in the class path, the JVM will throw a ClassNotFoundException.

Key Points About Classpath:


Contains Locations of Classes: The class path specifies directories or JAR files that contain compiled
Java classes.
Can Be Set in Multiple Ways:
Environment Variable: You can set the classpath as an environment variable (CLASSPATH).
Command-line Argument: You can specify the class path when running or compiling Java code using
the -cp or -class path option.
Can Include Directories and JAR Files: The class path can include both directories (where .class
files are stored) and JAR files (which package many .class files into a single file).
Default Class path: If no class path is specified, the JVM uses the current directory (.) as the default
class path, meaning it will look for classes in the directory from which the program is being executed.
Class Loading: The JVM searches the class path in the order it is defined to find the required classes.
How to Set the Class path:
Using Command Line:

You can specify the class path directly when compiling or running Java programs by using the -cp or
-class path option.
Example:
javac -cp /path/to/classes:/path/to/lib/some-library.jar MyClass.java
java -cp /path/to/classes:/path/to/lib/some-library.jar MyClass
10. Describe concept of Access protection.
In Java, access protection refers to the mechanisms that control the visibility and accessibility of
classes, methods, variables, and constructors from other classes or packages. These mechanisms help
in implementing encapsulation, which is a core principle of object-oriented programming, by
controlling how and where the members of a class can be accessed.

Java provides four main access modifiers that define the scope of access to classes and their members
(fields, methods, and constructors). These access modifiers are:

public
protected
default (no modifier)
12
private
1. public Access Modifier:
Scope: The public access modifier allows the class, method, or variable to be accessible from any other
class (within any package).
Usage: It is used when you want to make a class, method, or field accessible universally.
Example:
public class Car {
public String model; // This field is accessible from any other class

public void display() { // This method is accessible from any other class
System.out.println("Car model: " + model);
}
}
2. protected Access Modifier:
Scope: The protected modifier allows access to the member within:
The same package.
Subclasses (even if the subclass is in a different package).
Usage: It is typically used when you want a method or field to be accessible by classes within the same
package or subclasses that extend the class, regardless of whether those subclasses are in the same
package.
Example:
class Animal {
protected String species; // Can be accessed by subclasses and other classes in the same
package

protected void makeSound() {


System.out.println("Animal sound");
}
}

class Dog extends Animal {


public void bark() {
makeSound(); // Can access protected method from parent class
}
}
default Access Modifier (Package-Private):
13
Scope: The default access modifier (also called package-private) means the member is accessible only
within the same package. If no access modifier is specified, this is the default behavior.
Usage: It is used when you want the class or member to be accessible within the same package but not
outside of it.
Example:
class Car {
String model; // No access modifier: default (package-private)

void display() { // Default access: accessible within the same package


System.out.println("Car model: " + model);
}
}
private Access Modifier:
Scope: The private access modifier restricts access to the class, method, or variable to within the
same class only. It is the most restrictive access level.
Usage: It is used to encapsulate data and provide access through getters and setters, ensuring that
the data is not directly accessed or modified by external classes.
Example:
class Person {
private String name; // Can only be accessed within the Person class

private void setName(String name) { // Can only be accessed within the Person class
this.name = name;
}

public String getName() { // Public method to access the private name


return name;
}
}
Total program:
// In package com.example
package com.example;

public class Animal {


public String name;
protected int age;
14
String species; // default access (package-private)
private String secret;

public Animal(String name, int age, String species, String secret) {


this.name = name;
this.age = age;
this.species = species;
this.secret = secret;
}

public void revealSecret() {


System.out.println("The secret is: " + secret);
}
}

class Dog extends Animal {


public Dog(String name, int age, String species, String secret) {
super(name, age, species, secret);
}

public void displayInfo() {


// Accessing members of the parent class
System.out.println("Name: " + name); // public member, accessible
System.out.println("Age: " + age); // protected member, accessible
// System.out.println("Species: " + species); // default member, accessible because it's in
the same package
// System.out.println("Secret: " + secret); // private member, NOT accessible
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog("Buddy", 3, "Dog", "Loves to play fetch");
dog.displayInfo();
dog.revealSecret(); // Public method from the Animal class
}
15
}
Output:
Name: Buddy
Age: 3
Secret: Loves to play fetch

16

You might also like