In this tutorial we will discuss about the inheritance in Java. The most fundamental element of Java is the class. A class represents an entity and also, defines and implements its functionality. In Java, classes can be derived from other classes, in order to create more complex relationships.

A class that is derived from another class is called subclass and inherits all fields and methods of its superclass. In Java, only single inheritance is allowed and thus, every class can have at most one direct superclass. A class can be derived from another class that is derived from another class and so on. Finally, we must mention that each class in Java is implicitly a subclass of the Object class.

Suppose we have declared and implemented a class A. In order to declare a class B that is derived from A, Java offers the extendkeyword that is used as shown below:

1 class A {
2     //Members and methods declarations.
3 }
4  
5 class extends A {
6     //Members and methods from A are inherited.
7     //Members and methods declarations of B.
8 }

Java supports only public inheritance and thus, all fields and methods of the superclass are inherited and can be used by the subclass. The only exception are the private members of the superclass that cannot be accessed directly from the subclass. Also, constructors are not members, thus they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass. In order to call the constructor of the superclass Java provides the keyword super, as shown below:

01 class A {
02     public A() {
03         System.out.println("New A");
04     }
05 }
06  
07 class extends A {
08     public B() {
09         super();
10         System.out.println("New B");
11     }
12 }

A sample example to present the inheritance in Java is shown below:

Animal.java:

01 public class Animal {
02     public Animal() {
03         System.out.println("A new animal has been created!");
04     }
05      
06     public void sleep() {
07         System.out.println("An animal sleeps...");
08     }
09      
10     public void eat() {
11         System.out.println("An animal eats...");
12     }
13 }

Bird.java:

01 public class Bird extends Animal {
02     public Bird() {
03         super();
04         System.out.println("A new bird has been created!");
05     }
06      
07     @Override
08     public void sleep() {
09         System.out.println("A bird sleeps...");
10     }
11      
12     @Override
13     public void eat() {
14         System.out.println("A bird eats...");
15     }
16 }

Dog.java:

01 public class Dog extends Animal {
02     public Dog() {
03         super();
04         System.out.println("A new dog has been created!");
05     }
06      
07     @Override
08     public void sleep() {
09         System.out.println("A dog sleeps...");
10     }
11      
12     @Override
13     public void eat() {
14         System.out.println("A dog eats...");
15     }
16 }

MainClass.java:

01 public class MainClass {
02     public static void main(String[] args) {
03         Animal animal = new Animal();
04         Bird bird = new Bird();
05         Dog dog = new Dog();
06          
07         System.out.println();
08          
09         animal.sleep();
10         animal.eat();
11          
12         bird.sleep();
13         bird.eat();
14          
15         dog.sleep();
16         dog.eat();
17     }
18 }

In this example we created three distinct classes, AnimalDog and Bird. Both Dog and Bird classes extend the Animal class and thus, they inherit its members and methods. Moreover, as we can see below, each class overrides the methods of Animal and thus, both the Dog and Bird classes redefine the functionality of Animal’s methods.

A sample execution is shown below:

A new animal has been created!
A new animal has been created!
A new bird has been created!
A new animal has been created!
A new dog has been created! An animal sleeps...
An animal eats...
A bird sleeps...
A bird eats...
A dog sleeps...
A dog eats...

A nested class has access to all the private members of its enclosing class, both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass.

As already mentioned, a subclass inherits all of the public and protected members of its superclass. If the subclass is in the same package as its superclass, it also inherits the package-private members of the superclass. The inheritance in Java provides the following features:

  • You can declare a field in the subclass with the same name as the one in the superclass thus, hiding it. This is called shadowing.
  • You can declare new fields in the subclass that are not in the superclass.
  • You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it.
  • You can declare new methods in the subclass that are not in the superclass.

Final abstract classes can exist in a hierarchy of types. For more information about abstract classes and how are used in Java, please refer to the Java abstract tutorial here.

Inheritance and Casting

When a class B extends a class A, then an instance of the B class is of type B, but also of type A. Thus, such an instance can be used in all cases where a class B or class A object is required. However, the reverse is not true! An instance of the class A is of course of type A, but it is not of type B.

Thus, we can use casting between the instances of classes. The cast inserts a runtime check, in order for the compiler to safely assume that the cast is used properly and is correct. If not, a runtime exception will be thrown.

A simple example that demonstrates the usage of casting is shown below:

1 Animal a1 = new Dog();
2 Animal a2 = new Bird();
3          
4 a1.eat();
5 a2.sleep();
6          
7 // The following statements are incorrect.
8 // Dog d = new Animal();
9 // Bird b = new Animal();

A sample execution is shown below:

A dog eats...
A bird sleeps...

The instanceof operator

The instanceof operator can be used, in order to determine if an object is a valid instance of a specific type. It can be used to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface. A simple example is shown below:

1 Dog d = new Dog();
2 if(d instanceof Animal) {
3     Animal a = (Animal) d;
4     a.sleep();
5 }
6 d.sleep();

Interfaces

An interface in Java is an abstract type that is used to declare and specify a set of public methods and members. An interface can be implemented by a class. In this case, the class must provide an implementation for every method defined in the interface. A significant advantage of using interfaces is the fact that in Java, multiple interfaces can be implemented by a single class.

A sample example that uses both classes and multiple interfaces is shown below:

BasketballTeam.java:

1 public interface BasketballTeam {
2     public void printBasketballName();
3 }

FootballTeam.java:

1 public interface FootballTeam {
2     public void printFootballName();
3 }

Team.java:

01 public class Team implements BasketballTeam, FootballTeam {
02  
03     private String name = null;
04      
05     public Team(String name) {
06         this.name = name;
07     }
08  
09     @Override
10     public void printFootballName() {
11         System.out.println("Football Team: \"" + name + " F.C.\"");
12     }
13  
14     @Override
15     public void printBasketballName() {
16         System.out.println("Basketball Team: \"" + name + " B.C.\"");
17     }
18      
19     public static void main(String[] args) {
20         Team t = new Team("Team A");
21         t.printBasketballName();
22         t.printFootballName();
23     }
24 }

A sample execution is shown below:

Basketball Team: "Team A B.C."
Football Team: "Team A F.C."

Summary: Java Inheritance的更多相关文章

  1. Summary: Java中函数参数的传递

    函数调用参数传递类型(java)的用法介绍. java方法中传值和传引用的问题是个基本问题,但是也有很多人一时弄不清. (一)基本数据类型:传值,方法不会改变实参的值. public class Te ...

  2. SUMMARY | JAVA中的数据结构

    String String类是不可修改的,创建需要修改的字符串需要使用StringBuffer(线程同步,安全性更高)或者StringBuilder(线程非同步,速度更快). 可以用“+”连接Stri ...

  3. Java longTime 和C#日期转换(结构+运算符重载)

    前几天,因为工作原因,连到了公司的一个java系统.查看数据的时候,突然整个人都不好了,数据库中日期字段时间为毛都是整型?之前从来没有接触过java,所心就趁机了解了一下.原来,在数据库中,保存的是j ...

  4. JavaScript- The Good Parts Chapter 5 Inheritance

    Divides one thing entire to many objects;Like perspectives, which rightly gazed uponShow nothing but ...

  5. Java Interview Reference Guide--reference

    Part 1 http://techmytalk.com/2014/01/24/java-interview-reference-guide-part-1/ Posted on January 24, ...

  6. 【DateStructure】 Charnming usages of Map collection in Java

    When learning the usage of map collection in java, I found serveral beneficial methods that was enco ...

  7. java url demo

    // File Name : URLDemo.java import java.net.*; import java.io.*; public class URLDemo { public stati ...

  8. Java 8 Date-Time API 详解

    从Java版本1.0开始就支持日期和时间,主要通过java.util.Date类. 但是,Date类设计不佳. 例如,Date中的月份从1开始,但从日期却从0开始.在JDK 1.1中使用它的许多方法已 ...

  9. 关于Java中基类构造器的调用问题

    在<Java编程思想>第7章复用类中有这样一段话,值得深思.当子类继承了父类时,就涉及到了基类和导出类(子类)这两个类.从外部来看,导出类就像是一个与基类具有相同接口的新类,或许还会有一些 ...

随机推荐

  1. Android 使用tomcat搭建HTTP文件下载服务器

    上一篇: Android 本地搭建Tomcat服务器供真机测试 1.假设需要下载的文件目录是D:\download1(注意这里写了个1,跟后面的名称区分) 2.设置 tomcat 的虚拟目录.在 {t ...

  2. ab压测工具

    在学习ab工具之前,我们需了解几个关于压力测试的概念 吞吐率(Requests per second)概念:服务器并发处理能力的量化描述,单位是reqs/s,指的是某个并发用户数下单位时间内处理的请求 ...

  3. shell中的环境变量:local,global,export

     1.local一般用于局部变量声明,多在在函数内部使用.实例如下:      echo_start() { local STR="$1" echo "...... ${ ...

  4. VC消息传递(对话框间传递参数)

    以下用一个自创的对话框类(MyMessageDlg)向视图类(MessageTestView)发送自定义消息为例,说明这两种不同方法的自定义消息的 消息传递的方法一:使用ON_MESSAGE使用ON_ ...

  5. spring boot 通过Maven + tomcat 自动化部署

    使用maven创建的springboot项目,默认是jar包,springboot还有自己带的tomcat. 现在为了简单实现本地自动发布项目到服务器,需要通过发布war包的形式,通过maven将项目 ...

  6. JDK1.8版本,java并发框架支持锁包括

    1.自旋锁,自旋,jvm默认是10次,由jvm自己控制,for去争取锁 2.阻塞锁 被阻塞的线程,不会争夺锁 3.可重入锁,多次进入改锁的域 4.读写锁 5.互斥锁,锁本身就是互斥的 6.悲观锁,不相 ...

  7. /etc/vim/vimrc的一个的配置

    (转)Vim 配置文件===/etc/vimrc "===================================================================== ...

  8. wordpress---page页面数据调用

    在wordpress的开发中,会使用wordpress的的页面,那么页面数据该怎么调用呢? 拿到页面的 content: <?php if(have_posts()) : ?> <? ...

  9. Apache服务器301重定向去掉.html和.php

    在做优化网站的时候,会考虑到网站整站的集权: 考虑到网站可以生成静态,首先,让网站优先访问 index.html 之后考虑:去掉 .html 和 .php. 利用 .htaccess <IfMo ...

  10. Spark2 ML包之决策树分类Decision tree classifier详细解说

    所用数据源,请参考本人博客http://www.cnblogs.com/wwxbi/p/6063613.html 1.导入包 import org.apache.spark.sql.SparkSess ...