Question :

What is the syntax of Java Inheritance? Explain with example.

Subject

Java

Standard

Class 10

Views

931

Asked By

Prisha

Alexandria
Answer / Solution

The syntax of Java Inheritance is 

class Subclass-name extends Superclass-name
{
   //methods and fields
}
  • The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality.
  • In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or subclass.

In this example, we have a base class Teacher and a sub class PhysicsTeacher. Since class PhysicsTeacher extends the designation and college properties and work() method from base class, we need not to declare these properties and method in sub class.

Here we have collegeName, designation and work() method which are common to all the teachers so we have declared them in the base class, this way the child classes like MathTeacher, MusicTeacher and PhysicsTeacher do not need to write this code and can be used directly from base class.

class Teacher {
   String designation = "Teacher";
   String collegeName = "Pacific Polytechnic";
   void does(){
    System.out.println("Teaching");
   }
}

public class PhysicsTeacher extends Teacher{
   String mainSubject = "Physics";
   public static void main(String args[]){
    PhysicsTeacher obj = new PhysicsTeacher();
    System.out.println(obj.collegeName);
    System.out.println(obj.designation);
    System.out.println(obj.mainSubject);
    obj.does();
   }
}

Output of the above program is:
Pacific Polytechnic 
Teacher
Physics
Teaching

Recent Question Update

Advantages Of NCERT, CBSE & State Boards Solutions For All Subjects

  • All the NCERT Solutions have been prepared by academic experts having 10+ years of teaching experience.
  • They have prepared all the solutions in simple and easy language so that each and every student can understand the concepts easily.
  • All the solutions have been explained step to step-wise in details with better explanations.
  • Students can also use these question and answers for your assignments and in homework help.
  • All the solutions have been explained in detail and the answers have been compiled in a step-wise manner.
  • All the questions and answers are commonly prepared according to the Latest Syllabus of Board Education and Guidelines.
  • Students can know about the various types of questions asked in the exams with the help of these solutions.

Top Course Categories