Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Unit 2 Java

Inheritance in Java allows a subclass to reuse code from a superclass, promoting code reusability, reduced duplication, and improved maintainability. There are different types of inheritance, including single, multilevel, and hierarchical inheritance, with examples provided for each. The document also covers abstract classes, dynamic method dispatch, packages, Java bytecode, and access specifiers, explaining their significance and usage in Java programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Unit 2 Java

Inheritance in Java allows a subclass to reuse code from a superclass, promoting code reusability, reduced duplication, and improved maintainability. There are different types of inheritance, including single, multilevel, and hierarchical inheritance, with examples provided for each. The document also covers abstract classes, dynamic method dispatch, packages, Java bytecode, and access specifiers, explaining their significance and usage in Java programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Unit – 2

1. What is Inheritance? Its advantages? Explain with suitable example


Inheritance is a mechanism in Java that allows a class to reuse the code and behavior of another class. The class that
inherits the code and behavior is called the subclass or child class, and the class that provides the code and behavior is
called the superclass or parent class.

SYNTAX OF JAVA INHERITANCE


class Subclass-name extends Superclass-name
{
//methods and fields
}

TYPES OF INHERITANCE IN JAVA:


1. Single inheritance : This is the most common type of inheritance, where a subclass inherits from a single superclass.
2. Multilevel inheritance: This is a type of inheritance where a subclass inherits from a superclass, which in turn inherits
from another superclass, and so on.
3. Hierarchical inheritance: This is a type of inheritance where a superclass has multiple subclasses.
4. Multiple inheritance(java does not support )
5. Hybrid inheritance: This is a combination of multiple inheritance and hierarchical inheritance.

Advantages:
Code reusability:
Inheritance allows programmers to reuse code that has already been written and tested. This can save time and effort,
and it can also help to reduce errors.
Reduced code duplication:
Inheritance can help to reduce code duplication by allowing programmers to inherit common properties and methods
from a base class. This can make code more organized and easier to maintain.
Improved maintainability:
Inheritance can make code more maintainable by allowing programmers to make changes to a base class without having
to make changes to all of the derived classes.
Extensibility:
Inheritance allows programmers to extend the functionality of existing classes by creating new derived classes. This can
be useful for adding new features or for adapting existing classes to new requirements.

Example:
// Superclass
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

// Subclass inheriting from Animal


class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}

// Subclass inheriting from Dog


class Puppy extends Dog {
void play() {
System.out.println("Puppy plays");
}
}

public class Main {


public static void main(String[] args) {
// Single Inheritance Example
Dog dog = new Dog();
dog.sound(); // Inherited from Animal class
dog.bark(); // Method defined in Dog class

System.out.println();

// Multilevel Inheritance Example


Puppy puppy = new Puppy();
puppy.sound(); // Inherited from Animal class
puppy.bark(); // Inherited from Dog class
puppy.play(); // Method defined in Puppy class
}
}

Explanation:
 The Animal class is the superclass with a method sound().
 The Dog class is a subclass of Animal, inheriting the sound() method and adding a new method bark().
 The Puppy class is a subclass of Dog, inheriting both the sound() and bark() methods and adding a new method
play().
 In the main method, we demonstrate both single and multilevel inheritance by creating objects of Dog and
Puppy classes and invoking methods from their superclass and subclass.

2. Write a sample program to implement multilevel hierarchy.


Program:
class Animal {
void eat() {
System.out.println("eating...");
}
}

class Dog extends Animal {


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

class BabyDog extends Dog {


void weep() {
System.out.println("weeping...");
}
}

public class Main {


public static void main(String[] args) {
BabyDog babyDog = new BabyDog();
babyDog.eat();
babyDog.bark();
babyDog.weep();
}
}
Output:
eating...
barking...
weeping...

3. Explain about super keyword with suitable example.


The super keyword in Java is used to refer to the parent class of the current class. It can be used to access the parent
class's variables and methods, and to call the parent class's constructor.

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

class Dog extends Animal {


@Override
void eat() {
System.out.println("Dog is eating");
super.eat(); // This calls the parent class's eat() method
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // This calls the Dog class's eat() method, which in turn calls the Animal class's eat() method
}
}

Output:
Dog is eating
Animal is eating

In this example, the Dog class overrides the Animal class's eat() method. However, the Dog class still wants to call the
Animal class's eat() method, so it uses the super keyword.

4. Compare and contrast method overloading and method overriding?


5. Define interface? How to implement two interface from one class.

6. Explain about abstract classes with suitable examples


An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes
cannot be instantiated, but they can be subclassed.

Example:
abstract class Animal {
public abstract void animalSound();
public void sleep() {
System.out.println("Zzz");
}
}

class Pig extends Animal {


public void animalSound() {
System.out.println("The pig says: wee wee");
}
}
In this example, the Animal class is abstract because it includes the abstract method animalSound(). The Pig class is a
subclass of Animal and provides an implementation for the animalSound() method.

Benefits of using abstract classes:


Code reusability:
Abstract classes can help you to reuse code. For example, the sleep() method in the Animal class can be reused by all of
its subclasses.
Code organization:
Abstract classes can help you to organize your code. For example, you can create an abstract class for each type of entity
in system.
Information hiding:
Abstract classes can help you to hide implementation details from the user. For example, the Database class hides the
details of how to connect to a database from the user.

7. Explain about Dynamic method Dispatch with example program.


Dynamic method dispatch is a feature of Java that allows the compiler to resolve method calls at runtime, based on the
actual type of the object being called. This is in contrast to static method dispatch, which resolves method calls at
compile time, based on the declared type of the object being called.

Example:
// Superclass
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

// Subclass 1
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}

// Subclass 2
class Cat extends Animal {
void sound() {
System.out.println("Cat meows");
}
}

public class Main {


public static void main(String[] args) {
// Creating objects of subclasses
Animal animal1 = new Dog();
Animal animal2 = new Cat();

// Calling the sound method


animal1.sound(); // Dynamic method dispatch: calls Dog's sound method
animal2.sound(); // Dynamic method dispatch: calls Cat's sound method
}
}

In this example:
 The Animal class defines a method sound().
 The Dog and Cat classes are subclasses of Animal, and they override the sound() method with their own
implementations.
 In the main method, we create objects of type Animal but assign them references to Dog and Cat objects.
 When we call the sound() method on these objects, the method implementation invoked is determined by the
actual type of the object (Dog or Cat) rather than the reference type (Animal). This is dynamic method dispatch
in action.
8. Define package? How to create package with example program.
 A Package is nothing but a directory that contain classes and interfaces.
 Packages act as “Container” for classes.

PACKAGE CREATION :
To create a package simply include a package command as the first statement in a Java source file.

Syntax: package packagename;

The package name must be the same as the directory name. For example, if you create a package
named com.example.myapp, you would create a directory named com/example/myapp and then create Java source
files in that directory.

STEPS TO CREATION OF PACKAGE:


1. Declare the package at the beginning of a file using the form “package packagename;”
2. Define the classes
3. Crete the subdirectory under the main directory with package name.
4. Store the program with .java extension in main directory.
5. Compile the file.

COMPILE AND EXICUTE PACKAGE


Compilation: javac filename.java
Execution: java filename

Example:
package com.example.myapp;

public class MyClass {

public static void main(String[] args) {


System.out.println("Hello, world!");
}
}

-> Explain briefly about java magic code (byte code).

Java bytecode is an intermediate representation of Java programs that is executed by the Java Virtual Machine (JVM). It
is platform-independent, meaning that the same Java program can run on different devices and operating systems.

When you compile a Java program, the Java compiler converts your source code into bytecode. This bytecode is then
read and processed by a JVM running on a target system. The JVM interprets the bytecode and executes the instructions
it contains.

Java bytecode is a set of instructions that the JVM can understand and execute. These instructions are typically
represented by one or more bytes, hence the name "bytecode".
Bytecode is a compact form of instruction, which makes it efficient to store and transmit. It is also platform-independent,
which means that the same bytecode can be executed on any platform that has a JVM.

The Java Virtual Machine (JVM) is a software program that executes Java bytecode. The JVM is responsible for loading
bytecode into memory, interpreting it, and executing the instructions it contains.

The JVM is also responsible for managing memory and garbage collection. Garbage collection is the process of
automatically reclaiming memory that is no longer being used by Java objects.

The JVM is a key part of the Java platform. It allows Java programs to be executed on a variety of different platforms,
without having to be recompiled for each platform.

->Different types of access specifiers.


In Java, access specifiers (also known as access modifiers) are keywords used to control the visibility and accessibility of
classes, methods, and variables. There are four types of access specifiers:

public:
 Public members are accessible from any other class or package.
 There is no restriction on access.
Example:
public class MyClass {
public int publicVariable;
public void publicMethod() {
// Method implementation
}
}

protected:
Protected members are accessible within the same package and by subclasses (even if they are in different packages).
Example:
class MyClass {
protected int protectedVariable;
protected void protectedMethod() {
// Method implementation
}
}

default (no modifier):


 Members with no explicit access specifier (default access) are accessible only within the same package.
 If no access specifier is specified, the member is considered to have default access.
Example:
class MyClass {
int defaultVariable; // Default access
void defaultMethod() { // Default access
// Method implementation
}
}

private:
 Private members are accessible only within the same class.
 They cannot be accessed from outside the class, not even from subclasses.
Example:
class MyClass {
private int privateVariable;
private void privateMethod() {
// Method implementation
}
}

Access specifiers are essential for encapsulation, allowing you to control the visibility of your classes, methods, and
variables. By choosing the appropriate access specifier, you can enforce encapsulation and ensure proper data hiding
and access control in your Java programs.

You might also like