Java Program Which has 2 Classes Which Initializes a String in Its Constructor

«
»
This is a Java Program Which has two Classes Which Initializes a String in Its Constructor.

Constructor is used to initialise an object. Here we made two classes as Super and Sub class using Inheritance. We initialise two different strings in the constructors of these two classes and with the help of object of Sub class we print these strings.

Here is the source code of the Java Program Which has two Classes Which Initializes a String in Its Constructor. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

advertisement
  1. class String_Initialise
  2. {
  3.     String a, b;
  4.     public String_Initialise()
  5.     {
  6.         System.out.println("Base Class Constructor");
  7.         a = "String from Base Class";
  8.     }
  9. }
  10. public class String_Initialise1 extends String_Initialise
  11. {
  12.    public String_Initialise1()
  13.     {
  14.         System.out.println("Derived Class Constructor");
  15.         b = "String from Derived Class";
  16.     }
  17.     public static void main(String... arg) 
  18.     {
  19.         String_Initialise1 obj = new String_Initialise1();
  20.         System.out.println("the strings initialised in the constructors of Base and Derived classes are :");
  21.         System.out.println(obj.a +" and "+obj.b);
  22.     }
  23. }

Output:

$ javac String_Initialise1.java
$ java String_Initialise1
 
Base Class Constructor
Derived Class Constructor
the strings initialised in the constructors of Base and Derived classes are :
String from Base Class and String from Derived Class

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement

Here’s the list of Best Reference Books in Java Programming, Data Structures and Algorithms.

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn