0% found this document useful (0 votes)
15 views41 pages

Lecture 3

The document discusses inheritance in Java, explaining how one class can inherit properties and behaviors from another, creating a parent-child relationship. It covers types of inheritance, method overriding, the use of the super keyword, and the final keyword in relation to variables, methods, and classes. Additionally, it introduces abstract classes and methods, as well as the concept of varargs for methods that accept variable numbers of arguments.

Uploaded by

aadityajoshi2k5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views41 pages

Lecture 3

The document discusses inheritance in Java, explaining how one class can inherit properties and behaviors from another, creating a parent-child relationship. It covers types of inheritance, method overriding, the use of the super keyword, and the final keyword in relation to variables, methods, and classes. Additionally, it introduces abstract classes and methods, as well as the concept of varargs for methods that accept variable numbers of arguments.

Uploaded by

aadityajoshi2k5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 41

Web Technology

(KCS-602)
Lecture 3
Inheritance
 Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviors of a parent object. It is an important part of OOPs
(Object Oriented programming system).
 The idea behind inheritance in Java is that you can create new classes that are
built upon existing classes. When you inherit from an existing class, you can
reuse methods and fields of the parent class. Moreover, you can add new
methods and fields in your current class also.
 Inheritance represents the IS-A relationship which is also known as
a parent-child relationship.
 Child Class:
The class that extends the features of another class is known as child class,
sub class or derived class.
 Parent Class:
The class whose properties and functionalities are used(inherited) by another
class is known as parent class, super class or Base class.
 extends Keyword: extends is the keyword used to inherit the properties
of a class. Following is the syntax of extends keyword.

Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
Example:
class Teacher {
String designation = "Teacher";
String collegeName = "Beginnersbook";
void does(){
System.out.println("Teaching");
}
}
public class PhysicsTeacher extends Teacher{
String mainSubject = "Physics";
public static void main(String args[]){
Output: Beginnersbook
PhysicsTeacher obj = new PhysicsTeacher();
Teacher
System.out.println(obj.collegeName); Physics
System.out.println(obj.designation); Teaching
System.out.println(obj.mainSubject);
obj.does();
}
Types of inheritance in java
 On the basis of class, there can be three types of inheritance in java:
single, multilevel and hierarchical.
Single Inheritance Example

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark(); Output: barking...
d.eat();
eating...
}}
Multilevel Inheritance Example
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...");}
} Output: weeping...
barking...
class TestInheritance2{
eating...
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
Hierarchical Inheritance Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){ Output: meowing...
eating...
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
Method overriding
 Declaring a method in sub class which is already present in parent class is known as
method overriding.
 Overriding is done so that a child class can give its own implementation to a method
which is already provided by the parent class.
 In this case the method in parent class is called overridden method and the method in
child class is called overriding method.
 The main advantage of method overriding is that the class can give its own specific
implementation to a inherited method without even modifying the parent class
code.
 Method Overriding is an example of runtime polymorphism. When a parent class
reference points to the child class object then the call to the overridden method is
determined at runtime, because during method call which method(parent class or child
class) is to be executed is determined by the type of object. This process in which call to
the overridden method is resolved at runtime is known as dynamic method dispatch
Example
class Human{
//Overridden method
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) { Output:Boy is eating
Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
}
}
Example of dynamic dispatch
class ABC{
//Overridden method
public void disp()
{ System.out.println("disp() method of parent class"); } }
class Demo extends ABC{
//Overriding method
public void disp(){
System.out.println("disp() method of Child class"); }
public void newMethod(){
System.out.println("new method of child class"); }
public static void main( String args[]) {
// When Parent class reference refers to the parent class object then in this case overridden
method (the method of parent class) is called. //
ABC obj = new ABC();
obj.disp();
/* When parent class reference refers to the child class object then the overriding method
(method of child class) is called.
Output: disp() method of parent class
* This is called dynamic method dispatch and runtime polymorphism */ disp() method of Child c
ABC obj2 = new Demo();
Rules of method overriding

 The argument list should be exactly the same as that of the overridden method.
 The return type should be the same or a subtype of the return type declared in the
original overridden method in the superclass.
 The access level cannot be more restrictive than the overridden method's access level.
For example: If the superclass method is declared public then the overridding method
in the sub class cannot be either private or protected.
 Instance methods can be overridden only if they are inherited by the subclass.
 A method declared final cannot be overridden.
 A method declared static cannot be overridden but can be re-declared.
 If a method cannot be inherited, then it cannot be overridden.
 A subclass within the same package as the instance's superclass can override any
superclass method that is not declared private or final.
 A subclass in a different package can only override the non-final methods declared
public or protected.
 An overriding method can throw any uncheck exceptions, regardless of whether the
overridden method throws exceptions or not. However, the overriding method should
not throw checked exceptions that are new or broader than the ones declared by the
overridden method. The overriding method can throw narrower or fewer exceptions
than the overridden method.
 Constructors cannot be overridden.
Super keyword

 The super keyword is used for calling the parent class method/constructor.
super.myMethod() calls the myMethod() method of base class while super() calls
the constructor of base class.
class ABC{
public void myMethod()
{
System.out.println("Overridden method");
} }
class Demo extends ABC{
public void myMethod(){
//This will call the myMethod() of parent class
super.myMethod();
Output: Overridden method
System.out.println("Overriding method"); } Overriding method
public static void main( String args[]) {
Demo obj = new Demo();
obj.myMethod(); } }
Final keyword

 final is a non-access modifier applicable only to a variable, a method


or a class.
Final variables
 When a variable is declared with final keyword, its value can’t be modified,
essentially, a constant. This also means that you must initialize a final
variable.
 We cannot change the value of a final variable once it is initialized. Ex:
class Demo{
final int MAX_VALUE=99;
void myMethod(){
MAX_VALUE=101;
}
public static void main(String args[]){
Demo obj=new Demo();
obj.myMethod();
Output:Exception in thread "main" java.lang.Error: Unresolved compilation proble
}
The final field Demo.MAX_VALUE cannot be assigned
}
Blank final variable

 A final variable that is not initialized at the time of declaration is known as blank final
variable. We must initialize the blank final variable in constructor of the class
otherwise it will throw a compilation error.
 Example: class Demo{
//Blank final variable
final int MAX_VALUE;
Demo(){
//It must be initialized in constructor
MAX_VALUE=100; }
void myMethod(){
System.out.println(MAX_VALUE); }
public static void main(String args[]){ Output: 100

Demo obj=new Demo();


obj.myMethod(); } }
Whats the use of blank final variable?
class StudentData{
//Blank final variable
final int ROLL_NO;

StudentData(int rnum){
//It must be initialized in constructor
ROLL_NO=rnum;
}
void myMethod(){
System.out.println("Roll no is:"+ROLL_NO);
}
public static void main(String args[]){
StudentData obj=new StudentData(1234);
obj.myMethod();
}
}
Final static variable in Java

 If we won’t initialize a static variable, then by default JVM will provide a default value for
static variable. But when we declare a static variable with final modifier then we should
take care of the following conventions:
 Declaring variables only as static can lead to change in their values by one or more
instances of a class in which it is declared.
 Declaring them as static final will help you to create a CONSTANT. Only one copy of
variable exists which can’t be reinitialize.
 Important points about final static variable:
1. Initialization of variable Mandatory : If the static variable declared as final, then we
have to perform initialization explicitly whether we are using it or not and JVM won’t
provide any default value for the final static variable.
2. Initialization before class loading : For final static variable, it is compulsory that we
should perform initialization before class loading completion. We can initialize a final static
variable at the time of declaration.
3. Initialize inside a static block : We can also initialize a final static variable inside a static
block because we should initialize a final static variable before class and we know that
static block is executed before main() method.
Initialization of variable Mandatory :
class Test {
final static int x;
public static void main(String[] args)
{ System.out.println(x);
}
}
Output: Error: variable x might not have been initialized
Initialization before class
loading
 / Java program to illustrate that final static variable can be initialized at the time of
declaration
class Test {
final static int x = 10;
public static void main(String[] args)
{
System.out.println(x);
}
}

Output: 10
Initialize inside a static block
// Java program to illustrate that final static variable can be initialized inside static block
class Test {
final static int x;
static
{
x = 10;
}
public static void main(String[] args)
{
System.out.println(x);
}
}
Output: 10
Java final method

 When a method is declared with final keyword, it is called a final method. A final method
cannot be overridden.
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
Java final class
 If you make any class as final, you cannot extend it.
final class Bike{}

class Honda1 extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}
Output: Compile Time Error
There are two uses of a final class :

1. One is to prevent inheritance, as final classes cannot be extended.


For example, all Wrapper Classes like Integer, Float etc. are final
classes. We can not extend them.
 The other use of final with classes is to create an immutable class like
the predefined String class. You can not make a class immutable
without making it final.
Immutable class
 Immutable class means that once an object is created, we cannot change its content.
In Java, all the wrapper classes (like Integer, Boolean, Byte, Short) and String class is
immutable. We can create our own immutable class as well.
 Following are the requirements:
 The class must be declared as final (So that child classes can’t be created)
 Data members in the class must be declared as final (So that we can’t change the
value of it after object creation)
 A parameterized constructor
 Getter method for all the variables in it
 No setters(To not have the option to change the value of the instance variable)
Example to create Immutable
class
// An immutable class
public final class Student {
final String name;
final int regNo;
public Student(String name, int regNo) {
this.name = name;
this.regNo = regNo; }
public String getName() {
return name; }
public int getRegNo() {
return regNo; } }
// Driver class
class Test {
public static void main(String args[]) {
Student s = new Student("ABC", 101);
System.out.println(s.getName());
System.out.println(s.getRegNo());
// Uncommenting below line causes error
Abstract Methods and Classes
 A method without body (no implementation) is known as abstract method. A method must
always be declared in an abstract class, or in other words you can say that if a class has an
abstract method, it should be declared abstract as well.
 A class which is declared with the abstract keyword is known as an abstract class in Java. It
can have abstract and non-abstract methods (method with the body).
 This is how an abstract method looks in java:
public abstract int myMethod(int n1, int n2);
Rules of Abstract Method:
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.
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}

Output: running safely


Java varargs

 varargs in java enables a method to accept variable number of


arguments. We use three dots (…) also known as ellipsis in the method
signature to make it accept variable arguments. For example:
public static int sum(int i, int...js ){
//do something
}
Few points to know about varargs in java are:
1. We can have only one varargs in the method.
2. Only the last argument of a method can be varargs.
3. According to java documentation, we should not overload a varargs
method.
How java varargs work?
When we invoke a method with variable arguments, java compiler matches
the arguments from left to right. Once it reaches to the last varargs
parameter, it creates an array of the remaining arguments and pass it to the
method. In fact varargs parameter behaves like an array of the specified
type.
Example:
//method with variable arguments
public static int sum(int i, int...js ){
int sum = i;
for(int x : js){
sum+=x;
}
return sum;
}

//method with same implementation as sum with array as argument


public static int sumArray(int i, int[] js ){
int sum = i;
for(int x : js){
sum+=x;
}
return sum;
}
Why we should not overload varargs method

public class VarargsExample {


public static void main(String[] args) {
System.out.println(sum(1));
System.out.println(sum(1,2)); //compiler error, ambiguous method
}
public static int sum(int i, int...js ){
System.out.println("sum1 called");
int sum = i;
for(int x : js){
sum+=x; }
return sum; }
public static int sum(int i, int k, Object...js ){
System.out.println("sum2 called");
int sum = i+k;
for(Object x : js){
sum+=1; }
return sum; } }
Interfaces
 The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods
in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance
in Java.
 In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.
 Declaring Interfaces: The interface keyword is used to declare an interface.
interface MyInterface
{
/* All the methods are public abstract by default
* As you see they have no body
*/
public void method1();
public void method2();
}
 An interface is similar to a class in the following ways −
 An interface can contain any number of methods.
 An interface is written in a file with a .java extension, with the name of the
interface matching the name of the file.
 The byte code of an interface appears in a .class file.
 Interfaces appear in packages, and their corresponding bytecode file must be
in a directory structure that matches the package name.
 However, an interface is different from a class in several ways,
including −
 You cannot instantiate an interface.
 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface cannot contain instance fields. The only fields that can appear in
an interface must be declared both static and final.
 An interface is not extended by a class; it is implemented by a class.
 An interface can extend multiple interfaces.
interface MyInterface
{
public void method1();
public void method2();}
class Demo implements MyInterface{
// This class must have to implement both the abstract methods else you
will get compilation error
public void method1() {
System.out.println("implementation of method1"); }
public void method2() {
System.out.println("implementation of method2"); }
public static void main(String arg[]) {
MyInterface obj = new Demo();
obj.method1(); } }
key points to remember about
interfaces:
1) We can’t instantiate an interface in java. That means we cannot create the object of an interface
2) Interface provides full abstraction as none of its methods have body. On the other hand abstract class provides partial
abstraction as it can have abstract and concrete(methods with body) methods both.
3) implements keyword is used by classes to implement an interface.
4) While providing implementation in class of any method of an interface, it needs to be mentioned as public.
5) Class that implements any interface must implement all the methods of that interface, else the class should be
declared abstract.
6) Interface cannot be declared as private, protected or transient.
7) All the interface methods are by default abstract and public.
8) Variables declared in interface are public, static and final by default.
9) Interface variables must be initialized at the time of declaration otherwise compiler will throw an error.
10) Inside any implementation class, you cannot change the variables declared in interface because by default, they are
public, static and final.
11) An interface can extend any interface but cannot implement it. Class implements interface and interface extends
interface.
12) A class can implement any number of interfaces.
13) If there are two or more same methods in two interfaces and a class implements both interfaces, implementation
of the method once is enough.
14) A class cannot implement two interfaces that have methods with same name but different return type.
Multiple Inheritance
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}
Interface inheritance

interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}
Default Method in Interface

interface Drawable{
void draw();
default void msg(){System.out.println("default method");}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}}
Output: drawing rectangle
default method
Static Method in Interface

interface Drawable{
void draw();
static int cube(int x){return x*x*x;}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}

class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw(); Output: drawing rectangle
27
System.out.println(Drawable.cube(3));
}}
Difference between abstract class and
interface
Abstract class Interface
1) Abstract class can have abstract and non-abstract methods. Interface can have only abstract methods. Since Java 8, it can
have default and static methods also.

2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.

3) Abstract class can have final, non-final, static and non-static Interface has only static and final variables.
variables.

4) Abstract class can provide the implementation of interface. Interface can't provide the implementation of abstract class.

5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.

6) An abstract class can extend another Java class and implement An interface can extend another Java interface only.
multiple Java interfaces.

7) An abstract class can be extended using keyword "extends". An interface can be implemented using keyword "implements".

8) A Java abstract class can have class members like private, Members of a Java interface are public by default.
protected, etc.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy