Can we call sub class methods using super class object

  • Common coding interview question everybody facing in interviews is can we call sub class method using super class object? or can we call child class method using parent class? or can a super class call a subclass' method.
  • The answer is No. but still we can say yes. so we need to what are all those scenarios of calling sub class method from super class and lets discuss about which is the actual possible case to call sub class method using super class object.
  • Before that let me explain what is inheritance and how the super and sub classes related each other.
Can we call sub class methods using super class object.png

Inheritance:

  •  Getting the properties from one class object to another class object is known as inheritance.
  • Two types of inheritance
  • Getting the properties from one class object to another with level wise and with some priorities is known as multilevel inheritance.
  • Getting the properties from one class object to another class object with same priority is known as multiple inheritance
  • Java does not supports multiple inheritance
Read this:

Why Java does not supports multiple inheritance

Creating super class object and calling methods

  1. //Multilevel inheritance program
  2. Class A{
  3.  
  4. int a;
  5.  
  6. public void print(){
  7.  
  8. System.out.println("print method of super class A"); 

  9. }
  10.  
  11. }
  12. Class B extends A{
  13.  
  14. public void show(){
  15.  
  16.  System.out.println("show method of sub class B"); 

  17. }
  18. public static void main(String[] args){
  19.   
  20. A obj= new A();
  21. obj.a=10;
  22.  
  23. obj.print();
  24.  //obj.show(); // compile time error

  25.  System.out.println("a="obj.a); 

  26. }
  27. }



Output:
  1. print method of super class  A
  2. 10

  • In above program super class and sub class is there and sub class extending super class.
  • But we created object for super class so we can call only super class methods on that object.
  • If we create sub class object we can call super class and sub class methods on that object now we can able to access super class A methods only.
  • So by creating super class object we can call only super class methods

Creating super class object and calling methods

  1. //Multilevel inheritance program
  2. Class A{
  3.  
  4. int a;
  5.  
  6. public void print(){
  7.  
  8. System.out.println("print method of super class A"); 

  9. }
  10.  
  11. }
  12. Class B extends A{
  13.  
  14. public void show(){
  15.  
  16.  System.out.println("show method of sub class B"); 

  17. }
  18. public static void main(String[] args){
  19.   
  20. B obj= new B();
  21. obj.a=10;
  22.  
  23. obj.print();
  24. obj.show();

  25.  System.out.println("a="obj.a); 

  26. }
  27. }

Output:
  1. print method of super class  A
  2. show method of sub class B
  3. 10


  • Above program shows sub class object using super class methods and variables as we said in inheritance concept all super class members can accessed by the sub class means all super class members are available to sub class if sub class extending super class.
  • So whenever we create object of sub class it will call sub class constructor and from sub class constructor super class constructor will be called so memory will be allocated to all super class non static member and sub class non static members.
  • So we can call super class methods using sub class.
  • B obj= new B();
  • obj.print();
  • So by creating sub class object we can call both super class methods and sub class methods.


 Assigning sub class reference to super class object.

  1. //Multilevel inheritance program
  2. Class A{
  3.  
  4. int a;
  5.  
  6. public void print(){
  7.  
  8. System.out.println("print method of super class A"); 

  9. }
  10.  
  11. }
  12. Class B extends A{
  13.  
  14. public void show(){
  15.  
  16.  System.out.println("show method of sub class B"); 

  17. }
  18. public static void main(String[] args){
  19.   
  20. A obj= new B();
  21. obj.a=10;
  22.  
  23. obj.print();
  24. //obj.show(); // compile time error

  25.  System.out.println("a="obj.a); 

  26. }
  27. }

Output:
  1. print method of super class  A
  2. 10


  • Yes we can assign sub class object to super class reference.
  • So here Sub class object is created so memory allocated to all super class members
  • so can we call all methods ?  No eventhough sub class object is created we can not call sub class methods because we assigned sub class object to super class reference.
  • Then how its possible to call sub class methods?
  • Yes its possible to call sub class methods using super class by type casting to sub class object .
  • By type casting super class object to sub class object we can access all corresponding sub class and all super class methods on that reference.


 Assigning sub class reference to super class object.

  1. //Multilevel inheritance program
  2. Class A{
  3.  
  4. int a;
  5.  
  6. public void print(){
  7.  
  8. System.out.println("print method of super class A"); 

  9. }
  10.  
  11. }
  12. Class B extends A{
  13.  
  14. public void show(){
  15.  
  16.  System.out.println("show method of sub class B"); 

  17. }
  18. public static void main(String[] args){
  19.   
  20. A obj= new B();
  21. obj.a=10;
  22.  
  23. obj.print();
  24. //obj.show();   compile time error
  25. ((B)obj).show(); // works fine


  26.  System.out.println("a="obj.a); 

  27. }
  28. }

Output:
  1. print method of super class  A
  2. show method of sub class B
  3. 10

 Assigning sub class reference to super class object. We can call sub class methods if overridden

Otherwise we need to typecast to call sub class methods

  1. //Multilevel inheritance program
  2. Class A{
  3.  
  4. int a;
  5.  
  6. public void print(){
  7.  
  8. System.out.println("print method of super class A"); 

  9. }
  10.  
  11. }
  12. Class B extends A{
  13.  
  14. public void show(){
  15.  
  16.  System.out.println("show method of sub class B"); 

  17. }
  18. public void print(){
  19.  
  20. System.out.println("Print method of Sub class B"); 

  21. }
  22.  
  23. public static void main(String[] args){
  24.   
  25. A obj= new B();
  26. obj.a=10;
  27.  
  28. obj.print(); // print method is overridden in sub class so it will execute sub class method.
  29. //obj.show();   compile time error
  30. ((B)obj).show(); // works fine


  31.  System.out.println("a="obj.a); 

  32. }
  33. }

Output:
  1. Print method of Sub class B
  2. show method of sub class B
  3. 10

Static class in java

  • Yes we can create a class as static. But class should be inner class or nested class.
  • We know how to create static methods, static variables and static blocks.
  • As Java Supports defining a class within a class we can create a static inner class inside a class.
  • This inner static class inside a class can access static members of outer class even its private.

Java Program to create static inner class:


  1. package instanceofjavaTutorial;
  2.  
  3. public class Outer{ 
  4.  
  5.   static class inner{
  6.  
  7. public void print(){
  8.  
  9. System.out.println("static inner class method called");
  10.  
  11. }
  12.  
  13. }
  14.  
  15. public static void main(String args[]){
  16.  
  17. Outer.inner in= new Outer.innner();
  18.  
  19. in.print();
  20.  
  21. }

Output:

  1. static inner class method called



Static inner class accessing outer class static variable:

  1. package instanceofjavaTutorial;
  2.  
  3. public class Outer{ 
  4.  static int a=10;
  5.   static class inner{
  6.  
  7. public void print(){
  8.  
  9. System.out.println(a);
  10.  
  11. }
  12.  
  13. }
  14.  
  15. public static void main(String args[]){
  16.  
  17. Outer.inner in= new Outer.innner();
  18.  
  19. in.print();
  20.  
  21. }

Output:

  1. 10

  • In java there are two types of nested classes one is static and another one is non static nested classes.
  • We saw static classes in java lets see what will be there in non static nested classes.
Non-static nested class(inner class)
  1. Member inner class
  2. Anonymous inner class
  3. Local inner class

  • A class is defined within a class and outside of methods of that class known as member inner class.
  • Anonymous inner class is a inner class which does not have a name and whose instance is created at the time creating class itself.
  • A class which is defined inside a method of another class known as local inner class

Click here for more information about inner classes

Java Versions, Features and History


Java Versions, Features and History

  • Released on 23 January 1996, JDK 1.0 version.
  • Released on 19 February 1997 JDK 1.1 version.
    New features in JDK 1.1
    1. JDBC (Java Database Connectivity)
    2. Inner Classes
    3. Java Beans
    4. RMI (Remote Method Invocation)
    5. Reflection (introspection only)
  • Released on 8 December 1998 J2SE 1.2 version.
    New features in J2SE 1.2
    1. Collections framework.
    2. Java String memory map for constants.
    3. Just In Time (JIT) compiler.
    4. Jar Signer for signing Java ARchive (JAR) files.
    5. Policy Tool for granting access to system resources.
    6. Java Foundation Classes (JFC) which consists of Swing 1.0, Drag and Drop, and Java 2D class libraries.
    7. Java Plug-in
    8. Scrollable result sets, BLOB, CLOB, batch update, user-defined types in JDBC.
    9. Audio support in Applets.
  • Released on 8 May 2000 J2SE 1.3 version.
    New features in J2SE 1.3
    1. Java Sound
    2. Jar Indexing
    3. A huge list of enhancements in almost all the java area.
  • Released on 6 February 2002 J2SE 1.4 version.
    New features in J2SE 1.4
    1. XML Processing
    2. Java Print Service
    3. Logging API
    4. Java Web Start
    5. JDBC 3.0 API
    6. Assertions
    7. Preferences API
    8. Chained Exception
    9. IPv6 Support
    10. Regular Expressions
    11. Image I/O API
  • Released on 30 September 2004 J2SE 1.5 version.
    New features in J2SE 1.5
    1. Generics
    2. Enhanced for Loop
    3. Autoboxing/Unboxing
    4. Enum
    5. Varargs
    6. Static Import
    7. Metadata (Annotations)
    8. Instrumentation
  • Released on 11 December 2006 J2SE 1.6 version.
    New features in J2SE 1.6
    1. Scripting Language Support
    2. JDBC 4.0 API
    3. Java Compiler API
    4. Pluggable Annotations
    5. Native PKI, Java GSS, Kerberos and LDAP support.
    6. Integrated Web Services.
    7. Lot more enhancements.
  • Released on 28 July 2011 J2SE 1.7 version.
    New features in J2SE 1.7
    1. Strings in switch Statement
    2. Type Inference for Generic Instance Creation
    3. Multiple Exception Handling
    4. Support for Dynamic Languages
    5. Try with Resources
    6. Java nio Package
    7. Binary Literals, underscore in literals
    8. Diamond Syntax
    9. Automatic null Handling


  • Released on 18th march 2014 JDK 1.8 version.
    New features in JDK 1.8
           

  1. Default and Static methods in Interface
  2. Lambda Expressions
  3. Optional
  4. Streams
  5. Method References
  6. Data Time API
  7. Nashorn Javascript Engine
  8. Parallel Arrays

Can we overload static methods in java

  • Yes. We can overload static methods in java.
  • Method overriding is not possible but method overloading is possible for static methods.
  • Before that lets see about method overloading in java.

Method overloading:

  •  Defining multiple methods with same name and with different arguments is known as method overloading.
  • Multiple methods with same name and different arguments so compile time itself we can tell which method is going to get executed based on method call.
  • Method overloading also known as compile time polymorphism. 

Static methods - method overloading 

  • Its always possibles static method overloading.
  • Defining multiple static methods with same name and different arguments will possible.
  • By this we can define multiple main methods in our class with different arguments but only default main method will be called by the JVM remaining methods we need to call explicitly.
  • Lets see an example java program which explains static method overloading.

  1. class StaticMethodOverloading{
  2.  
  3. public static void staticMethod(){
  4.  
  5. System.out.println("staticMethod(): Zero arguments");
  6.  
  7.  
  8. public static void staticMethod(int a){
  9.  
  10. System.out.println("staticMethod(int a): one argument");
  11.  
  12.  
  13. public static void staticMethod(String str, int x){
  14.  
  15. System.out.println("staticMethod(String str, int x): two arguments");
  16.  
  17. }
  18.  
  19. public static void main(String []args){
  20.   
  21.   StaticMethodOverloading.staticMethod();
  22.   StaticMethodOverloading.staticMethod(12);
  23.   StaticMethodOverloading.staticMethod("Static method overloading",10);
  24.  
  25. }
  26. }


 Output:

  1. staticMethod(): Zero arguments
  2. staticMethod(int a): one argument
  3. staticMethod(String str, int x): two arguments


Java Program to overload main method in java

  1. class mainMethodOverloading{
  2.  
  3. public static void main(boolean x){
  4.  
  5. System.out.println("main(boolean x) called ");
  6.  
  7.  
  8. public static void main(int x){
  9.  
  10. System.out.println("main(int x) called");
  11.  
  12.  
  13. public static void main(int a, int b){
  14.  
  15. System.out.println("main(int a, int b) called");
  16.  
  17. }
  18.  
  19. public static void main(String []args){
  20.    
  21.  
  22. System.out.println("main(String []args) called ");
  23.  
  24.   mainMethodOverloading.main(true);
  25.   mainMethodOverloading.main(10);
  26.  mainMethodOverloading.main(37,46);
  27.  
  28.  
  29. }
  30. }




 Output:

  1. main(String []args) called
  2. main(boolean x) called
  3. main(int x) called
  4. main(int a, int b) called

Can we override static methods in java

  • Exact answer is NO. We can not override static methods.
  • Before discussing this topic lets see what is static in java. 

Static methods in java:

  •  Static means class level if we declare any data or method as static then those data(variables) and methods belongs to that class at class level.
  • Static variables and static methods belongs to class level.
  • Static methods are not the part of objects state . Belongs to class
  • Without using object we can call these static methods.
 here the detailed explanation on static methods

Instance methods in java:


  • Instance methods will be called at run time.
  • Instance variables and instance methods are object level. variables values may change from one object to another where as static variable values are class level so if we access by using any object and changes that values will effect to all objects means its class level variable.
  •  Lets see about overriding in java.

Method overriding in java:


  •  Defining the super class method in sub class with same signature.
  • Even though in inheritance all properties of supers class can access in sub class we have an option of overriding super class methods in sub class known as method overriding.
  • So by this every-time sub-most object method will be called.

Instance methods - Method Overriding

  
  1. class SuperClassDemo{
  2.  
  3. public void instanceMethod(){
  4.  
  5. System.out.println("SuperClassDemo instanceMethodcalled");
  6.  
  7. }
  8.  
  9. }

  1. class SubClassDemo extends SuperClassDemo{
  2.  
  3. public void instanceMethod(){
  4.  
  5. System.out.println("SubClassDemo instanceMethod called");
  6.  
  7. }
  8. public static void main(String []args){
  9.   
  10.   SuperClassDemo superObj= new SuperClassDemo();
  11.   SuperClassDemo  superobj1= new  SubClassDem(); 
  12.   SubClassDemo subObj= new  SubClassDem(); 
  13.   // here no need to create object to call a static method please note that.

  14.   superObj.instanceMethod();
  15.   superObj1.instanceMethod();
  16.   subObj.instanceMethod();
  17.  
  18. }
  19. }

Output

  1. SuperClassDemo instanceMethodcalled
  2. SubClassDemo instanceMethodcalled
  3. SubClassDemo instanceMethodcalled

 Static methods - method overriding:

  • Lest an example program on static methods in method overriding concept and then discus about this clearly.
  1. class SuperClassDemo{
  2.  
  3. public static void staticMethod(){
  4.  
  5. System.out.println("SuperClassDemo staticMethod called");
  6.  
  7. }
  8.  
  9. }

  1. class SubClassDemo extends SuperClassDemo{
  2.  
  3. public static void staticMethod(){
  4.  
  5. System.out.println("SubClassDemo staticMethod called");
  6.  
  7. }
  8. public static void main(String []args){
  9.   
  10.   SuperClassDemo superObj= new SuperClassDemo();
  11.   SuperClassDemo  superobj1= new  SubClassDem(); 
  12.   SubClassDemo subObj= new  SubClassDem(); 
  13.   // here no need to create object to call a static method please note that.

  14.   superObj.staticMethod();
  15.   superObj1.staticMethod();
  16.   subObj.staticMethod();
  17.  
  18. }
  19. }



Output

  1. SuperClassDemo staticMethod called
  2. SuperClassDemo staticMethod called
  3. SubClassDemo staticMethod called

 Method Overriding - Method Hiding:

  • Method overriding : in method overriding we will define super class method in sub class with same signature and these methods will be called at run time based on the object.
  • Method Hiding: In method hiding even though super class methods are accesible in sub class they are not the part of sub class so the methods and these methods will be called based on the class.
  • In method Hiding if we define same static method in super class and sub class they are not same they are unique and distinct from the other.



Return type / return statement in java example

Return type in java: return statement in java

  • Basically return type is used in java methods.
  • Method signature includes this return type.
  • public int show(){ // }
  • we will use methods to do a particular task after completion of task if we want to return something to the calling place these return types will be used.
  • Based on the type of data to be returned will mention it as int , char , float double etc as return type in method signature and return statement should be the last statement of the method body.
  • In Java, the return statement is used to exit a method and return a value to the calling method. The value returned can be of any data type that is specified in the method's return type. 
  • For example, if a method has a return type of int, it can return an integer value. Here's an example of a simple method that uses the return statement to return an int value:


public int add(int a, int b) {
    int sum = a + b;
    return sum;
}

  • In this example, the add method takes two int parameters, a and b, and returns the sum of the two values. The method uses the return statement to return the value of the sum variable back to the calling method.
  • You can also use return statement without returning any value, in this case method should have void return type.


public void printHelloWorld() {
    System.out.println("Hello, World!");
    return;
}

  • In this case the method printHelloWorld doesn't return any value and the calling method doesn't need to assign the return to any variable, just invoking the method will do the job.
  • It is also worth noting that when a return statement is executed, it immediately exits the current method, regardless of where it is in the method's execution flow. So, any code after a return statement will not be executed.

Type of declaration of methods based on return type and arguments:

1.Method with out return type  and without arguments: return statement in java


  1. package com.instanceofjava;
  2. class sample{
  3.  
  4. public void add(){
  5.  
  6. int a=40;
  7. int b=50;
  8. int c=a+b;
  9. System.out.println(c);
  10.  
  11. }

  12. public static void main(String args[]) // ->method prototype.
  13.  
  14. sample obj= new sample();
  15. obj.add();
  16.  
  17.  
  18.  }
  19. }

2.Method with out return type and with arguments.

  1. package com.instanceofjava;
  2. class sample{
  3.  
  4. public void add(int a, int b){
  5.  
  6. int c=a+b;
  7. System.out.println(c);
  8.  
  9. }

  10. public static void main(String args[]) // ->method prototype.
  11.  
  12. sample obj= new sample();
  13. obj.add(13,24);
  14.  
  15.  
  16.  }
  17. }

3.Method with return type  and without arguments.


  1. package com.instanceofjava;
  2. class sample{
  3.  
  4. public int add(){
  5. int a=40;
  6. int b=50;
  7. int c=a+b;
  8. return c;
  9. }

  10. public static void main(String args[]) // ->method prototype.
  11.  
  12. sample obj= new sample();
  13. int x=obj.add(); 
  14. System.out.println(x);
  15.  
  16.  }
  17. }

4.Method with return type and with arguments.

 

  1. package com.instanceofjava;
  2. class sample{
  3.  
  4. public int add(int a, int b){
  5.  
  6. int c=a+b;
  7. return c;
  8. }

  9. public static void main(String args[]) // ->method prototype.
  10.  
  11. sample obj= new sample();
  12.  
  13. int x=obj.add(1,2);
  14. System.out.println(x);
  15.  
  16.  }
  17. }


Select Menu