Overriding Problem/Example




//basic

public class poly1 { // only one class can be public

 public static void main(String args[]) {

  
  child1 c1=  new child1(2,1,"child 1 ");
  c1.showw();
 }

}

class Base { // /base class or parent class

 static int index=1; // /class variable it cann't be instance of objects
 int a;
 int b;

 Base(int a, int b) {
  this.a = a;
  this.b = b;
 }

 static void setIndex() {
  index++;
  System.out.println("the index is "+index);
 }

 void show() {
  //setIndex();
  System.out.println( a+" "+b);
   }

}

class child1 extends Base { // /Syntax to inherit only extends to one parent
       // Multiple inheritance not allowed in java
 String name;

 child1(int a, int b, String name) {
  super(a, b); // /super should place at top of child constructor if
      // parent class has a constructor
  this.name = name;
 }

 void show() {                                   // /overriding
  super.show();                               
  System.out.println("The name is " + name); 
 }

}
More:Link
Problem :While overriing we can,t call the same method inside it which is overdided..
to do so use Super.Method();

0 comments:

Post a Comment

My Instagram