java CHAPTER 3 - Copy
java CHAPTER 3 - Copy
Inheritance , Interface
And Package
12 Marks
Inheritance in Java
• Inheritance is an important pillar of OOP.
• It is the mechanism in which one class is allow to inherit the
features(fields and methods) of another class.
Important terminology:
Super Class:
• The class whose features are inherited.(or a base class or a parent class).
Sub Class:
• The class that inherits the other class is known as sub class(or a derived
class, extended class, or child class).
• The subclass can add its own fields and methods in addition to the
superclass fields and methods.
Reusability:
• Inheritance supports “reusability”, i.e. when we create a new class and
there is already a class that includes some of the code that we want, we
can derive our new class from the existing class.
• By doing this, we are reusing the fields and methods of the existing
class.
Inheritance in Java
• Inheritance is an important pillar of OOP.
• It is the mechanism in which one class is allow to inherit the
features(fields and methods) of another class.
Important terminology:
• Super Class
• Sub Class
• Reusability
class B, which in turn serves as a base class for the derived class C.
class one {
public void print_thakur() public class Main
{ {
System.out.println("Thakur"); public static void main(String[] args)
{
}
three t = new three();
} t.print_thakur();
class two extends one { t.print_poly();
public void print_poly() t.print_kandivli();
{ }
}
System.out.println("Polytechnic");
}
}
class three extends two {
public void print_kandivli()
{
System.out.println("Kandivli");
}
}
Hierarchical Inheritance :
• In Hierarchical Inheritance, one class serves as a superclass
(base class) for more than one sub class.
• In below image, the class A serves as a base class for the
derived class B,C and D.
class three extends one
class one {
{ public void print_kandivli()
public void print_thakur() {
System.out.println("Kandivli");
{
}
System.out.println("Thakur"); }
}
} public class Main
{
class two extends one public static void main(String[] args)
{
{
three t = new three();
public void print_poly() t.print_thakur();
{ two w = new two();
w.print_poly();
System.out.println("Polytechnic"); t.print_kandivli();
} }
} }
Method Overloading in Java:
• Overloading allows different methods to have same name, but different
signatures where signature can differ by number of input parameters or type
of input parameters or both.
• Overloading is related to compile time (or static) polymorphism.
public class Sum
{
public int sum(int x, int y) { return (x + y); }
public int sum(int x, int y, int z) { return (x + y + z); }
public double sum(double x, double y) { return (x + y); }
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
Constructors in Java
• Constructors are used to initialize the object’s data members.
When is a Constructor called ?
• Each time an object is created using new() keyword constructor is
invoked to assign initial values to the data members of the same class.
• Constructor is invoked at the time of object or instance creation.
class Thakur
{
Thakur() {}
}
Thakur obj = new Thakur(); //This statement calls above constructor.
Default constructor:
• If no constructor in a class, Java Type Default Value
compiler inserts a default boolean false
long 0L
their wont be any default constructor
char \u0000
from Java compiler in that class.
float 0.0f
• The default constructor initializes any
double 0.0d
uninitialized instance variables with object Reference null
No-arg constructor:
• Constructor with no arguments is known as no-arg constructor.
• The body can have any code unlike default constructor where the
body of the constructor is empty.
• If you write public Demo() { } in your class Demo it cannot be
called default constructor since you have written the code of it.
Example 1: class Demo
{
public Demo()
{
System.out.println(“No argument constructor");
}
public static void main(String args[])
{
Demo d=new Demo();
}
class Main
Parameterized {
Constructor: String languages;
A constructor that accepts Main(String lang)
one or more parameters are {
known as parameterized languages = lang;
constructors System.out.println(languages + " Programming
Language");
}
public static void main(String[] args) {
• Hence final variables must be used only for the values that we
want to remain constant throughout the execution of program.
A final variable cannot be reassign, doing it will throw compile-time error.
class TP
{
final int CAPACITY = 4;
public static void main(String args[])
{
CAPACITY = 5; // throw compile-time error
}
}
Output
Compiler Error: cannot assign a value to final variable CAPACITY
Final methods: Method declared with final keyword is a final method.
• A final method cannot be overridden.
class A
{
final void m1()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void m1() // COMPILE-ERROR! Can't override.
{
System.out.println("Illegal!");
}
}
Final classes
• When a class is declared with final keyword, it is called a final
class.
Rules:
1. It can have abstract methods(methods without body) as well as
concrete methods (regular methods with body).
2. A normal class(non-abstract class) cannot have abstract methods.
3. We can not create object of it abstract class as these classes are
incomplete, they have abstract methods that have no body so java wont
allows you to create object of abstract class.
4. It can have final methods.
5. It can have constructor and static methods also.
Why we need an abstract class?
• Consider a class Shape and has a calculateArea() method for this class.
• As right now for shape - we don't know the implementation for the
calculateArea() method.
• If the shape is circle then its implementation will be for calculating area
for shape circle or if the shape is triangle then implementation will be for
calculating area for Shape Triangle..
• So for class Shape the calculateArea() method will be an abstract
(without implementation) and which ever concrete class will extend this
class, needs to provide implementation for this method.
abstract class Shape { public abstract void calculateArea(); }
class Rectangle extends Shape {
public void calculateArea() {
int length=4, breadth=3;
System.out.println("Area=:"+length * breadth);
}
}
class Circle extends Shape {
public void calculateArea() { int radius=3;
System.out.println("Area=:"+3.14*radius*radius);
}
}
class Triangle extends Shape {
public void calculateArea() { int length=2, height=3;
System.out.println("Area=:"+0.5*height*length);
}
}
Abstract method in Java
Rules:
1. Abstract methods don’t have body, they just have method signature.
2. If a class has an abstract method it should be declared abstract, the vice
versa is not true, which means an abstract class doesn’t need to have an
abstract method compulsory.
3. If a regular class extends an abstract class, then the class must have to
implement all the abstract methods of abstract parent class or it has to
be declared abstract as well.
Java : Static Block, Methods and Variables:
• Static keyword can be used with variable, method and block.
• Static members belong to the class instead of a specific
instance, this means you can access it without object.
Static Block:
• Static block is used for initializing the static variables.
• This block gets executed when the class is loaded in the memory.
• Example :
class StaticBlockExample
{
static int num;
static String mystr;
static { num = 97;
mystr = “Thakur Polytechnic";
}
public static void main(String args[])
{
System.out.println("Value of num: "+num);
System.out.println("Value of mystr: "+mystr);
}
}
Java Static Variables:
• Static variables are also known as Class Variables.
• A static variable is common to all the instances (or objects) of the class
because it is a class level variable.
• Means, a single copy of static variable is created and shared among all
the instances (or objects) of the class.
• Static variables can be accessed directly in static and non-static
methods.
• Memory allocation for such variables only happens once when the
class is loaded in the memory.
Example 1: Static variables accessed directly in Static and non static method
class StaticVariableExample
{
static int var1;
static String var2;
void disp()
{
System.out.println("Var1 is: "+var1);
System.out.println("Var2 is: "+var2);
}
public static void main(String args[])
{
StaticVariableExample s = new StaticVariableExample();
s.disp();
}
}
Java Static Methods:
• Static Methods can access static variables and static methods without
using object of the class.
• Static methods can be accessed directly in static and non-static methods.
Syntax: static return_type method_name();
• The Java compiler adds public and abstract keywords before the
interface method.
• Also, it adds public, static and final keywords before data members.
The relationship between classes and interfaces
• Name Conflicts: We can define two classes with the same name in
different packages so to avoid name collision, we can use packages
For example there can be two classes with name Employee in two
packages, college.staff.cse.Employee and college.staff.ee.Employee
class StaticImportDemo
{
public static void main(String args[])
{
// We don't need to use 'System.out' as imported using static.
out.println("Thakur Polytechnic");
}
}
Thakur Polytechnic