Java Prograaming - Notes (Unit-3)
Java Prograaming - Notes (Unit-3)
In the above example, the Dog class is created by inheriting the methods and fields from the Animal
class.
1
There are five types of inheritance.
2
3
4
//Single
class A {
int a, b;
void display()
{ SOP(“Inside class A values =”+a+” ”+b); }
}
class B extends A
{
int c;
void show()
{ SOP(“Inside Class B values=”+a+” “+b+” “+c);}
}
class SingleInheritance {
public static void main(String args[]) {
B obj = new B();
obj.a=10;
obj.b=20;
obj.c=30;
[Link]();
[Link]();
}}
//MultiLevel Output:
class Electronics { Class Electronics
public Electronics() Class Grinder
{ SOP("Class Electronics"); } Class WetGrinder
public void deviceType() Device Type: Electronics
{ SOP("Device Type: Electronics"); } Category: Grinder
} Grinding Technology: WetGrinder
class Grinder extends Electronics {
public Grinder()
{ SOP("Class Grinder"); }
public void category()
{ SOP("Category - Grinder"); }
}
class WetGrinder extends Grinder {
public WetGrinder()
{ SOP("Class WetGrinder"); }
public void grinding_tech()
{ SOP("Grinding Technology- WetGrinder"); }
}
public class Tester {
public static void main(String[] arguments) {
WetGrinder wt= new WetGrinder();
[Link]();
[Link]();
wt.grinding_tech(); }
}
5
6
//Hybrid Output:
public class ClassH1 { disp() method of ClassH2
public void dispH1() disp() method of ClassH1
{ SOP("disp() method of ClassH1"); } disp() method of ClassH3
} disp() method of ClassH1
public class ClassH2 extends ClassH1 { disp() method of ClassH4
public void dispH2() disp() method of ClassH1
{ SOP("disp() method of ClassH2"); }
}
public class ClassH3 extends ClassH1{
public void dispH3()
{ SOP("disp() method of ClassH3"); }
}
public class ClassH4 extends ClassH1{
public void dispH4()
{ SOP("disp() method of ClassH4"); }
}
public class HierarchicalInheritanceTest {
public static void main(String args[]) {
ClassH2 h2 = new ClassH2();
h2.dispH2();
h2.dispH1();
ClassH3 h3 = new ClassH3();
h3.dispH3();
h3.dispH1();
ClassH4 h4 = new ClassH4();
h4.dispH4();
h4.dispH1();
}
}
● The method name should be common and the same as it is in the parent class.
● The method signature (parameter list, return type) in the method must be the same as in the parent
class.
● All the abstract methods in the parent class should be overridden in the child class.
● If it declared the methods as static or final, then those methods cannot be overridden.
9
3. CONSTRUCTOR OVERLOADING & OVERRIDING
Constructor overloading is similar to method overloading, which allows multiple
methods with the same name but different parameters to be defined in a class.
Constructor overloading is a technique that allows multiple constructors with different
parameter lists to be defined in a class.
Constructor overloading is achieved by creating constructors with different
parameter lists. The parameter lists can differ in the number of parameters, their types, and
their order. When an object is created, the constructor with the appropriate parameter list is
called to initialize the object.
Constructor Overriding
Super-class constructors cannot be overridden as the constructors have the same name as
their class.
To be able to access a constructor in a sub-class with the same number and data type of
arguments as in the super-class, it must be defined in the sub-class itself.
When constructors are defined in a sub-class, the corresponding super-class constructors
are called during the creation of objects of that sub-class.
Generally, super-class methods are called using the following syntax:
[Link]( arguments-list)
Specific rules for the use of keyword super()
1. The first calling method must be super() in the constructor’s definition. If the super()
method is not specified, Java will implicitly call the super() method with no arguments.
2. Super() is used to call a constructor method with the appropriate arguments from the
immediate super-class. This may, in turn, call the constructor of its super-class and so on. The usage
of super() in the constructor is similar to the use of keyword this().
12
3. To use super() in the constructor of sub-class, a constructor with the same signature
must exist in the super-class.
import [Link].*; class sub class number 200 super
One { class number 100 num 100
int num;
One(int n) { [Link] = n; }
void show() { [Link] ("num" +num); }
}
class Two extends one { int
num1;
Two(int x, int y) { super(x); num1 = y;
} void show() {
[Link]("sub class number"+num1);
[Link]("super class number"+num); [Link]();
}
}
class SampleClass {
public static void main(String args[ ]) {
Two t = new Two(100,200); [Link]();
}
}
13
Method Overloading Method Overriding
In method overloading, methods must have the In method overriding, methods must have the same
same name and different signatures. name and same signature.
Static binding is being used for overloaded Dynamic binding is being used for overriding
methods. methods.
Argument list should be different while doing Argument list should be same in method overriding.
method overloading.
14
4. DYNAMIC METHOD DISPATCH
Mechanism in which a call to an overridden method is resolved at run time instead
of compile time. This is an important concept because of how Java implements run-time
polymorphism.
Java uses the principle of ‘a superclass reference variable can refer to a subclass
object’ to resolve calls to overridden methods at run time.
When an overridden method is called by a reference, java determines which version
of that method to execute based on the type of object it refer to.
In simple words the type of object which it referred determines which version of
overridden method will be called.
Upcasting
When Parent class reference variable refers to Child class object, it is known as
Upcasting.
this can be done and is helpful in scenarios where multiple child classes extends one
parent class. In those cases we can create a parent class reference and assign child class
objects to it.
15
5. FINAL VARIABLES & METHODS
The final keyword in java is one of the most useful keywords when it comes to implementing
security to a program.
It restricts the user from changing the values or contents declared as final. The final keyword can
be used with variables, methods and classes.
As the word-final suggests, we can finalize a certain entity using the final keyword. In
other words, anything declared final in the java program cannot be modified.
The final keyword restricts the access of the user to modify the data.
● A variable that is declared as a final variable is a constant throughout the
program and its value cannot be changed whatsoever.
● Method that is declared final cannot be overridden by any other subclasses.
● A class that is declared final cannot be inherited by any other class.
Final variables are constants that cannot be altered throughout the program. After the
initialization of the final variable, it is finalized and alteration is not possible. If we try to alter it,
we will get a compilation error.
We can declare a final variable and not initialize it; this type of final variable is known as a
blank final variable. We have to initialize the variable in a constructor; otherwise, it will give a
compilation error that the variable might not have been initialized.
16
Final method is a method that cannot be overridden. We can call a final method from a
subclass, but the subclass cannot override the final method of the parent class. If we try to do so, it
will give a compilation error.
The java final method increases security. A final method prevents the subclass from
overriding the definition of a method. If there is a method that contains a definition that should not
be altered by the extended classes, it should be declared final to prevent overriding; this increases
security while implementing the program.
(Final class) When there is a class that is a stand-alone and should not be inherited in any
circumstances, it should be declared final. A final class cannot be inherited whatsoever.
17
6. USE OF SUPER KEYWORD
The super keyword in Java is used in subclasses to access superclass members (attributes,
constructors and methods).
Uses of super keyword
●To call methods of the superclass that is overridden in the subclass.
If methods with the same name are defined in both superclass and subclass, the method in the
subclass overrides the method in the superclass. This is
called method overriding.
class Animal {
public void display() I am a dog
{ [Link]("I am an animal"); }
}
class Dog extends Animal {
public void display()
{ [Link]("I am a dog"); }
public void printMessage()
{ display(); }
}
class Override {
public static void main(String[] args) {
Dog dog1 = new Dog();
[Link]();
}
}
class Animal {
public void display(){ I am a dog
[Link]("I am an animal"); I am an animal
}
}
class Dog extends Animal {
public void display(){
[Link]("I am a dog");
}
public void printMessage(){
display();
[Link]();
}
}
class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
[Link]();
}
}
18
● To access attributes (fields) of the superclass if both superclass and
subclass have attributes with the same name.
class Animal {
Animal() { [Link]("I am an animal"); } I am an animal
} I am a dog
class Dog extends Animal {
Dog() { super();
[Link]("I am a dog"); }
}
class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
}
}
19
its abstract methods or be declared as abstract themselves.
20
abstract returnType methodName(parameterList); public
abstract void calculate(int x, int y);
Abstraction means hiding irrelevant details from the user. Abstraction helps us to
increase efficiency thereby reducing complexity. In java, we use abstract classes and
abstract methods to achieve abstraction.
21
abstract public void legs(); The details of Pigeon is:
abstract public void eyes(); Pigeons are intelligent animals.
} It has 2 legs. It
class Camel extends Animal { has 2 eyes.
Camel(String name) { super(name); }
public void legs() { [Link]("It has 4 legs."); } The details of Ant are: there
public void eyes() { [Link]("It has 2 eyes."); } are over 12,000 ant species
} worldwide.
class Pigeon extends Animal { It has 6 legs. It
Pigeon(String name) { super(name); } has 2 eyes.
public void legs() { [Link]("It has 2 legs."); }
public void eyes() { [Link]("It has 2 eyes."); }
}
class Ant extends Animal {
Ant(String name) { super(name); }
public void legs() { [Link]("It has 6 legs."); }
public void eyes() { [Link]("It has 2 eyes."); }
}
public class Test {
public static void main(String[] args) {
Animal object1 = new Camel("Camel");
[Link]("Camels are found in desert.");
[Link]();
[Link]();
22
[Link]();
Animal object2 = new Pigeon("Pigeon");
[Link]("Pigeons are intelligent animals.");
[Link]();
[Link]();
[Link]();
Animal object3 = new Ant("Ant");
[Link]("there are over 12,000 ant species worldwide.");
[Link]();
[Link]();
}
}
Static Methods
static methods are also called class methods. It is because a static method belongs to the class
rather than the object of a class.
we can invoke static methods directly using the class name.
23
9. INTERFACE (DEFINE, IMPLEMENT, ACCESSING METHODS & VARIABLES)
Interface is defined as an abstract type used to specify the behavior of a class.
● An interface contains static constants and abstract methods.
● A class can implement multiple interfaces.
● In Java, interfaces are declared using the interface keyword.
● All methods in the interface are implicitly public and abstract.
Syntax:
interface { //methods; }
***To use an interface in your class, append the keyword “implements” after your class
name followed by the interface name.
Why is an Interface required?
Consider Example;
24
10.EXTENDING INTERFACE, NETED INETERFACE
Class Interface
In class, you can instantiate variable and create an In an interface, you can’t instantiate variable and
object. create an object.
Class can contain concrete(with implementation) The interface cannot contain concrete(with
methods implementation) methods
The access specifiers used with classes are private, In Interface only one specifier is used- Public.
protected and public.
An interface extends another interface like a class implements an interface in interface inheritance.
An interface may be defined inside another interface, and also inside a class. The interface that
defined inside another interface or a class is known as nested interface. The nested interface is
also referred as inner interface.
●The nested interface declared within an interface is public by default.
●The nested interface declared within a class can be with any access modifier.
●Every nested interface is static by default.
25
11.PACKAGE DEFINITION
In small projects, all the java files have unique names. So, it is not difficult to put them in a
single folder. But, in the case of huge projects where the number of java files is large, it is very
difficult to put files in a single folder because the manner of storing files would be disorganized.
Moreover, if different java files in various modules of the project have the same name; it is not
possible to store two java files with the same name in the same folder because it may occur
naming conflict.
This problem of naming conflict can be overcome by using the concept of packages.
A package is nothing but a physical folder structure (directories) that contains a group of
related classes, interfaces, and sub-packages according to their functionality.
It provides a convenient way to organize your work. The Java language has various in- built
packages.
For example, [Link], [Link], [Link], and [Link]. etc.
“A real-life example is when you download a movie, song, or game, you make a different
folder for each category like movie, song, etc. In the same way, a group of packages in java is just
like a library.”
Advantage of using packages in Java
1. Maintenance: Java packages are used for proper maintenance.
2. Reusability: We can place the common code in a common folder so that everybody can check
that folder and use it whenever needed.
3. Name conflict: Packages help to resolve the naming conflict between the two classes with the same
name.
4. Organized: It also helps in organizing the files within our project.
5. Access Protection: A package provides access protection. It can be used to provide visibility
control.
26
Types of Packages
1. User-defined Package
The package which is defined by the user is called a User-defined package. It
contains user-defined classes and interfaces.
A keyword “package” is used to create user-defined packages in java programming.
package packageName;
27
Predefined packages in java are those which are developed by Sun Microsystem.
They are also called built-in packages in java.
These packages consist of a large number of predefined classes, interfaces, and
methods that are used by the programmer to perform any task in his programs.
Core packages:
1. [Link]: lang stands for language. The Java language package consists of java
classes and interfaces that form the core of the Java language and the JVM. It is a fundamental
package that is useful for writing and executing all Java programs.
Examples are classes, objects, String, Thread, predefined data types, etc. It is
imported automatically into the Java programs.
2. [Link]: io stands for input and output. It provides a set of I/O streams that are used to
read and write data to files. A stream represents a flow of data from one place to another place.
3. Java util: util stands for utility. It contains a collection of useful utility classes and
related interfaces that implement data structures like LinkedList, Dictionary, HashTable, stack,
vector, Calender, data utility, etc.
4. [Link]: net stands for network. It contains networking classes and interfaces for
networking operations. The programming related to client-server can be done by using this
package.
Window Toolkit and Applet:
1. [Link]: awt stands for abstract window toolkit. The Abstract window toolkit
packages contain the GUI(Graphical User Interface) elements such as buttons, lists, menus,
and text areas. Programmers can develop programs with colorful screens, paintings, and
images, etc using this package.
2. [Link]: It contains classes and interfaces for creating images and
colors.
3. [Link]: It is used for creating applets. Applets are programs that are
executed from the server into the client machine on a network.
There are three approaches to import one package into another package in Java. import
package.*;
import [Link];
Using fully qualified name.
28
package [Link]; // Now import package.
public class Sum import [Link].*;
{
int a = 20; class SumTest
int b = 30; {
public void cal() public static void main(String[] args)
{ {
int s = a + b; [Link]("Sum: " Sum s = new Sum();
+s); [Link]();
} }
} }
Output:
Sum: 50
[Link]();
}
}
Output:
Kolhapur is the first city of Maharashtra.
Kolhapur city is called Cultural capital city of Maharashtra.
30