Java_Chapter _2
Java_Chapter _2
What is Inheritance?
Inheritance is the mechanism of deriving one class from already define class
The subclass inherits the properties (member variables and member method ) of
superclass.
Single Inheritance: A single class inherits from only one superclass is called as single
inheritance
Parent Class
Child Class
Syntax
class Parent
{
____
____
}
class Child extends Parent
{
____
____
}
For eg .
class Add1
{
int a=10,b=20,c;
void add()
{
c=a+b;
System.out.println("Addition="+c);
}
}
class SubData extends Add1
{
void sub()
{
System.out.println("Sub="+(b-a));
}
}
class Demo
{
public static void main(String args[])
{
SubData a1=new SubData();
a1.add();
a1.sub();
}
}
Multilevel Inheritance: A class inherits from a superclass, which in turn inherits from
another superclass, forming a hierarchy.
Parent Class
Child Class 1
Child Class 2
Syntax
class Parent
{
____
____
}
class Child1 extends Parent
{
____
____
}
class Child2 extends Child1
{
____
____
}
For Eg
class Grandfather
{
String s1 = "String of Grandfather";
}
class Father extends Grandfather
{
String s2 = "String of Father";
}
class Child extends Father
{
String s3= "String of Child";
void show()
{
System.out.println(“s1= “+s1+”s2 = ”+s2+”s3= “+s3);
}
}
class Demo
{
public static void main(String args[])
{
Child a1=new Child();
a1.show();
}
}
1. Hierarchical Inheritance: Multiple classes inherit from the same superclass is called
as hierarchical inheritance
Important Notes
• Java does not support multiple inheritance (a class inheriting from multiple classes)
through classes. This is to avoid the "diamond problem" (ambiguity in inherited
members).
Benefits of Inheritance
• Code Reusability: Common code can be placed in the superclass and reused by
subclasses.
Method overloading
Method overloading in Java is a powerful feature that allows programmer to define multiple
methods within the same class that have the same name but different parameters. The
compiler distinguishes between these methods based on the number, types, or order of
their parameters.
• Flexibility: It provides flexibility in how you call a method, allowing you to pass
different types or numbers of arguments.
1. Same Method Name: The methods must have the same name.
2. Different Parameter Lists: The methods must differ in at least one of the following:
o Order of parameters: A method that takes an int and then a float is different
from a method that takes a float and then an int.
3. Return Type is Not a Factor: The return type of the method does not play a role in
method overloading so it doesn’t matter what type of value is method returning.
Two methods can have the same name, different parameter lists and different return
types or same return type, and this is perfectly valid overloading.
Example
class Calculator
{
// Method 1: Adds two integers
int add(int a, int b)
{
System.out.println(“Addition =” +( a + b)); //a=2,b=3 so (2+3=5)
}
// Method 2: Adds three integers
int add(int a, int b, int c)
{
System.out.println(“Addition =” +( a+b+c)); //a=2,b=3 ,c=4 so
(2+3+4=9)
}
public static void main(String args[])
{
Calculator calc = new Calculator();
• The compiler determines which add method to call based on the arguments you
provide in the main method.
• calc.add(2, 3) calls the first add method because it matches the signature (int, int).
• calc.add(2, 3, 4) calls the second add method because it matches (int, int, int).
Important Note: If you try to call an overloaded method and the compiler cannot find
a unique match, you will get a compile-time error. This is called "ambiguous method call."
Method Overriding
Method overriding in Java allows a subclass (child class) to provide a specific implementation
for a method that is already defined in its superclass (parent class). This lets the subclass
customize the behavior of the inherited method to suit its own needs.
Method overriding is essential for achieving polymorphism (the ability of an object to take
on many forms with same name)
Subclasses need to perform method that are similar to their superclass method but with
some modifications. Overriding keep the same method name and same parameter list (for
consistency) but change the implementation(different body).
1. Same Method Signature: The overriding method in the subclass must have the same
name, same parameter list (number and types of parameters) as the method in the
superclass. The method signature must be identical(same).
o If the superclass method is public, the subclass method must also be public.
class Flower
void color()
System.out.println("Pink");
void color()
System.out.println("Red");
class MainDemo
r.color() // Output:Pink
s.color() // Output:Red
The super keyword is used to invoke the super class constructor from subclass constructor. It
is used if super class has a parameterized constructor. It can be used only from the subclass
constructor and it has to be the first instruction in the subclass constructor.
Accessing Superclass Members: The super is same as this except that it always refers to the
superclass of the subclass in which it is used. It has following format
super.member
for eg.
class Flower
{
void color()
{
System.out.println("Pink");
}
}
class Rose extends Flower
{
void color()
{
super.color();
System.out.println("Red");
}
}
class MainDemo
{
public static void main(String args[])
{
Rose s=new Rose();
s.color() // Output:Red
}
}
final
In Java, the final keyword is a powerful modifier that can be applied to variables, methods,
and classes. It has different meanings and effects depending on where it's used for eg-final
variable , final method or final class
1. final Variable
A final variable's value cannot be changed after it has been initialized. It's essentially a
constant i.e final variable store fixed value .
Declaration :
You must initialize a final variable. You can do it at the time of declaration only once.
final variables are often used for constants (values that should not change throughout
the program). By convention, constant names are often written in uppercase with
underscores (e.g., MAX_VALUE, PI).
2. final Method
How to Declare:
class Parent
final methods are used when you want to ensure that the behavior of a method remains
consistent and is not modified by subclasses.
3. final Class
A final class cannot be subclassed (inherited from). This prevents other classes from
extending the final class.
How to Declare:
final classes are used when you want to create a class that is immutable (its state cannot be
changed after creation) or when you want to prevent others from creating subclasses that is
preventing inheritance.
All methods in a final class are implicitly final (you don't need to explicitly declare them
as final).
Abstract Method
An abstract method is a method that is declared without an implementation (no method
body). It essentially acts as a placeholder specifying that subclasses(child class) must provide
a concrete implementation for that method.
How to Declare:
Note:
o Abstract methods can only exist within abstract classes (explained below).
o They do not have a body (no curly braces {}). The declaration ends with a
semicolon.
o Subclasses that inherit from the abstract class must override all the abstract
methods and provide concrete implementations. If a subclass doesn't provide
an implementation, it must also be declared as abstract.
Abstract Class
An abstract class is a class that cannot be instantiated directly(We can not create object for
abstract class). It can contain both abstract methods (which must be implemented by
subclasses) and concrete methods (which have body).
• How to Declare:
• Note:
o Abstract classes can have both abstract methods and concrete (non-abstract)
methods.
o If a class has even one abstract method, the class itself must be declared as
abstract.
Interface
Interface is also known as kind of class so it also contain methods and variables but with
major difference of only abstract method and final variable i.e method do not specify any
code and the data variables are constant hence it is the child class responsibility to
implement code for abstract method.
Method declaration contains only list of methods without any body statement and ends with
semicolon. The methods are, essentially, abstract methods; there can be no default
implementation of any method specified within an interface. Each class that includes an
interface must implement all of the methods.
Following example is of interface definition, which contains two variables and one method.
interface student
The code for implementation of the method is not provided in the interface. The method
declaration terminated with semicolon. Now this is the responsibility of the class that
implements this interface to define the code for the method.
Extending Interfaces
Interface can be extended like classes. That is, an interface can be subinterfaced from other
interfaces. The newly subinterface can inherit all the members of superinterface is the
manner like subclasses. The extend keyword is used. The syntax is:
interface Name
{
body of SubName2;
Implementing Interfaces
Once an interface has been defined, one or more classes can implement that interface.
Interfaces are used as "superclass" whose properties are inherited by classes. So create a
class that inherits the interface. To implement an interface, include the implements clause in
a class definition and then override the methods defined by the interface.
body of ClassName;
Here,
(iii) If a class implements more than one interface, then interfaces must be separated with
commas.
body of ClassName;
For eg
interface Area
{ // interface defined
float pi = 3.14F;
return (x * y);
class Demo
System.out.println(r1.compute(1.2f,3.2f));
Package
Reusability can be achieved through inheritance and interfaces by extending the classes and
implementing the interfaces. But this is limited to reusing the classes within a program.
Suppose, if we want to use the classes from other programs without actually copying them
into program then this can be achieved in Java by using packages which is very similar to
class libraries in other libraries. Another way of achieving the reusability concept in Java is
packages.
Packages are used for grouping a variety of classes and interfaces together. This grouping is
done according to the functionality. Packages are acts as "containers" for classes that are
used to keep the class name space compartmentalized. Packages are stored in hierarchical
manner and are explicitly imported into new class definitions.
}
}
System.out.println("Enter number1");
int num1=sc.nextInt();
System.out.println("Enter number2");
int num2=sc.nextInt();
System.out.println("Addition = "+result);
java AddDemo