• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Liutauras Vilda
  • Knute Snortum
  • Bear Bibeault
Sheriffs:
  • Devaka Cooray
  • Jeanne Boyarsky
  • Junilu Lacar
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • salvin francis
Bartenders:
  • Tim Holloway
  • Piet Souris
  • Frits Walraven

Subclass

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Star extends Object {
Star(){
System.out.println("Star");
}
Star(String s1){
super();
System.out.println(s1+"is a Star");}

Star(String s2, String s3){
this("Mervury");
System.out.println(s2+"and"+s3+" are also Stars");}

public static void main(String[] args){
Sun sun=new Sun();
Sun sun1=new Sun("Venus");
Sun sun2= new Sun("Mars", "Eaarth");
}
}
class Sun extends Star{
public Sun(){System.out.println("Star Wars1");
}
public Sun(String v1){ super(v1,"Saturn");
System.out.println("Star Wars2");}
public Sun (String v2, String v3){
if (v2.substring(0,v2.length()).length()>v3.length())
System.out.println("Mission to Mars");
else
System.out.println("Earth");
}
}
For the above code, the answer of compiling the code will be:
1. Star
2.Star Wars1
3.Mercury is a star
4.Venus and Saturn are also star
5.Star Wars2
6.Star
7. Earth
My question is, when compile the third constructor in subclass Sun, Sun sun2= new Sun("Mars", "Earth"); why the line 6 Star get print out?
Thanks for attention
 
Author
Posts: 121
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello!
Your third constructor of Sun does not start with an "super();", so it is implicitly inserted by the compiler, so your constructor looks like:

This super() calls the constructor Star(), which prints out "Star". By the way, inserting an "super(v2, v3);" at the start of your thrird constructor of Sun would enforce executing the Star(String, String)-constructor. Perhaps this is what you expected.
Greetings from Euroland,
Stefan
 
Ranch Hand
Posts: 2676
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A good test on this is to remove the Star() constructor but leave the other two constructors in the Star class. When you try to compile the Sun class you will receive a compiler error because there is no matching constructor in Star.
 
Tongue wrestling. It's not what you think. And here, take this tiny ad. You'll need it.
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!