[Go to site: main page, start]

0% found this document useful (0 votes)
25 views10 pages

Java Inheritance and Super Keyword Examples

The document contains examples of inheritance in Java. It demonstrates how to extend classes and access properties and methods of parent classes from child classes using the super keyword. It also shows overriding and overloading methods.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views10 pages

Java Inheritance and Super Keyword Examples

The document contains examples of inheritance in Java. It demonstrates how to extend classes and access properties and methods of parent classes from child classes using the super keyword. It also shows overriding and overloading methods.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

class Teacher {

//fields of parent class


String designation = "Teacher";
String collegeName = "DCS UBIT";

//method of parent class


void does(){
[Link]("Teaching");
}
}

public class PhysicsTeacher extends Teacher{


//field of child class
String mainSubject = "Physics";
public static void main(String args[]){
PhysicsTeacher obj = new PhysicsTeacher();
//accessing the fields of parent class
[Link]([Link]);
[Link]([Link]);

[Link]([Link]);

//accessing the method of parent class


[Link]();
}
}

Instaneof example:

class A{
}
class B extends A{
}
public class JavaExample extends B{
public static void main(String args[]) {
A obj1 = new A();
B obj2 = new B();
JavaExample obj3 = new JavaExample();
[Link](obj1 instanceof A);
[Link](obj2 instanceof A);
[Link](obj1 instanceof B);
[Link](obj3 instanceof B);
}
}

Inheritance: Access Specifiers Example


class Teacher {
private String designation = "Teacher";
private String collegeName = "Beginnersbook";
public String getDesignation() {
return designation;
}
protected void setDesignation(String designation) {
[Link] = designation;
}
protected String getCollegeName() {
return collegeName;
}
protected void setCollegeName(String collegeName) {
[Link] = collegeName;
}
void does(){
[Link]("Teaching");
}
}

public class JavaExample extends Teacher{


String mainSubject = "Physics";
public static void main(String args[]){
JavaExample obj = new JavaExample();
/* Note: we are not accessing the data members
* directly we are using public getter method
* to access the private members of parent class
*/
[Link]([Link]());
[Link]([Link]());
[Link]([Link]);
[Link]();
}
}

Super keyword: Inherentance Example

class ParentClass{
//Parent class constructor
ParentClass(){
[Link]("Constructor of Parent");
}
}
class JavaExample extends ParentClass{
JavaExample(){
/* It by default invokes the constructor of parent class
* You can use super() to call the constructor of parent.
* It should be the first statement in the child class
* constructor, you can also call the parameterized constructor
* of parent class by using super like this: super(10), now
* this will invoke the parameterized constructor of int arg
*/
[Link]("Constructor of Child");
}
public static void main(String args[]){
//Creating the object of child class
new JavaExample();
}
}

Inheritance: Method Overloading

class ParentClass{
//Parent class constructor
ParentClass(){
[Link]("Constructor of Parent");
}
void disp(){
[Link]("Parent Method");
}
}
class JavaExample extends ParentClass{
JavaExample(){
[Link]("Constructor of Child");
}
void disp(){
[Link]("Child Method");
//Calling the disp() method of parent class
[Link]();
}
public static void main(String args[]){
//Creating the object of child class
JavaExample obj = new JavaExample();
[Link]();
}
}

Super Keyword in Java Examples

//Parent class or Superclass or base class


class Superclass
{
int num = 100;
}
//Child class or subclass or derived class
class Subclass extends Superclass
{
/* The same variable num is declared in the Subclass
* which is already present in the Superclass
*/
int num = 110;
void printNumber(){
[Link](num);
}
public static void main(String args[]){
Subclass obj= new Subclass();
[Link]();
}
}
Now accessing the num variable of parent class:
class Superclass
{
int num = 100;
}
class Subclass extends Superclass
{
int num = 110;
void printNumber(){
/* Note that instead of writing num we are
* writing [Link] in the print statement
* this refers to the num variable of Superclass
*/
[Link]([Link]);
}
public static void main(String args[]){
Subclass obj= new Subclass();
[Link]();
}
}

2) Use of super keyword to invoke constructor of parent class

class Parentclass
{
Parentclass(){
[Link]("Constructor of parent class");
}
}
class Subclass extends Parentclass
{
Subclass(){
/* Compile implicitly adds super() here as the
* first statement of this constructor.
*/
[Link]("Constructor of child class");
}
Subclass(int num){
/* Even though it is a parameterized constructor.
* The compiler still adds the no-arg super() here
*/
[Link]("arg constructor of child class");
}
void display(){
[Link]("Hello!");
}
public static void main(String args[]){
/* Creating object using default constructor. This
* will invoke child class constructor, which will
* invoke parent class constructor
*/
Subclass obj= new Subclass();
//Calling sub class method
[Link]();
/* Creating second object using arg constructor
* it will invoke arg constructor of child class which will
* invoke no-arg constructor of parent class automatically
*/
Subclass obj2= new Subclass(10);
[Link]();
}
}
Output:

Constructor of parent class


Constructor of child class
Hello!
Constructor of parent class
arg constructor of child class
Hello!

Parameterized super() call to invoke parameterized constructor of parent class

class Parentclass
{
//no-arg constructor
Parentclass(){
[Link]("no-arg constructor of parent class");
}
//arg or parameterized constructor
Parentclass(String str){
[Link]("parameterized constructor of parent class");
}
}
class Subclass extends Parentclass
{
Subclass(){
/* super() must be added to the first statement of constructor
* otherwise you will get a compilation error. Another important
* point to note is that when we explicitly use super in constructor
* the compiler doesn't invoke the parent constructor automatically.
*/
super("Hahaha");
[Link]("Constructor of child class");

}
void display(){
[Link]("Hello");
}
public static void main(String args[]){
Subclass obj= new Subclass();
[Link]();
}
}
Output:

parameterized constructor of parent class


Constructor of child class
Hello

3) How to use super keyword in case of method overriding


class Parentclass
{
//Overridden method
void display(){
[Link]("Parent class method");
}
}
class Subclass extends Parentclass
{
//Overriding method
void display(){
[Link]("Child class method");
}
void printMsg(){
//This would call Overriding method
display();
//This would call Overridden method
[Link]();
}
public static void main(String args[]){
Subclass obj= new Subclass();
[Link]();
}
}

Output:
Child class method
Parent class method

What if the child class is not overriding any method: No need of super

class Parentclass
{
void display(){
[Link]("Parent class method");
}
}
class Subclass extends Parentclass
{
void printMsg(){
/* This would call method of parent class,
* no need to use super keyword because no other
* method with the same name is present in this class
*/
display();
}
public static void main(String args[]){

Subclass obj= new Subclass();


[Link]();
}
}

Example 3: super Keyword in Inheritance


class Animal {

// method in the superclass


public void eat() {
[Link]("I can eat");
}
}

// Dog inherits Animal


class Dog extends Animal {

// overriding the eat() method


@Override
public void eat() {
// call method of superclass
[Link]();
[Link]("I eat dog food");
}

// new method in subclass


public void bark() {
[Link]("I can bark");
}
}

class Main {
public static void main(String[] args) {

// create an object of the subclass


Dog labrador = new Dog();

// call the eat() method


[Link]();
[Link]();
}
}

Example 4: protected Members in Inheritance


class Animal {
protected String name;

protected void display() {


[Link]("I am an animal.");
}
}

class Dog extends Animal {

public void getInfo() {


[Link]("My name is " + name);
}
}

class Main {
public static void main(String[] args) {

// create an object of the subclass


Dog labrador = new Dog();

// access protected field and method


// using the object of subclass
[Link] = "Rocky";
[Link]();

[Link]();
}
}

Inheritance Example:

class Calculation {
int z;

public void addition(int x, int y) {


z = x + y;
[Link]("The sum of the given numbers:"+z);
}

public void Subtraction(int x, int y) {


z = x - y;
[Link]("The difference between the given numbers:"+z);
}
}

public class My_Calculation extends Calculation {


public void multiplication(int x, int y) {
z = x * y;
[Link]("The product of the given numbers:"+z);
}

public static void main(String args[]) {


int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
[Link](a, b);
[Link](a, b);
[Link](a, b);
}
}
Inheritance Example”
class Superclass {
int age;

Superclass(int age) {
[Link] = age;
}

public void getAge() {


[Link]("The value of the variable named age in super class is: " +age);
}
}

public class Subclass extends Superclass {


Subclass(int age) {
super(age);
}

public static void main(String args[]) {


Subclass s = new Subclass(24);
[Link]();
}
}

Inheritance Example:

class Animal {
}

class Mammal extends Animal {


}

class Reptile extends Animal {


}

public class Dog extends Mammal {

public static void main(String args[]) {


Animal a = new Animal();
Mammal m = new Mammal();
Dog d = new Dog();

[Link](m instanceof Animal);


[Link](d instanceof Mammal);
[Link](d instanceof Animal);
}
}

Common questions

Powered by AI

The 'super' keyword is used in a subclass to access fields in the superclass that are hidden due to field name collision with the subclass. When a field in a subclass shares a name with a field in its superclass, it hides the superclass’s field. By using 'super.fieldName', the subclass can explicitly refer to and access the hidden superclass field. This is crucial for retrieving or manipulating superclass state when the same-named subclass field shadows those fields, thereby managing the object state effectively without unintended overwrites or losses .

Protected members in a superclass are accessible within subclasses even if they reside in different packages. This visibility means that subclass methods can access and modify these fields directly, providing more flexible interaction with superclass state and behavior compared to private members. This allows the subclass to build on the parent class's functionality while enforcing encapsulation within the package structure. Access to protected members from non-subclass and non-package members is restricted, maintaining a controlled exposure of class internals .

Inheritance in Java promotes code reusability by allowing new classes to inherit fields and methods from existing classes, reducing redundancy and enhancing maintainability. By extending a superclass, a subclass can use and augment its behavior and attributes without rewriting the code. This also supports extensibility, as classes can be extended to introduce new functionalities or modify existing ones, leveraging shared codebases. This promotes a modular design approach, facilitating adjustments and scalability in software development, which is particularly beneficial in large programs involving complex hierarchies .

Method overloading occurs when multiple methods with the same name but different parameter lists are defined within a class or its subclass. It allows the same method name to perform different tasks based on parameter input. Inheritance supports overloading by allowing subclasses to define overloaded methods in addition to inheriting from their hierarchy. Unlike method overriding, where a subclass provides a specific implementation of a method defined in its superclass, overloading doesn't change any existing method's behavior and is resolved at compile time, determined by the method signature used, not runtime object type .

Access specifiers in Java such as private, protected, and public determine the accessibility of class members within a class hierarchy. Private members are accessible only within the class they're declared in, making them inaccessible in any subclass or outside this class. Protected members are accessible in the subclass and within the same package, allowing subclass methods to utilize these members directly. Public members are accessible from any other class. This impacts how class members can be inherited and modified, ensuring encapsulation and controlled abstraction .

Method overriding in Java allows a subclass to provide a specific implementation for a method that is already defined in its superclass, thereby supporting dynamic polymorphism. This means that at runtime, the JVM determines the method implementation to invoke based on the object type, rather than the reference type, allowing objects to be treated as instances of their parent class while using subclass methods. Inheritance facilitates this by establishing a class hierarchy where subclasses inherit methods from their parents. This polymorphic behavior allows for flexible and reusable code, letting methods operate differently for different object instances while adhering to a common interface or abstract class .

The 'super' keyword in Java is used to call the parent class’s methods that have been overridden in the subclass. This allows a subclass to retain and reuse the overridden functionality from the parent class as needed. When a subclass overrides a method, it often completely replaces the parent method's functionality. Using 'super' enables programmers to explicitly invoke the overridden method in the parent, ensuring the inherited method can be utilized alongside new subclass behavior. This is crucial when subclass functionality needs to extend rather than replace parent behavior .

The 'instanceof' operator in Java checks whether an object is an instance of a specific class or any of its superclasses/interfaces, allowing runtime verification of object types. This is particularly useful in abstract or polymorphic designs where objects can be of more than one type. 'instanceof' ensures type safety by confirming an object's type before performing any operations specific to that type, preventing class cast exceptions and ensuring stable polymorphic interactions. It provides insights into the actual class type and hierarchy relationship of objects during execution, crucial for type-aware logic in dynamic systems .

Calling an overloaded constructor in the parent class using 'super' is important to initialize the parent class variables correctly and ensure that any necessary setup defined in the parent class constructor is executed before the child class operations. When omitted, the compiler implicitly calls the parent's no-argument constructor, which can lead to a compilation error if a no-arg constructor is not defined. This ensures the parent class state is correctly set, adhering to object-oriented principles of consistent and predictable object initialization across inheritance hierarchies .

In Java, if a subclass constructor does not explicitly call a superclass constructor using 'super()', the Java compiler automatically inserts a call to the superclass's no-argument constructor at the beginning of the subclass constructor. This implicit call ensures that the instance is initialized in the correct order, with the subclass inheriting the initialized state of the superclass, unless explicitly defined otherwise. This behavior underlies the object construction chain in Java, which ensures proper initialization and hierarchy consistency, especially in simple inheritance cases where superclass constructors don't require specific parameters .

You might also like