Online Java Compiler - Online Java Editor - Java Code Online [Link]
com/online-java-compiler
Font Size: 12px
[Link]
1 // Parent class
2 class Parent { This program can be used for following
3 // Data member
4 private String name;
concepts:
5 * inheritance concept (only single
6 // Constructor inheritance)
7 Parent(String name) {
8 [Link] = name; * super keyword
9 } * final keyword
10 * method overriding
11 // Method to be overridden
12 void display() { * constructors in inheritance
13 [Link]("Inside Parent class");
14 }
15
16 // Final method that cannot be overridden
17 final void finalMethod() {
18 [Link]("Final method in Parent class");
19 }
20 }
21
22 // Child class inheriting from Parent class
23 class Child extends Parent {
24 // Data member
25 private int age;
26
27 // Constructor
28 Child(String name, int age) {
29 super(name); // Call to Parent class constructor
30 [Link] = age;
31 }
32
33 // Method overriding
34 @Override
35 void display() {
36 [Link]("Inside Child class");
37 }
38
39 // Method using super keyword to call parent method
40 void callParentDisplay() {
41 [Link](); // calling parent's display method
42 }
43 }
44
45 public class InheritanceExample {
46 public static void main(String[] args) {
47 // Creating objects of Parent and Child classes
48 Parent parent = new Parent("John");
49 Child child = new Child("Alice", 10);
50
51 // Demonstrate method overriding
52 [Link](); // calls display() method of Parent class
53 [Link](); // calls display() method of Child class
54
55 // Demonstrate using super keyword
56 [Link](); // calls display() method of Parent class using super
57
58 // Demonstrate final method
59 [Link](); // calls final method of Parent class
60 // [Link](); // Error: Cannot override final method
61 }
62 }
63
Share feedback
1 of 2 13-03-2024, 04:08 pm
Online Java Compiler - Online Java Editor - Java Code Online [Link]
External Libraries Upload Files Input Output JDroid
Inside Parent class
Inside Child class
Inside Parent class
Final method in Parent class
CPU Time: | Memory: |
Compiled and & executed in
No files generated
Facebook Twitter Email LinkedIn Copy Link
LEAVE A REVIEW ON
Product Hunt
2 of 2 13-03-2024, 04:08 pm