Results 1 to 5 of 5
- 05-15-2011, 05:52 AM #1
Member
- Join Date
- May 2011
- Posts
- 1
- Rep Power
- 0
Help - How the inheritance of java works?
I have a question regarding the inheritance in Java. Suppose I have the following:
public class Parent {
public void printALetter() {System.out("Parent A");}
}
public class Child1 extends Parent {
public void printALetter() {System.out("Child1 A")};
}
public class Child2 extends Parent {
public void printALetter() {System.out("Child2 A")};
}
now I want to declare a variable of type Parent that can be assigned to either Child1 or Child2.
Parent p;
Child1 c1 = new Child1();
Child2 c2 = new Child2();
p = c1;
p.printALetter() // does this print out Child1 A
p = c2;
p.printALetter() // does this print out Child2 A
Somehow in my program both times it prints out Parent.
which is not what I want.
Basically I want to have a collection of either Child1 and Child2.
and in my program, I will just need to get assign any one of them
to a Parent reference, so it will call the method I want it too.
AM I Making sense?
Any help is appreciated.
ftc
-
Show your program as it should and does print out Child ...
- 05-15-2011, 06:19 AM #3
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
You should be using System.out.println. This should work polymorphically as you want since all the classes override the method. Perhaps someone else can say why this isn't working.
- 05-15-2011, 01:00 PM #4
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,413
- Blog Entries
- 7
- Rep Power
- 17
When people rob a bank they get a penalty; when banks rob people they get a bonus.
- 05-15-2011, 01:13 PM #5
Output:Java Code:class Parent { public void printALetter() { System.out.println("Parent A"); } } class Child1 extends Parent { public void printALetter() { System.out.println("Child1 A"); } } class Child2 extends Parent { public void printALetter() { System.out.println("Child2 A"); } } public class IT { public static void main(String[] args) { Parent p; Child1 c1 = new Child1(); Child2 c2 = new Child2(); p = c1; p.printALetter(); // does this print out Child1 A p = c2; p.printALetter(); // does this print out Child2 A } }
Works on my Java-installation.Java Code:Child1 A Child2 A
Similar Threads
-
Help with java gui and inheritance
By sssss in forum Advanced JavaReplies: 8Last Post: 01-19-2011, 04:38 AM -
Source works in NetBeans but not with java/javac (commandline)
By Jacsoft3 in forum NetBeansReplies: 0Last Post: 10-05-2009, 11:25 PM -
Java chat program, works on single PC, but not over internet?
By rolls in forum NetworkingReplies: 7Last Post: 03-31-2009, 01:29 PM -
What are the hot java frames works on demand
By mallaravi in forum Web FrameworksReplies: 1Last Post: 10-28-2008, 01:34 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks