[go: up one dir, main page]

0% found this document useful (0 votes)
89 views22 pages

Unit 4

Single-level inheritance occurs when a subclass inherits from a single superclass. Multilevel inheritance occurs when a subclass inherits from a superclass, which in turn inherits from another superclass. Method overriding allows a subclass to provide its own implementation of a method defined in the superclass. Dynamic method dispatch determines which implementation of an overridden method to execute based on the actual type of the object at runtime. Abstract classes cannot be instantiated but can be subclassed, while interfaces define contracts that classes can implement.

Uploaded by

Ayush Rai
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)
89 views22 pages

Unit 4

Single-level inheritance occurs when a subclass inherits from a single superclass. Multilevel inheritance occurs when a subclass inherits from a superclass, which in turn inherits from another superclass. Method overriding allows a subclass to provide its own implementation of a method defined in the superclass. Dynamic method dispatch determines which implementation of an overridden method to execute based on the actual type of the object at runtime. Abstract classes cannot be instantiated but can be subclassed, while interfaces define contracts that classes can implement.

Uploaded by

Ayush Rai
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/ 22

UNIT-IV

Inheritance: (Single Level and Multilevel)

Inheritance is a mechanism in object-oriented programming that allows a new class


to be based on an existing class. The new class, known as the subclass, inherits the
properties and behaviors of the existing class, known as the superclass.

In Java, there are two types of inheritance: single-level inheritance and multilevel
inheritance.

Single-Level Inheritance: Single-level inheritance occurs when a subclass inherits


from a single superclass. This means that the subclass is derived from one parent
class only. The subclass can inherit all of the public and protected methods and
variables from the superclass, and can add its own methods and variables as well.

For example, consider the following code snippet:

class Vehicle {
public void start() {
System.out.println("Vehicle started");
}
}

class Car extends Vehicle {


public void drive() {
System.out.println("Car is being driven");
}
}

public class Main {


public static void main(String[] args) {
Car myCar = new Car();
myCar.start();
myCar.drive();
}
} (); } }

In this example, the class Car is a subclass of the class Vehicle. The Car class
inherits the start() method from the Vehicle class and adds its own drive() method.

Multilevel Inheritance: Multilevel inheritance occurs when a subclass inherits from


a superclass, which in turn inherits from another superclass. This means that the
subclass is derived from multiple parent classes. The subclass can inherit all of the
public and protected methods and variables from its parent classes, and can add its
own methods and variables as well.

For example, consider the following code snippet:

class Animal {
public void eat() {
System.out.println("Animal is eating");
}
}

class Mammal extends Animal {


public void walk() {
System.out.println("Mammal is walking");
}
}

class Dog extends Mammal {


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

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat();
myDog.walk();
myDog.bark();
}

In this example, the class Dog is a subclass of the class Mammal, which is itself a
subclass of the class Animal. The Dog class inherits the eat() method from the
Animal class, the walk() method from the Mammal class, and adds its own bark()
method.

Method Overriding

Method Overriding is a concept in Java where a subclass provides its


implementation for a method that is already defined in its superclass. This allows
the subclass to change the behavior of the method in a way that is more appropriate
for its own needs.

To override a method, the subclass must provide a method with the same name,
return type, and parameters as the method in the superclass. The method in the
subclass must also have the same or a more accessible access modifier than the
method in the superclass.

When the method is called on an object of the subclass, the implementation in the
subclass is executed instead of the implementation in the superclass. This is
because the Java Virtual Machine (JVM) determines the implementation of the
method based on the actual type of the object at runtime, rather than the declared
type of the reference variable.

Here's an example of method overriding in Java:

class Animal {

public void makeSound() {

System.out.println("Animal is making a sound");

class Cat extends Animal {

@Override

public void makeSound() {

System.out.println("Meow");

public class Main {

public static void main(String[] args) {


Animal animal = new Animal();

animal.makeSound(); // Output: Animal is making a sound

Cat cat = new Cat();

cat.makeSound(); // Output: Meow

Animal anotherAnimal = new Cat();

anotherAnimal.makeSound(); // Output: Meow

In this example, the Animal class has a method makeSound(). The Cat class extends
the Animal class and overrides the makeSound() method with its own
implementation that prints "Meow". In the main method, an object of the Animal
class and an object of the Cat class are created, and the makeSound() method is
called on each object. When the method is called on the Cat object, the
implementation in the Cat class is executed, even though the reference variable is
of type Animal. This demonstrates the dynamic method dispatch feature of Java.

Dynamic Method Dispatch


Dynamic Method Dispatch is a mechanism in Java that allows a subclass to
override a method in its superclass and then execute the overridden method at
runtime. This is achieved through the use of the concept of polymorphism.

When a method is called on an object, the JVM looks at the type of the object at
runtime and determines which implementation of the method to execute. If the
method is overridden in the subclass, the implementation in the subclass is
executed instead of the implementation in the superclass. This is known as
dynamic method dispatch.

Here's an example of dynamic method dispatch in Java:


class Animal {

public void makeSound() {

System.out.println("Animal is making a sound");

class Cat extends Animal {

@Override

public void makeSound() {

System.out.println("Meow");

public class Main {

public static void main(String[] args) {

Animal animal = new Animal();

animal.makeSound(); // Output: Animal is making a sound

Cat cat = new Cat();

cat.makeSound(); // Output: Meow

Animal anotherAnimal = new Cat();

anotherAnimal.makeSound(); // Output: Meow

}
In this example, the Animal class has a method makeSound(). The Cat class extends
the Animal class and overrides the makeSound() method with its own
implementation that prints "Meow". In the main method, an object of the Animal
class, an object of the Cat class, and a reference variable of type Animal referring
to an object of the Cat class are created. When the makeSound() method is called
on each object or reference variable, the implementation that is executed is
determined at runtime based on the actual type of the object, demonstrating
dynamic method dispatch.

Abstract Classes
In Java, an abstract class is a class that cannot be instantiated on its own, but can be
subclassed by other classes. Abstract classes are useful when creating a hierarchy
of classes that share some common functionality, but each subclass has its own
specific behavior.

An abstract class is declared using the abstract keyword in its class definition. It can
contain both abstract and non-abstract methods. Abstract methods are methods that
do not have an implementation and are declared using the abstract keyword. Non-
abstract methods, on the other hand, have an implementation and are declared as
usual.

Here's an example of an abstract class in Java:

abstract class Animal {

public abstract void makeSound();

public void eat() {

System.out.println("Animal is eating");

class Cat extends Animal {

@Override

public void makeSound() {

System.out.println("Meow");
}

public class Main {

public static void main(String[] args) {

Animal animal = new Cat();

animal.makeSound(); // Output: Meow

animal.eat(); // Output: Animal is eating

In this example, the Animal class is declared as an abstract class with an abstract
method makeSound() and a non-abstract method eat(). The Cat class extends the Animal
class and provides an implementation for the makeSound() method.

In the Main class, an object of the Cat class is created and assigned to a reference
variable of type Animal. The makeSound() and eat() methods are called on the reference
variable, which calls the implementation of the makeSound() method from the Cat
class and the implementation of the eat() method from the Animal class.
Note that you cannot create an instance of an abstract class using the new keyword. You can only create instances of its non-
abstract subclasses. Also, if a class contains one or more abstract methods, it must be declared as abstract.

Interfaces and Packages


Interfaces and packages are important concepts in Java that help in organizing and structuring
code.

Interfaces: An interface is a collection of abstract methods and constant variables. It defines a


contract that a class can implement to provide certain functionality. In Java, an interface is
declared using the interface keyword followed by the interface name. All methods in an
interface are by default public and abstract, and all variables are by default public, static, and
final. A class can implement multiple interfaces.

Here's an example of an interface in Java:

interface Animal {

public void makeSound();


}

class Cat implements Animal {

@Override

public void makeSound() {

System.out.println("Meow");

public class Main {

public static void main(String[] args) {

Animal animal = new Cat();

animal.makeSound(); // Output: Meow

In this example, the Animal interface defines a single method makeSound(). The Cat class
implements the Animal interface and provides an implementation for the makeSound()
method.

Packages: A package is a namespace that organizes a set of related classes and interfaces. It
provides a way to group related classes together and also prevents naming conflicts between
classes with the same name. In Java, a package is declared using the package keyword at the
beginning of a Java file. By convention, the package name is in reverse order of the domain
name of the organization that created the code.

Here's an example of a package in Java:

package com.example.animals;

interface Animal {

public void makeSound();

}
class Cat implements Animal {

@Override

public void makeSound() {

System.out.println("Meow");

public class Main {

public static void main(String[] args) {

Animal animal = new Cat();

animal.makeSound(); // Output: Meow

In this example, the Animal interface and the Cat and Main classes are declared in the
com.example.animals package. This package can be organized in a directory structure that
reflects the package name, with the Java files in the corresponding directory. For example,
the Main.java file can be located in the directory com/example/animals. To use classes from
this package in other Java files, you can use the import statement at the beginning of the file.

Extending interfaces and packages

Extending interfaces and packages are important concepts in Java that help in
organizing and structuring code and also provide flexibility in code reuse.

Extending Interfaces: In Java, an interface can extend one or more other interfaces
using the extends keyword. When an interface extends another interface, it inherits
all the methods and constants from the parent interface. The child interface can
also add its own methods and constants.

Here's an example of extending interfaces in Java:

interface Animal {

public void makeSound();


}

interface Mammal extends Animal {

public void giveBirth();

class Cat implements Mammal {

@Override

public void makeSound() {

System.out.println("Meow");

@Override

public void giveBirth() {

System.out.println("Giving birth to kittens");

public class Main {

public static void main(String[] args) {

Mammal mammal = new Cat();

mammal.makeSound(); // Output: Meow

mammal.giveBirth(); // Output: Giving birth to kittens

In this example, the Animal interface defines a single method makeSound(). The
Mammal interface extends the Animal interface and adds a new method giveBirth(). The
Cat class implements the Mammal interface and provides implementations for both
the makeSound() and giveBirth() methods.
Extending Packages: In Java, packages can also be organized hierarchically. This
allows for easy grouping of related packages and also provides flexibility in code
reuse. When a package extends another package, it inherits all the classes and
interfaces from the parent package.

Here's an example of extending packages in Java:

package com.example.animals;

interface Animal {
public void makeSound();
}

interface Mammal extends Animal {


public void giveBirth();
}

public class Main {


public static void main(String[] args) {
Mammal mammal = new Cat();
mammal.makeSound(); // Output: Meow
mammal.giveBirth(); // Output: Giving birth to kittens
}
}

In this example, the com.example.animals package contains the Animal, Mammal, and
Main classes. If you have another package called com.example.zoo that needs to use the
Animal and Mammal interfaces, you can extend the com.example.animals package using
the import statement.

package com.example.zoo;

import com.example.animals.*;

class Zoo {

public static void main(String[] args) {

Mammal mammal = new Cat();

mammal.makeSound(); // Output: Meow


mammal.giveBirth(); // Output: Giving birth to kittens

In this example, the Zoo class in the com.example.zoo package imports the Animal,
Mammal , and Cat classes from the com.example.animals package using the import
statement. This allows the Zoo class to use the functionality provided by the Animal,
Mammal , and Cat classes without having to redefine them in the com.example.zoo
package.

Package and Classes Visibility

In Java, visibility is an important concept that determines which classes and


members of a class can be accessed from other classes. There are four levels of
visibility in Java: public, protected, default (package-private), and private.

Public: Public members and classes are visible to all classes in all packages.

Example:

package com.example;

public class MyClass {

public int myPublicVar;

public void myPublicMethod() {

// code here

In this example, the MyClass class has a public variable myPublicVar and a public
method myPublicMethod(). These members can be accessed from any class in any
package.

Protected: Protected members and classes are visible to all classes within the same
package as well as any subclasses (even if they are in a different package).

Example:
package com.example;

public class MyClass {

protected int myProtectedVar;

protected void myProtectedMethod() {

// code here

In this example, the MyClass class has a protected variable myProtectedVar and a
protected method myProtectedMethod(). These members can be accessed from any
class within the same package and any subclass (even if they are in a different
package).

Default (Package-private): Members and classes with default (package-private)


visibility are only visible to other classes within the same package.

Example:

package com.example;

class MyClass {

int myDefaultVar;

void myDefaultMethod() {

// code here

In this example, the MyClass class has a default (package-private) variable


myDefaultVar and a default (package-private) method myDefaultMethod(). These
members can be accessed from any class within the same package but not from
classes in other packages.

Private: Members and classes with private visibility are only visible to the same
class.
Example:

package com.example;

public class MyClass {

private int myPrivateVar;

private void myPrivateMethod() {

// code here

In this example, the MyClass class has a private variable myPrivateVar and a
private method myPrivateMethod(). These members can only be accessed from
within the MyClass class itself.

Standard JAVA Packages

Java comes with a set of standard packages that provide commonly used
functionality. These packages include java.util, java.lang, java.io, and
java.net.

java.util: This package provides a collection of utility classes, such as the


Scanner class for parsing text input, Random class for generating random
numbers, and ArrayList class for managing dynamic arrays.

Example:

import java.util.Scanner;

public class MyClass {

public static void main(String[] args) {


Scanner input = new Scanner(System.in);

System.out.print("Enter your name: ");

String name = input.nextLine();

System.out.println("Hello, " + name + "!");

java.lang: This package provides fundamental classes and interfaces that


are automatically imported in all Java programs. This includes the Object
class, which is the root of the class hierarchy, and the String class, which is
used to represent text strings.

Example:

public class MyClass {

public static void main(String[] args) {

Object obj = new Object();

String greeting = "Hello, world!";

System.out.println(greeting);

java.io:This package provides classes for input and output operations,


such as reading and writing files, and working with streams.

Example:

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;
public class MyClass {

public static void main(String[] args) {

try {

File myFile = new File("input.txt");

Scanner input = new Scanner(myFile);

while (input.hasNextLine()) {

System.out.println(input.nextLine());

input.close();

} catch (FileNotFoundException e) {

System.out.println("File not found!");

e.printStackTrace();

java.net:This package provides classes for networking operations, such as


connecting to remote servers, sending and receiving data, and working with
URLs.

Example:

import java.net.URL;

import java.net.URLConnection;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class MyClass {

public static void main(String[] args) {

try {

URL url = new URL("http://www.example.com");

URLConnection conn = url.openConnection();

BufferedReader input = new BufferedReader(new


InputStreamReader(conn.getInputStream()));

String line;

while ((line = input.readLine()) != null) {

System.out.println(line);

input.close();

} catch (Exception e) {

System.out.println("Error: " + e.getMessage());

These standard packages are extensively used in Java programming to


achieve various functionalities, and it is recommended to have a good
understanding of these packages to become a proficient Java developer.

Wrapper Class

In Java, a wrapper class is a class that provides an object representation of a


primitive data type. The wrapper classes are part of the java.lang package
and they provide a way to convert primitive data types into objects and vice
versa. The eight primitive data types in Java are boolean, byte, char, short,
int, long, float, and double.

Wrapper classes provide methods to perform various operations on the


corresponding primitive data type. For example, the Integer class provides
methods to convert an integer to a string, to compare two integers, and to
perform arithmetic operations.

The wrapper classes are:

 Boolean: Represents a boolean value as an object.


 Byte: Represents a byte value as an object.
 Character: Represents a character value as an object.
 Short: Represents a short value as an object.
 Integer: Represents an integer value as an object.
 Long: Represents a long value as an object.
 Float: Represents a float value as an object.
 Double: Represents a double value as an object.

For example, to convert a primitive int to an Integer object, you can use
the valueOf() method:

int num = 42;


Integer obj = Integer.valueOf(num););

And to convert an Integer object back to an int, you can use the
intValue() method:

Integer obj = Integer.valueOf(42);

int num = obj.intValue();

Wrapper classes are often used in situations where you need to store
primitive values in a collection or pass them as arguments to methods that
require objects. Additionally, wrapper classes can be useful when you need
to perform operations on primitive values using methods that are only
available for objects, such as sorting or searching a collection of values.
Overall, wrapper classes provide a convenient way to work with primitive
data types as objects in Java.

Auto Boxin and Unboxing

Autoboxing and unboxing are features in Java that allow automatic


conversion between primitive data types and their corresponding wrapper
classes.

Autoboxing is the process of automatically converting a primitive data type


into its corresponding wrapper class object. For example, when an int value
is assigned to an Integer reference, autoboxing converts the int value to an
Integer object.

Here's an example of autoboxing:

int num = 42;

Integer obj = num; // autoboxing

Unboxing is the opposite of autoboxing, where a wrapper class object is


automatically converted back to its corresponding primitive data type. For
example, when an Integer object is assigned to an int variable, unboxing
converts the Integer object to an int value.

Here's an example of unboxing:

Integer obj = Integer.valueOf(42);

int num = obj; // unboxing

Autoboxing and unboxing are convenient features in Java that make code
more readable and easier to write. They allow you to treat primitive values
and their corresponding wrapper class objects interchangeably in most
situations. However, it's important to be aware of the performance
implications of autoboxing and unboxing, as the automatic conversions can
create unnecessary objects and lead to increased memory usage and
decreased performance.
Enumeration
Enumerations, or enums for short, are a special type of class in Java that represent a fixed set
of constants. Enums were introduced in Java 5 and are defined using the enum keyword.

An enum can contain a list of named constants, which are defined as public, static, and final
fields within the enum class. Each constant is typically written in uppercase letters, and they
are separated by commas.

Here's an example of an enum:

public enum Day {


MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY,
SUNDAY
}, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }

You can also add additional data and methods to an enum. For example, you could define an
enum for the months of the year and include a method to return the number of days in each
month:

public enum Month {

JANUARY(31),

FEBRUARY(28),

MARCH(31),

APRIL(30),

MAY(31),

JUNE(30),

JULY(31),

AUGUST(31),

SEPTEMBER(30),

OCTOBER(31),

NOVEMBER(30),

DECEMBER(31);
private final int days;

private Month(int days) {

this.days = days;

public int getDays() {

return days;

Enums are useful for representing fixed sets of constants that are related to each other. They
can help make code more readable and maintainable by providing a concise and self-
documenting way to represent a set of values. Additionally, enums can be used in switch
statements, and they can also be used as the type of a variable or parameter.

Metadata

Metadata, also known as annotations, are a powerful feature in Java that


allow you to add additional information to your code. Metadata can be
used to provide information about classes, methods, fields, parameters, and
more.

Annotations are defined using the @ symbol followed by the name of the
annotation, and they can be added to a declaration in one of two ways:
either directly preceding the declaration, or within the declaration using the
element-value pair syntax.

Here's an example of an annotation that marks a method as deprecated:

@Deprecated

public void oldMethod() {

// method implementation
}

You can also define your own custom annotations. Custom annotations can
be used to mark classes, methods, or other elements in your code with
additional information that can be processed by tools or frameworks.

Here's an example of a custom annotation that marks a method as


requiring authentication:

public @interface RequiresAuth {

String[] roles() default {"user"};

Annotations can be accessed at runtime using Java's Reflection API.


Reflection allows you to inspect and modify the metadata associated with a
class or object, including its annotations.

Metadata is a powerful feature in Java that allows you to add additional


information to your code that can be used by tools, frameworks, and other
programs. By using annotations effectively, you can make your code more
self-documenting, more flexible, and more powerful.

You might also like