What is parent and child class in java

Asked By 25 points N/A Posted on -
qa-featured

What is parent and child class in Java and how to declare it?

Can you show me a sample codes?

SHARE
Best Answer by Schneider Matthew
Answered By 0 points N/A #103659

What is parent and child class in java

qa-featured

A child class is inherited from a parent class.

This means that some data elements and operations of the parent class also exist in the inherited child class.

The child class can have some extra elements and operations.

Two or more children can be formed from a parent class.

Objects created out of the parent class only access the entities of the parent class itself.

Parent classes have no information about the child classes formed.

However,the child classes can use the inherited components as well as the elements and members of itself.

The nature of inheritability is defined in the parent class itself, which states that only selected members of the class can be inherited (eg: public, protected etc.)

Best Answer
Best Answer
Answered By 0 points N/A #195499

What is parent and child class in java

qa-featured

Hi Noah Baker,

Java is an object oriented programming language and one of the features of OOP is Inheritance that is to extend the features of something that is already available. It is used to enhance reusability of code.

Here, one class inherits the properties of another class using the keyword "extends". The class from which one class derives properties is called a Parent class and the class which derives the property is called a Child/Sub class.

In java, the extended properties can be the data members and the member functions of the parent class.

There are 2 types of inheritance in java.

Simple and Multi level.

Please see the below example which shows Inheritance in Java.

Simple Inheritance

class Parent {

  int par;

  int get(int x){

  par=x; 

  return(0);

  }

  void Show(){

  System.out.println(par);

  }

}

 

class Child extends Parent{

  public static void main(String args[]){

  Parent parent = new Parent();

  parent.get(5);

  parent.Show();

  }

  void display(){

  System.out.println("This is child class");

  }

}

 

 

 

Multi level Inheritance

 

class MainParent {

  int mPar;

  int get(int x){

  mPar=x;

  return(0);

  }

  void Show(){

  System.out.println(mPar);

  }

}

class SubParent extends MainParent{

  void ShowSubParent(){

  System.out.println("I am the sub parent");

  }

}

 

class Child extends SubParent{

  void display(){

  System.out.println("I am the child");

  }

  public static void main(String args[]){

  MainParent mainParent = new MainParent();

  mainParent.get(5);

  mainParent.Show();

  }

}

 

 

Hope it helps.

Related Questions