public class ExampleTester { public static void main(String args[]) { Example my
ID: 3666499 • Letter: P
Question
public class ExampleTester {
public static void main(String args[])
{ Example myExample = new Example1();
myExample.printer(5);
//myExample.anotherPrinter(3);
myExample = new Example2();
myExample.printer(5);
myExample = new Example();
myExample.printer(5); } }
public class Example {
public void printer(int y){
System.out.println("inside Ex y="+y);
}
}
public class Example1 extends Example{
public void printer(int y){
System.out.println("inside Ex1 y="+y);
}
public void anotherPrinter(int y){
System.out.println("anotherPrinter::inside Ex1 y="+y);
}
}
public class Example2 extends Example{
public void printer(int y){
System.out.println("inside Ex2 y="+y);
}
}
What is this code about?
Explanation / Answer
The above program out put is bellow:
Onc executing the program you will get the following result
inside Ex1 y=5
inside Ex2 y=5
inside Ex y=5
extends Keyword:
extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends keyword.
class Super{
.....
.....
}
class Sub extends Super{
.....
.....
}
IS-A Relationship:
Let us see how the extends keyword is used to achieve inheritance.
class Example {
public void printer(int y)
{
System.out.println("inside Ex y="+y);
}
}
class Example1 extends Example{
public void printer(int y)
{
System.out.println("inside Ex1 y="+y);
}
public void anotherPrinter(int y)
{
System.out.println("anotherPrinter::inside Ex1 y="+y);
}
}
class Example2 extends Example
{
public void printer(int y)
{
System.out.println("inside Ex2 y="+y);
}
}
Now, based on the above example, In Object Oriented terms, the following are
Example is the superclass of Example1 class.
Example is the superclass of Example2 class.
Example1 and Example2 are subclasses of Example class.
Now, if we consider the IS-A relationship, we can say
Example1 IS-A Example
Example2 IS-A Example
With use of the extends keyword the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.