Module 2
Module 2
Consider three classes, class Vehicle, class Car, and class SUV. Here, the class Vehicle is
the grandfather class. The class Car extends class Vehicle and the class SUV extends class
Car.
Consider three classes – Car, Maruti and Maruti800. We have done a setup – class Maruti
extends Car and class Maruti800 extends Maruti. With the help of this Multilevel hierarchy
setup our Maruti800 class is able to use the methods of both the classes (Car and Maruti).
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...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat(); } }
Hierarchical Inheritance
When two or more classes are inherited from a single class, it is known as hierarchical
inheritance
class Animal{ class TestInheritance3{
void eat(){System.out.println("eating...");} public static void main(String args[]){
} Cat c=new Cat();
class Dog extends Animal{ c.meow();
void bark(){System.out.println("barking...");} c.eat();
//c.bark();//C.T.Error
}
}
class Cat extends Animal{ }
void meow(){System.out.println("meowing...");} Output:
}
meowing...
eating...
Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
Since compile-time errors are better than runtime errors, Java renders compile-time
error if you inherit 2 classes. So whether you have same method or different, there will
be compile time error.
Using Super
Used to
1.Access the members of the superclass from within the subclass:
2.Invoke the superclass constructor from within the subclass constructor.
3.Resolve ambiguity between a field or method in the subclass and a field or method in the
superclass.
4.Access the static members of the superclass from within the subclass.
// Parent class
class School
{
// Instance variables
int id;
String name = "SSM Public School";
}
class Teacher extends School
{
// Instance variable in the child class
int id;
String name;
void printSchoolName() {
// Using super.name, we can access the name variable of the parent class
// Using this.name, we can access the name variable of the child class
System.out.println("School Name: " + super.name);
}
public static void main(String[] args) {
Teacher ob = new Teacher();
ob.printSchoolName();
}
}
When constructors are called,
Constructor is a block of code that initializes the newly created object.
A constructor resembles an instance method in java but it’s not a method as it doesn’t have a
return type.
In short constructor and method are different.
People often refer constructor as special type of method in Java.
Constructor has same name as the class and looks like this in a java code.
There are two types of constructors in Java:
1.Default constructor (no-arg constructor)
2.Parameterized constructor
Syntax:
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1(); } } Bike is created
Example:
/Java Program to demonstrate the use of the parameterized constructor.
class Student4{
int id; public static void main(String args[]){
String name; //creating objects and passing values
//creating a parameterized constructor Student4 s1 = new Student4(111,"Karan");
Student4(int i,String n){ Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
id = i;
s1.display();
name = n; s2.display();
} }
//method to display the values }
void display()
{
System.out.println(id+" "+name);
}
Constructor Overloading in Java
Constructor overloading in Java is a technique of having more than one constructor with different
parameter lists.
They are differentiated by the compiler by the number of parameters in the list and their types.
//Java program to overload constructors
class Student5{ void display()
int id; {
String name; System.out.println(id+" "+name+" "+age);
int age; }
//creating two arg constructor
Student5(int i,String n){ public static void main(String args[]){
id = i; Student5 s1 = new Student5(111,"Karan");
name = n; Student5 s2 = new Student5(222,"Aryan",25);
} s1.display();
Student5(int i,String n,int a){ s2.display();
}
id = i; name = n; age=a; }
}
Method Overriding
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
Method overriding is used for runtime polymorphism
2.method
3.class
If you make any variable as final, you cannot change the value
of final variable(It will be constant).
Eg: class Bike{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike obj=new Bike();
obj.run(); } }
If you make any method as final, you cannot override it.
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda honda= new Honda();
honda.run();
} } Output: Compile Time Error
If you make any class as final, you cannot extend it.
final class Bike{}
Example, there is getObject() method that returns an object but it can be of any type like
Employee,Student etc, we can use Object class reference to refer that object. For example:
Object obj=getObject();//we don't know what object will be returned
The Object class provides some common behaviors to all the objects such as object can be
compared, object can be cloned, object can be notified etc.
Cloning
The object cloning is a way to create exact copy of an object.
The clone() method of Object class is used to clone an object.
The java.lang.Cloneable interface must be implemented by the class whose object
clone we want to create.
If we don't implement Cloneable interface, clone() method
generates CloneNotSupportedException.
The clone() method is defined in the Object class.
Syntax of the clone() method is as follows:
protected Object clone() throws CloneNotSupportedException
class Student18 implements Cloneable{ Student18 s2=(Student18)s1.clone();
int rollno; System.out.println(s1.rollno+" "+s1.name);
String name; System.out.println(s2.rollno+" "+s2.name);
Student18(int rollno,String name) }
{ catch(CloneNotSupportedException c)
{
this.rollno=rollno;
}
this.name=name; }
} }
public Object clone()throws CloneNotSupportedException
{
return super.clone(); Output:
101 amit
}
101 amit
public static void main(String args[]){
try
{ Student18 s1=new Student18(101,"amit");
Packages .
Defining a package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form,
built-in package and
user-defined package.
The -d switch specifies the destination where to put the generated class file.
You can use any directory name like d:/abc (in case of windows).
If you want to keep the package within the same directory, you can use . (dot).
Finding packages and CLASSPATH,
Java packages are mirrored by directories.
Java run-time system looks for packages from three parts.
Current folder
First, the Java run-time system uses the current working directory as its
starting point.
If your package is in a subdirectory of the current directory, it will be found.
CLASSPATH
Second, you can specify a directory path or paths by setting
the CLASSPATH environmental variable.
-classpath
Third, you can use the -classpath option with java and javac to specify the
path to your classes.
package example
// A simple package
package MyPack;
class MyClass
{
void me()
{ System.out.println("hi from package"); }
}
class Main
{ public static void main(String args[])
{
MyClass c = new MyClass();
c.me();
}
}
In order for a program to find MyPack, one of three things must be true.
Either the program can be executed from a directory immediately
above MyPack, or the CLASSPATH must be set to include the path to MyPack,
or the -classpath option must specify the path to MyPack when the program is
run via java.
When the second two options are used, the class path must not include MyPack,
itself.
It must simply specify the path to MyPack.
For example, in a Windows environment, if the path to MyPack is
C:\MyPrograms\Java\MyPack
different packages.
The accessibility of the members of a class or interface depends on its access
specifiers.
The following table provides information about the visibility of both data members
and methods.
Nested Interfaces
An interface declared within another interface or class, is known as a nested interface.
The nested interfaces are used to group related interfaces so that they can be easy to maintain.
The nested interface must be referred to by the outer interface or class.
It can't be accessed directly.
interface Showable{
void show();
interface Message{
void msg();
}
}
class TestNestedInterface1 implements Showable.Message
{ public void msg() { System.out.println("Hello nested interface"); }
public static void main(String args[])
{
Showable.Message message=new TestNestedInterface1();//upcasting here
message.msg();
} }
Variables in interface
In Java, an interface variable is implicitly public, static, and final.
This means that the variable's value cannot be changed once it is assigned.
Furthermore, interface variables are accessible to all implementing classes,
promoting code reusability and standardization.
public interface Constants {
String DATABASE_URL = "jdbc:mysql://localhost:3306/mydatabase";
String USERNAME = "root";
String PASSWORD = "password123";
}
public class DatabaseConnection {
// Code for establishing a database connection using the constants
}
public interface Currency { public class Main
String SYMBOL = "$"; {
double convertToUSD(double amount);
public static void main(String[] args)
}
public class Dollar implements Currency { {
public double convertToUSD(double amount) { Currency dollar = new Dollar();
return amount; Currency euro = new Euro();
}
}
double amount = 100;
public class Euro implements Currency {
public double convertToUSD(double amount) { System.out.println("Amount in dollars: " +
return amount * 1.18;
} dollar.convertToUSD(amount) + SYMBOL);
}
System.out.println("Amount in euros: " +
euro.convertToUSD(amount) + SYMBOL);
}