With the relationship, a child can access the parent's methods and fields with the child's class ability to create its own methods and attributes.
See the program below for the sample program.
[+/-] show/hide
import javax.swing.*;
public class SampleInheritance{
public static void main (String args[]){
String numstring1=JOptionPane.showInputDialog("Input a number");
int mynum1=Integer.parseInt(numstring1);
Parent1 obj1=new Parent1();
obj1.setnum(mynum1);
obj1.square();
obj1.cube();
System.out.println("Last number result from parent methods: "+obj1.getnum());
String numstring2=JOptionPane.showInputDialog("Input a number");
int mynum2=Integer.parseInt(numstring2);
Child1 obj2=new Child1();
obj2.setnum(mynum2);
obj2.square();
obj2.cube();
obj2.nth();
System.out.println("Last number result with parent and child methods: "+obj2.getnum());
}
}
class Parent1{
int num;
void setnum(int x)
{num=x;}
void square()
{num=num*num;
}
void cube()
{num =num*num*num;
}
int getnum()
{return num;}
}
class Child1 extends Parent1{
void nth()
{ num=num/2;}
}
No comments:
Post a Comment