Java Inheritance Tutorial: explained with examples

Java Inheritance Tutorial

What is Inheritance?

  • Inheritance in Java

Java inheritance examples

Advanced concepts to learn next, start mastering java with our hands-on courses today..

Cover

In practice, inheritance, and polymorphism are used together in Java to achieve fast performance and readability of code.

Java Inheritance Types

Below are the different types of inheritance which are supported by Java.

  • Single Inheritance

Multilevel Inheritance

  • Hierarchical Inheritance

Multiple Inheritance

Hybrid Inheritance

1. Single Inheritance

In single inheritance, subclasses inherit the features of one superclass. In the image below, class A serves as a base class for the derived class B.

Single inheritance

Single inheritance

2. Multilevel Inheritance

In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the derived class also acts as the base class for other classes. In the below image, class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C. In Java, a class cannot directly access the grandparent’s members .

Multilevel Inheritance

3. Hierarchical Inheritance

In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In the below image, class A serves as a base class for the derived classes B, C, and D.

Hierarchical-Inheritance-in-Java

4. Multiple Inheritance ( Through Interfaces)

In Multiple inheritances , one class can have more than one superclass and inherit features from all parent classes. Please note that Java does not support multiple inheritances with classes. In Java, we can achieve multiple inheritances only through Interfaces . In the image below, Class C is derived from interfaces A and B.

Multiple Inheritance

5. Hybrid Inheritance

It is a mix of two or more of the above types of inheritance. Since Java doesn’t support multiple inheritances with classes, hybrid inheritance involving multiple inheritance is also not possible with classes. In Java, we can achieve hybrid inheritance only through Interfaces if we want to involve multiple inheritance to implement Hybrid inheritance. However, it is important to note that Hybrid inheritance does not necessarily require the use of Multiple Inheritance exclusively. It can be achieved through a combination of Multilevel Inheritance and Hierarchical Inheritance with classes, Hierarchical and Single Inheritance with classes. Therefore, it is indeed possible to implement Hybrid inheritance using classes alone, without relying on multiple inheritance type. 

Hybrid Inheritance

Java IS-A type of Relationship

IS-A is a way of saying: This object is a type of that object. Let us see how the extends keyword is used to achieve inheritance.

Now, based on the above example, in Object-Oriented terms, the following are true:-

  • SolarSystem is the superclass of Earth class.
  • SolarSystem is the superclass of Mars class.
  • Earth and Mars are subclasses of SolarSystem class.
  • Moon is the subclass of both Earth and SolarSystem classes.

What Can Be Done in a Subclass?

In sub-classes we can inherit members as is, replace them, hide them, or supplement them with new members: 

  • The inherited fields can be used directly, just like any other fields.
  • We can declare new fields in the subclass that are not in the superclass.
  • The inherited methods can be used directly as they are.
  • We can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it (as in the example above, toString() method is overridden).
  • We can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it.
  • We can declare new methods in the subclass that are not in the superclass.
  • We can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super .

 Advantages Of Inheritance in Java:

  • Code Reusability: Inheritance allows for code reuse and reduces the amount of code that needs to be written. The subclass can reuse the properties and methods of the superclass, reducing duplication of code.
  • Abstraction: Inheritance allows for the creation of abstract classes that define a common interface for a group of related classes. This promotes abstraction and encapsulation, making the code easier to maintain and extend.
  • Class Hierarchy: Inheritance allows for the creation of a class hierarchy, which can be used to model real-world objects and their relationships.
  • Polymorphism: Inheritance allows for polymorphism, which is the ability of an object to take on multiple forms. Subclasses can override the methods of the superclass, which allows them to change their behavior in different ways.

Disadvantages of Inheritance in Java:

  • Complexity: Inheritance can make the code more complex and harder to understand. This is especially true if the inheritance hierarchy is deep or if multiple inheritances is used.
  • Tight Coupling: Inheritance creates a tight coupling between the superclass and subclass, making it difficult to make changes to the superclass without affecting the subclass.

Let us check some important points from the article are mentioned below:

  • Default superclass : Except Object class, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of the Object class.
  • Superclass can only be one: A superclass can have any number of subclasses. But a subclass can have only one superclass. This is because Java does not support multiple inheritances with classes. Although with interfaces, multiple inheritances are supported by Java.
  • Inheriting Constructors: A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
  • Private member inheritance: A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods(like getters and setters) for accessing its private fields, these can also be used by the subclass.

FAQs in Inheritance

1. what is inheritance java.

Inheritance is a concept of OOPs where one class inherits from another class that can reuse the methods and fields of the parent class.

2. What are the 4 types of inheritance in Java?

There are Single, Multiple, Multilevel, Hierarchical and Hybrid

3. What is the use of extend keyword?

Extend keyword is used for inheriting one class into another.

4. What is an example of inheritance in Java?

A real-world example of Inheritance in Java is mentioned below:

Consider a group of vehicles. You need to create classes for Bus, Car, and Truck. The methods fuelAmount(), capacity(), applyBrakes() will be the same for all three classes.
References Used: “Head First Java” by Kathy Sierra and Bert Bates “Java: A Beginner’s Guide” by Herbert Schildt “Java: The Complete Reference” by Herbert Schildt “Effective Java” by Joshua Bloch “Java: The Good Parts” by Jim Waldo.

Please Login to comment...

Similar reads.

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Javatpoint Logo

Java Object Class

Java inheritance, java polymorphism, java abstraction, java encapsulation, java oops misc.

JavaTpoint

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

Java Tutorial

Java methods, java classes, java file handling, java how to, java reference, java examples, java inheritance, java inheritance (subclass and superclass).

In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories:

  • subclass (child) - the class that inherits from another class
  • superclass (parent) - the class being inherited from

To inherit from a class, use the extends keyword.

In the example below, the Car class (subclass) inherits the attributes and methods from the Vehicle class (superclass):

Try it Yourself »

Did you notice the protected modifier in Vehicle?

We set the brand attribute in Vehicle to a protected access modifier . If it was set to private , the Car class would not be able to access it.

Why And When To Use "Inheritance"?

- It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class.

Tip: Also take a look at the next chapter, Polymorphism , which uses inherited methods to perform different tasks.

Advertisement

The final Keyword

If you don't want other classes to inherit from a class, use the final keyword:

If you try to access a final class, Java will generate an error:

The output will be something like this:

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

DEV Community

DEV Community

Suleiman Ibrahim

Posted on Sep 26, 2021 • Updated on Oct 26, 2021

OOP Series: Inheritance in Java

Introduction.

Object-oriented Programming (OOP) is a programming paradigm based on the concepts of Objects and Classes . It allows the group or collection of related objects in a class and creates functionalities for use by the class with the help of methods. Object-oriented programming has four pillars or principles known as:

  • Inheritance
  • Polymorphism
  • Data Abstraction
  • Encapsulation

These four principles define an Object-oriented language. In this article, we will be looking at Inheritance .

  • Prerequisite knowledge
  • Direct and Indirect superclass

Composition vs. Inheritance

  • The Student class

PREREQUISITE KNOWLEDGE

This article explains the concept of inheritance using the Java programming language. Thus, you need the following knowledge of Java:

  • Basic understanding of OOP.
  • Classes and objects. If you are new to Java or have a rusty knowledge of it, you can do well to check out Hello World Breakdown in Java where we walk through the building blocks of a simple Java program.

INHERITANCE

Inheritance is one of the four pillars of the Object-Oriented Programming paradigm. Inheritance is a concept that allows us to create new classes from an existing class by acquiring or inheriting the properties of that class. And also, adding more functionality to the new class. Take the family hierarchy, for example, the children exhibit some characteristics of either the mother or the father. Some of these characteristics might include:

Here, we can say that the child inherits those characteristics from the parent. Since those characteristics are present in the parent. Sometimes, the child might inherit not only the characteristics of the parent but the grandparents as well. In other cases, the child might inherit the characteristics of both the parent and grandparent and still display their characteristics, which make the child unique. This is the basic concept of inheritance in OOP. Inheritance allows us to derive a new class from an existing class. The existing class from which we can derive the new classes is called the superclass in Java. It is also known as the base class or parent class in some other languages like C++. While the new class that is derived is called the subclass in Java. It is also known as derived or child class in some other object-oriented languages as well.

Some advantages inheritance provides are:

  • Reusability: It allows the reuse of code written by us or other programmers. Hence, avoiding reinventing the wheel .
  • Flexibility: When we need to update some group of classes, inheritance allows us to update the superclass only. Instead of making the update on all the affected classes.
  • Redundancy: Inheritance allows us to write less code and build upon the previous ones. Thereby reducing redundancy and encouraging cleaner code.
  • Data hiding: The use of private instance variables, and setters and getters methods to access them. This allows restricted access to the variables of a class.

Direct and Indirect Superclass

We can categorize superclasses into two types, direct superclass, and indirect superclass. The direct superclass is the immediate class from which a new class inherits in the class hierarchy. It is the class immediately above the new class in the inheritance hierarchy tree. The indirect superclass is any class in the inheritance hierarchy above the direct superclass. The new class does not directly inherit any attribute from an indirect superclass but gets these attributes from the direct superclass. All classes in Java directly or indirectly inherit from the Object class, which can be found in java.lang.Object . The Object class provides some functionalities such as equals() (which checks whether two objects are equal), getClass() (which returns the runtime class of a particular object), toString() (which returns a string comprising the name of the class of which the object is an instance and the unsigned hexadecimal representation of the hash code of the object), notify() , notifyAll() and many others which the Object’s subclasses can utilize.

Java only provides support for single inheritance. Unlike other programming languages like C++ that support both single and multiple inheritance. In single inheritance, we can derive a class from only one direct superclass, while in multiple inheritance, we can derive a class from more than one superclass. The relationship that can exist between two classes can either be is-a relationship or has-a relationship. Is-a relationship implies inheritance, while has-a relationship implies composition. In inheritance, we can treat an object of a subclass as an object of the superclass. For instance, if a Rectangle class extends the Shape class, then the Rectangle is-a Shape and thus, we can treat it as a Shape. In composition, a class can to have references to objects of other classes as its member. For example, each student has a course of study, so it is necessary to include a reference of the Course class as a member of the Student class. In this case, we can say that each Student has-a a Course.

The Student Class

Student Hierarchy

Here, we can consider the Student class to be the base class of all classes. Undergraduate and Graduate inherit directly from the Student class. FirstYear and SecondYear inherit directly from the Undergraduate class. In this case, FirstYear and SecondYear have an indirect inheritance to the Student class and a direct inheritance to the Undergraduate class. Since FirstYear and SecondYear inherit directly from the Undergraduate but not directly from the Student class.

Student.java first starts by declaring and initializing its instance private instance fields. Recall that any field or member declared as private is only accessible to the class alone, so therefore the instance fields declared in the Student class can’t be accessed outside the class. This is where the set and get methods come to help. In this case, the set methods first validate the values entered before making them available to the class for use and throw an error with a meaningful message to the user. It means that any class extending the Student class needs not to validate its first name, last name, and student id anymore because the Student class has already handled that. This is one of the advantages of inheritance provides. It prevents programmers from reinventing the wheel. This speeds up production and also reduces the complexity of a program since some implementations are done in the superclass. The toString() method at the end also shows that the Student class is overriding one of its superclass methods using the @Override annotation. Recall that every class in Java by default and directly or indirectly extends the Object superclass, so we don’t have to explicitly extend the Object class at the Student class declaration. This also shows that subclasses can modify or increase the capabilities of the superclass members by simply overriding them in the subclass.

The next program containing the Undergraduate class inherits the properties of the Student class.

Undegraduate.java first starts at the class declaration by extending/inheriting from the Student class using the extends keyword. extends is a keyword in Java we use to implement inheritance and it can only extend one class since Java only supports single inheritance. The program continued by declaring an instance field and then declaring the constructor with parameters. Then next to the initializing the superclass variable using the super keyword. A set of parentheses comprising the superclass constructor arguments immediately followed this. super is also a keyword in Java and subclasses use it to initialize the variables of the superclass constructor. Java requires that the first task of any subclass constructor is to call the constructor of its direct superclass. We don’t need to validate firstName, lastName, and studentId anymore because the superclass has handled that already. And we can access them using the super. followed by their get methods. Similar to the Student class, the Undergraduate class also has its own toString() method which uses super.toString() String representation of the superclass. We can access members of the superclass using the super. followed by the member to access. For example,

The next program containing the Graduate class also inherits from the student class

Similar to the Undergraduate class, the Graduate class also extends the Student class. And contains an instance variable and a constructor that takes in values to initialize the superclass variables. The implementation of the Graduate class is similar to the Undergraduate class. The main purpose of the Graduate class is to show how multiple subclasses can inherit from a single superclass—Student class. The next program contains the StudentTest class that implements both the Undergraduate and Graduate classes.

Class StudentTest creates objects of both the Undergraduate and Graduate classes. And then passes the constructor values as well. It then proceeds to print the values of the objects created. Notice that we did not explicitly use the toString() method to print the String representation of the objects. This is because we have already customized them from the Undergraduate and Graduate classes respectively. Below is the output of executing StudentTest.java

StudentTest.java output

The output first displays the details of the undergraduate student. Followed by the graduate student. Notice that among the undergraduate and graduate student details is an extra detail specifying the type of student. Which was not included in the constructor when created. These details and the format of the output were all included in the toString() method of the respective subclasses.

Inheritance is a broad topic in Java and other object-oriented programming languages as well. This article implemented the concept of inheritance using the Student class. With Graduate and Undergraduate classes as subclasses. We learned about the concept of superclass and subclass and their usage in inheritance. And then used some keywords such as extends, super as well as using the @override annotation to add functionalities to the default toString method of every class. We then moved to use the setters and getters methods to access the private field of a superclass as well as validate the values before setting them. In the next article, we will build upon the concept of inheritance by introducing Polymorphism. The ability of objects to exist in many forms. Which is also a core principle of object-oriented programming.

Top comments (0)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

m__mdy__m profile image

What is Encapsulation

mahdi - Mar 16

dilanka-rathnasiri profile image

Java Method overriding

Dilanka Rathnasiri - Mar 15

crawlbase profile image

How to Bypass CAPTCHAs in Web Scraping 2024

Crawlbase - Mar 14

anogneva profile image

PVS-Studio extension for Visual Studio Code: searching for errors in Java code

Anastasiia Ogneva - Feb 9

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

SlidePlayer

  • My presentations

Auth with social network:

Download presentation

We think you have liked this presentation. If you wish to download it, please recommend it to your friends in any social system. Share buttons are a little bit lower. Thank you!

Presentation is loading. Please wait.

Java Inheritance.

Published by Διώνη Ιωαννίδης Modified over 5 years ago

Similar presentations

Presentation on theme: "Java Inheritance."— Presentation transcript:

Java Inheritance

PHP functions What are Functions? A function structure:

java inheritance presentation

Object Oriented Programming with Java

java inheritance presentation

OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.

java inheritance presentation

METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.

java inheritance presentation

1 Chapter 6: Extending classes and Inheritance. 2 Basics of Inheritance One of the basic objectives of Inheritance is code reuse If you want to extend.

java inheritance presentation

Inheritance Java permits you to use your user defined classes to create programs using inheritance.

java inheritance presentation

Java Inheritance. What is inherited A subclass inherits variables and methods from its superclass and all of its ancestors. The subclass can use these.

java inheritance presentation

Encapsulation, Inheritance & Interfaces CSE 115 Spring 2006 February 27, March 1 & 3, 2006.

java inheritance presentation

1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.

java inheritance presentation

1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.

java inheritance presentation

Chapter 10 Classes Continued

java inheritance presentation

Inheritance Review/Recap. ClassA extends ClassB ClassA now inherits (can access and use) all public and protected elements of ClassB We can expect the.

java inheritance presentation

8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.

java inheritance presentation

Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.

java inheritance presentation

CISC6795: Spring Object-Oriented Programming: Polymorphism.

java inheritance presentation

(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.

java inheritance presentation

Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.

java inheritance presentation

Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.

java inheritance presentation

What is inheritance? It is the ability to create a new class from an existing class.

About project

© 2024 SlidePlayer.com Inc. All rights reserved.

404 Not found

inheritance in java

Inheritance in Java

Apr 05, 2019

460 likes | 788 Views

Inheritance in Java. CS 3331 Fall 2009. Outline. Overloading Inheritance and object initialization Subtyping Overriding Hiding. constructor overloading. public class Point { public Point() { /* … */ } public Point(int x, int y) { /* … */ }

Share Presentation

  • color red dynamic bindi
  • subset relationship
  • double distance int
  • different methods
  • public class s

tangia

Presentation Transcript

Inheritance in Java CS 3331 Fall 2009

Outline • Overloading • Inheritance and object initialization • Subtyping • Overriding • Hiding

constructor overloading • public class Point { • public Point() { /* … */ } • public Point(int x, int y) { /* … */ } • public double distance(Point other) { /* … */ } • public double distance(int x, int y) { /* … */ } • public double distance() { /* … */ } • // … • } method overloading Overloading of Methods and Constructors • Def. Overloading The ability to allow different methods or constructors of a class to share the same name.

Overloading (Cont.) • Which overloaded method to invoke? Resolved at compile-time with signature matching, where signature is name and parameter types. • Constructors/Methods Signatures • 1: Point() Point() • 2: Point(int x,int y) Point(int,int) • 3: double distance(Point other) distance(Point) • 4: double distance(int x,int y) distance(int,int) • 5: double distance() distance() • Point p1 = new Point(); // which constructor? • Point p2 = new Point(10,20); • p2.distance(p1); // which method? • p2.distance(20,30); • p2.distance();

When to Overload? When there is a general, nondiscriminative description of the functionality that fits all the overloaded methods. public class StringBuffer { public StringBuffer append(String str) { /* … */ } public StringBuffer append(boolean b) { /* … */ } public StringBuffer append(char c) { /* … */ } public StringBuffer append(int i) { /* … */ } public StringBuffer append(long l) { /* … */ } // … }

When to Overload? (Cont.) When all the overloaded methods offer the same functionality, with some of them providing default arguments. public class String { public String substring(int i, int j) { // base method: return substring from index i to j - 1. } public String substring(int i) { // provide default argument return substring(i, length()); } // … }

Inheritance • Inheritance models the is-a relationship. • If class S extends class T, then all objects of S can act-like an object of T. • Only single inheritance is allowed among classes. • All public and protected members of a superclass are accessible in the subclasses.* *All protected members are also accessible within the package.

Constructors of Subclasses • Can invoke a constructor of the direct superclass. • super(…) must be the first statement. • If the super constructor call is missing, by default the no-arg super() is invoked implicitly. • Can also invoke another constructor of the same class. • this(…) must be the first statement.

this(0,0); Example of “this” Calls public class Point { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public Point() { // default constructor this.x = 0; this.y = 0; } }

Point -x: int -y: int +Point() +Point(x: int, y: int) super(x,y); Example of “super” Calls public class ColoredPoint extends Point { private Color color; public ColoredPoint(int x, int y, Color color) { this.x = x; this.y = y; this.color = color; } public ColoredPoint(int x, int y) { this(x, y, Color.BLACK); // point with default value } public ColoredPoint() { color = Color.BLACK; // what will be the values of x and y? } }

Default Constructor • If no constructor is defined, the following form of no-arg default constructor is automatically generated by the compiler. public ClassName() { super(); } Q. What would be the use of default constructor?

Execution Order of Constructors Rule: Superclass first and field initialization first - Instance variable initializer vs. instance initializer (or initialization block) Example: S x = new S(); public class S extends T { int y = 30; // 3: third public S() { super(); y = 40; // 4: fourth } // ... } public class T { int x = 10; // 1: first public T() { x = 20; // 2: second } // ... }

Exercise • What value will be printed and why? class Super { protected int x = 100; } class Sub extends Super { { x = 200; } public staticvoid main(String[] args) { System.out.println(new Sub().x); } }

Exercise • What are the room number and capacity of the following two objects, respectively? ClassRoom c1 = new ClassRom(100); ClassRoom c2 = new ClassRoom(300, 100); class ClassRoom extends Room { private int capacity = 60; public ClassRoom(int c) { capacity = c; } public ClassRoom(int n, int c) { super(n); } { if (number % 2 == 1) capacity *= 2; } } class Room { private int number = 100; public Room() { this(++nextNum); } public Room(int n) { number = n; } private static int nextNum = 100; static { nextNum += 100; } { number += 2; } }

Outline • Overloading • Inheritance • Subtyping • Overriding • Hiding

Types • What’re types? • Sets of values • Why types? • To statically detect program errors, called type errors. • Typed- vs. untyped-languages (also, static vs. dynamic typing) • Types in Java • Primitive types (e.g., boolean, int, long, etc.) • Classes (e.g., Object, String, etc.) • Interfaces (e.g., Runnable, List, etc.) • Array types (e.g., int[], Object[], List[][], etc.)

Subtyping • What’s subtyping? • Subset relationship among types (e.g., Manager is a subtype (or subset) of Employee) • Subtype’s values are legitimate values of supertypes. • Why subtyping? • Can organizes types into hierarchy, called subype hierarchy • Can extend programs by adding subtypes • Subtyping in Java • Between classes (subclassing) • Between interfaces (subinterfacing) • Between classes and interfaces (implementation or realization) • Between arrays

Substitution Property • Def. Substitution property • A value of subtype can appear where a value of its supertype is expected, e.g., in arguments, results, receivers, and assignments. // 1. argument // public void register(Students); register(new PhDStudent(“Joe”)); // 2. return value public Student find(String name) { // I am lazy, so I am going to return Joe every time. return new PhDStudent(“Joe”); } // 3. receiver of method call // toString in the class Object new PhDStudent(“Joe”).toString();

Substitution Property (Cont.) • Rules of (polymorphic) assignment • The type of expression at the right-hand side of an assignment must be a subtype of the type of the variable at the left-hand side of the assignment. class Student { … } class Undergraduate extends Student { … } class Graduate extends Student { … } Student s1, s2; s1 = new Undergradute(); // polymorphic assignment s2 = new Graudate(); // polymorphic assignment Graduate s3 = s2; // is this OK? Graduate s3 = (Graduate) s2; // explicit casting

Widening and Narrowing • Def. widening and narrowing • The conversion of a subtype to one of its supertype is called widening, and the conversion of a supertype to one of its subtype is called narrowing (or downcasting). // s is a stack of strings Stack s = new Stack(); s.push(“Hello”); // widening: void push(Object) … // Stack defines a method top, i.e., “public Object top()”. s.top().size(); // okay? ((String) s.top()).size(); // downcasting

Overriding Methods • Def. Overriding • Refers to the introduction of an instance method in a subclass that has the same name, signature, and return type of a method declared in the superclass. • Consequences • Implementation of the method in the subclass replaces the implementation of the method in the superclass

Overriding Methods (Cont.) public class T { public void m() { … } } public class S extends T { public void m() { … } } T t = new T(); S s = new S(); t.m(); // invoke m of class T s.m(); // invoke m of class S

Overriding Methods (Cont.) • Dynamic dispatch (binding): The method to be invoked is determined at runtime by the runtime type of the object, not by the declared type (static type). class Student { public int minCredits() { return 12; } … } class GraduateStudent extends Student { public int minCredits() { return 9; } … } Student s; // … s.minCredits(); // which minCredits method?

Overriding Methods (Cont.) • Q. How overriding differ from overloading?

Implementation of Dynamic Binding • Storage structure of instance variables • Class instance records (CIRs) store the state of an object • The CIR for a subclass adds its new fields to the parent CIR. • Dynamic bindings of messages to methods • Virtual Method Tables (VMTs) are used for dynamic binding.

Dynamic Binding (Cont.) class Point { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } } class ColoredPoint extends Point { private Color color; public ColoredPoint(int x, int y, Color c) { super(x, y); color = c; } public Color getColor() { return color; } } CIR for Point x y … CIR for ColoredPoint x y color …

Object.class Point.class p: getX: getY: … super: vmt: … super: vmt: … super: vmt: … ColoredPoint.class class: x: 10 y: 20 color: getColor: … Color.RED Dynamic Binding (Cont.) ColoredPoint p = new ColoredPoint(10,20,Color.RED); p.getColor(); p.getX(); Q: What if getX is overridden in ColoredPoint?

Hiding Fields and Class Methods • Def. Hiding • Refers to the introduction of a field (instance or class) or a class method in a subclass that has the same name as a field or class method declared in the superclass. • Hiding vs. overriding • Statically resolved (bound) at compile-time vs. dynamically dispatched at run-time

hiding of field Example class Student { protected String description = “Student”; public String getDescription() { return description; } } class Undergraduate extends Student { protected String description = “Undergraduate”; } new Student().getDecription(); // what value is returned? new Undergraduate().getDescription(); // what value? Q. How to refer to hidden fields?

  • More by User

Java Classes and Inheritance

Java Classes and Inheritance

Java Classes and Inheritance. Object (again): A computational unit consisting of some data elements to which are associated some specific methods for operating on them. Class: A category of objects having a single formal description in a software system.

414 views • 16 slides

Class Design in Java Overloading 	Programming with Multiple Classes 	Inheritance 	Inheritance and Access Control

Class Design in Java Overloading Programming with Multiple Classes Inheritance Inheritance and Access Control

:: OOP :: Object Oriented Programming Lec10 :: Overloading By Nattapong Songneam http://www.siam2dev.com Information technology Rajabhat pranakhon university. Class Design in Java Overloading Programming with Multiple Classes Inheritance Inheritance and Access Control.

869 views • 60 slides

Multiple Code Inheritance in Java

Multiple Code Inheritance in Java

Multiple Code Inheritance in Java. Maria Cutumisu Supervisors: Duane Szafron, Paul Lu. Outline. Overview Motivation Implementation Validation Syntax Support for Compilation Conclusions. Type Separation Mechanisms in Java. Type. Interface. Class. We want separation of types.

305 views • 17 slides

Some Inheritance Issues in Java

Some Inheritance Issues in Java

Some Inheritance Issues in Java. Inheritance. protected members in Java are visible to the package as well as to subclasses Java: public, private, protected, (default) C++: public, private, protected. Inheritance. We have already mentioned the name collision resolution differences

268 views • 18 slides

Java 212: Inheritance and Polymorphism

Java 212: Inheritance and Polymorphism

Java 212: Inheritance and Polymorphism. Chapter Objectives. Learn about inheritance Learn about subclasses and superclasses Explore how to override (not overload!) the methods of a superclass Examine how constructors of superclasses and subclasses work.

787 views • 59 slides

Inheritance using Java

Inheritance using Java

Inheritance using Java. Terms source: http://www.learn-java-tutorial.com/Java-Inheritance.cfm. Why inheritance?. to model hierarchies found in the real world to allow customization for some features, and have some features that are common to all Also helpful with maintenance

534 views • 9 slides

Inheritance, polymorphism & typing rules in Java – revision

Inheritance, polymorphism & typing rules in Java – revision

Inheritance, polymorphism & typing rules in Java – revision. or: Everything you wanted to know about OOP but were afraid to ask. SOFTENG 251 Object Oriented Software Construction. Who I am. Hong Yul Yang PhD candidate (another one) Software Engineering alumni 2000 – 2003

464 views • 31 slides

Java Unit 11: Inheritance I

Java Unit 11: Inheritance I

Java Unit 11: Inheritance I. What is Inheritance?. Inheritance. All classes in Java are related to each other in a hierarchical way. Except for the class at the top of the hierarchy, which has nothing above it, a class has exactly one class immediately above it in the hierarchy.

361 views • 18 slides

Inheritance in Java

Inheritance in Java. What is inheritance (in Java)?. Inheritance is a mechanism for enhancing existing classes What does that mean…? Defining new classes, which build on the function-ality of existing classes. What is inheritance (in Java)?.

4.87k views • 27 slides

Inheritance in Java

Inheritance in Java. CS 3331. Two Programming Languages Words . Overloading Overriding. Overloading of Methods and Constructors. public class Point { public Point() { /* … */ } public Point(int x, int y) { /* … */ } public double distance(Point other) { /* … */ }

475 views • 30 slides

Abstraction, Inheritance, and Polymorphism in Java

Abstraction, Inheritance, and Polymorphism in Java

Abstraction, Inheritance, and Polymorphism in Java.

452 views • 34 slides

Java Inheritance and Polymorphism

Java Inheritance and Polymorphism

Java Inheritance and Polymorphism. Inheritance. Definitions. A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class).

345 views • 18 slides

Java interface and inheritance

Java interface and inheritance

"For more Classes Visit www.tutorialoutlet.com Java interface and inheritance"

51 views • 3 slides

How do I use inheritance in Java?

How do I use inheritance in Java?

Java class supports reuse through inheritance and composition. This two-part tutorial shows you how to use inheritance in your Java programs. In Part 1, Learn how to use the extends keyword to derive a child from a parent class. In part 2 you will visit java.long.Object, this is the superclass of Java, from which any other class inherits.

116 views • 11 slides

Java Persistence: Object Inheritance Mapping

Java Persistence: Object Inheritance Mapping

Java Persistence: Object Inheritance Mapping. Goals. Be able to map a inheritance relationships between classes to the database using class annotations and ORM descriptors. Objectives. Strategies Single Table Per Class Table per Concrete Class Table per Class (Join) Non-entity inheritance

470 views • 46 slides

Java Classes and Inheritance

173 views • 16 slides

Inheritance in Java

Inheritance in Java Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

885 views • 60 slides

Object Oriented Programming using Java -  Inheritance  Overview

Object Oriented Programming using Java - Inheritance Overview

Department of Computer and Information Science, School of Science, IUPUI. Object Oriented Programming using Java - Inheritance Overview. Dale Roberts, Lecturer Computer Science, IUPUI E-mail: [email protected]. Introduction. Inheritance Software reusability

261 views • 24 slides

Java Inheritance

Java Inheritance

Java Inheritance. What is inherited. A subclass inherits variables and methods from its superclass and all of its ancestors. The subclass can use these members as is, or it can hide the member variables or override the methods. A little more detail.

203 views • 12 slides

Java Inheritance | Java Inheritance Program Example | Java Inheritance Tutorial | Simplilearn

Java Inheritance | Java Inheritance Program Example | Java Inheritance Tutorial | Simplilearn

This presentation on Java Inheritence will give an introduction to the inheritence concept in Java Object-Oriented Programming concepts. In this video, we will understand how to perform inheritence across Java classes using an example of mobile phones. Whether you are an experienced programmer or not, this channel is intended for everyone who wishes to learn Java programming. You will also learn about how to use private variables in a class. And, at the end of the concept, you will see an exciting program so that you will have in-depth knowledge of Java encapsulation. About Simplilearn Java certification training course: If youu2019re looking to master web application development for virtually any computing platform, this Java Certification Training course is for you. This all-in-one Java training will give you a firm foundation in Java, the most commonly used programming language in software development. This advanced Java Certification Training course is designed to guide you through the concepts of Java from introductory techniques to advanced programming skills. The course will provide you with the knowledge of Core Java 8, operators, arrays, loops, methods, and constructors while giving you hands-on experience in JDBC and JUnit framework. Java Certification Course Key Features: 1. 70 hours of blended training 2. Hands-on coding and implementation of two web-based projects 3. Includes Hibernate and Spring frameworks 4. 35 coding-related exercises on Core Java 8 5. Lifetime access to self-paced learning 6. Flexibility to choose classes Eligibility: Simplilearnu2019s Java Certification Training course is ideal for software developers, web designers, programming enthusiasts, engineering graduates, and students or professionals who wish to become Java developers. Pre-requisites: Prior knowledge of Core Java is a prerequisite to taking this advanced Java Certification training course. Our Core Java online self-paced course is available for free to become familiar with the basics of Java programming. Learn more at https://www.simplilearn.com/mobile-and-software-development/java-javaee-soa-development-training

240 views • 12 slides

IMAGES

  1. Explain Different Types of Inheritance in Java

    java inheritance presentation

  2. PPT

    java inheritance presentation

  3. what is inheritance in java programming?

    java inheritance presentation

  4. Types of Inheritance in Java: Single, Multiple, Multilevel, and Hybrid

    java inheritance presentation

  5. Inheritance in Java With Examples

    java inheritance presentation

  6. What is Inheritance in Java with Examples

    java inheritance presentation

VIDEO

  1. JAVA||INHERITANCE

  2. Group 4 Presentation

  3. Preemptive Priority Inheritance Presentation/Real Time and Embedded system course

  4. inheritance java learn coding

  5. inheritance in Java programming #javaprogramming #inharitnce

  6. Inheritance in Java

COMMENTS

  1. Inheritance in JAVA PPT

    Inheritance in JAVA PPT. Nov 24, 2014 • Download as PPTX, PDF •. 39 likes • 36,559 views. P. Pooja Jaiswal. A description on Inheritance in Java (PPT). Presentations & Public Speaking. 1 of 16. Download now.

  2. Guide to Inheritance in Java

    1. Overview. One of the core principles of Object-Oriented Programming - inheritance - enables us to reuse existing code or extend an existing type. Simply put, in Java, a class can inherit another class and multiple interfaces, while an interface can inherit other interfaces. In this article, we'll start with the need for inheritance ...

  3. Java Inheritance Tutorial: explained with examples

    Inheritance is the process of building a new class based on the features of another existing class. It is used heavily in Java, Python, and other object-oriented languages to increase code reusability and simplify program logic into categorical and hierarchical relationships. However, each language has its own unique way of implementing ...

  4. PPT

    Presentation Transcript. Inheritance in Java Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object. 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 ...

  5. Inheritance in Java

    It is the mechanism in Java by which one class is allowed to inherit the features (fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from another class can reuse the methods and fields of that class. In addition, you can add new fields and methods to your current ...

  6. PPT

    Inheritance vs. Interfaces • One quite important difference between inheritance and interfaces: • A class can implement multiple interfaces • A class can only extend one class • There is no such thing as multiple inheritance in Java…. • Multiple inheritance has issues, taken out of Java to keep things simple RHS - SOC.

  7. Inheritance In Java

    A. Arnab Bhaumik. A Presentation On Inheritance In Java. Software. 1 of 18. Download Now. Download to read offline. Inheritance In Java - Download as a PDF or view online for free.

  8. Inheritance in Java

    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.

  9. Java Inheritance (Subclass and Superclass)

    In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories: subclass (child) - the class that inherits from another class. superclass (parent) - the class being inherited from. To inherit from a class, use the extends keyword.

  10. PPT CS 1311

    CS 1311. Inheritance. Introduction In real situations either when modeling real world objects such as vehicles, animals, etc. or when modeling abstract data structures such as queues, stacks, collections, windows, menu boxes the structure of different object families can be viewed as a kind of "family" tree. Java like most OO languages allows ...

  11. OOP Series: Inheritance in Java

    Undegraduate.java first starts at the class declaration by extending/inheriting from the Student class using the extends keyword.extends is a keyword in Java we use to implement inheritance and it can only extend one class since Java only supports single inheritance. The program continued by declaring an instance field and then declaring the constructor with parameters.

  12. INHERITANCE IN JAVA.

    Download ppt "INHERITANCE IN JAVA." Inheritance in Java Mechanism of deriving new class from old class. The old class is known as- Base Class / Super class / Parent Class The new class is known as- Derived class/ Sub Class / Child class Types: Single Inheritance Multilevel Inheritance Multiple inheritance Hierarchical Inheritance.

  13. Java Inheritance: Types, Access Specifiers, 'This' & 'Final ...

    Presentation of Inheritance in Java.pptx - Free download as Powerpoint Presentation (.ppt / .pptx), PDF File (.pdf), Text File (.txt) or view presentation slides online. The document discusses inheritance in Java. It defines inheritance as a mechanism where a subclass acquires properties and behaviors of a superclass. It describes different types of inheritance like single, multilevel, and ...

  14. PPT

    140 likes | 203 Views. Java Inheritance. What is inherited. A subclass inherits variables and methods from its superclass and all of its ancestors. The subclass can use these members as is, or it can hide the member variables or override the methods. A little more detail. Download Presentation. class. base class.

  15. Java Inheritance.

    Presentation on theme: "Java Inheritance."— Presentation transcript: 1 Java Inheritance. 2 What is inherited A subclass inherits variables and methods from its superclass and all of its ancestors. The subclass can use these members as is, or it can hide the member variables or override the methods. ...

  16. Java Inheritance

    Java Inheritance - Free download as Powerpoint Presentation (.ppt), PDF File (.pdf), Text File (.txt) or view presentation slides online. Inheritance is the one important topics of Object oriented programming

  17. PPT

    Basic concepts in Java - Object-oriented programming (OOPs) basic in Support Object-oriented software: as the name implies, Object-Oriented Programming or OOPs refers to languages that use objects in programming. Object-oriented design goal for real-world entities, such as inheritance, to hide, to implement polyvalence, etc. is the programming.

  18. PPT

    Java Inheritance and Polymorphism. Inheritance. Definitions • A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class). Classes can be derived from classes that are derived ...

  19. Java Inheritance

    Java Inheritance. May 16, 2021 • Download as PPTX, PDF •. 0 likes • 100 views. Manish Tiwari. Follow. This is a small presentation for inheritance in Java. Education. 1 of 12. Download now.

  20. PPT

    Presentation Transcript. Java Inheritance. Inheritance • On the surface, inheritance is a code re-use issue. • we can extend code that is already written in a manageable manner. • Inheritance is more • it supports polymorphism at the language level.

  21. PPT

    Outline • Overloading • Inheritance and object initialization • Subtyping • Overriding • Hiding. Inheritance • Inheritance models the is-a relationship. • If class S extends class T, then all objects of S can act-like an object of T. • Only single inheritance is allowed among classes. • All public and protected members of a ...