• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 16:16
CEST 22:16
KST 05:16
  • Home
  • Forum
  • Calendar
  • Streams
  • Liquipedia
  • Features
  • Store
  • EPT
  • TL+
  • StarCraft 2
  • Brood War
  • Smash
  • Heroes
  • Counter-Strike
  • Overwatch
  • Liquibet
  • Fantasy StarCraft
  • TLPD
  • StarCraft 2
  • Brood War
  • Blogs
Forum Sidebar
Events/Features
News
Featured News
[ASL19] Finals Recap: Standing Tall9HomeStory Cup 27 - Info & Preview18Classic wins Code S Season 2 (2025)16Code S RO4 & Finals Preview: herO, Rogue, Classic, GuMiho0TL Team Map Contest #5: Presented by Monster Energy6
Community News
Flash Announces Hiatus From ASL63Weekly Cups (June 23-29): Reynor in world title form?13FEL Cracov 2025 (July 27) - $8000 live event22Esports World Cup 2025 - Final Player Roster16Weekly Cups (June 16-22): Clem strikes back1
StarCraft 2
General
Program: SC2 / XSplit / OBS Scene Switcher The SCII GOAT: A statistical Evaluation Statistics for vetoed/disliked maps Weekly Cups (June 23-29): Reynor in world title form? PiG Sty Festival #5: Playoffs Preview + Groups Recap
Tourneys
FEL Cracov 2025 (July 27) - $8000 live event RSL: Revival, a new crowdfunded tournament series Sparkling Tuna Cup - Weekly Open Tournament WardiTV Mondays Korean Starcraft League Week 77
Strategy
How did i lose this ZvP, whats the proper response Simple Questions Simple Answers
Custom Maps
[UMS] Zillion Zerglings
External Content
Mutation # 481 Fear and Lava Mutation # 480 Moths to the Flame Mutation # 479 Worn Out Welcome Mutation # 478 Instant Karma
Brood War
General
Player “Jedi” cheat on CSL Flash Announces Hiatus From ASL BW General Discussion SC uni coach streams logging into betting site Practice Partners (Official)
Tourneys
[BSL20] Non-Korean Championship 4x BSL + 4x China The Casual Games of the Week Thread CSL Xiamen International Invitational [BSL20] Grand Finals - Sunday 20:00 CET
Strategy
Simple Questions, Simple Answers I am doing this better than progamers do.
Other Games
General Games
Path of Exile Stormgate/Frost Giant Megathread Nintendo Switch Thread What do you want from future RTS games? Beyond All Reason
Dota 2
Official 'what is Dota anymore' discussion
League of Legends
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Heroes of StarCraft mini-set
TL Mafia
TL Mafia Community Thread Vanilla Mini Mafia
Community
General
Russo-Ukrainian War Thread US Politics Mega-thread Summer Games Done Quick 2025! Trading/Investing Thread Things Aren’t Peaceful in Palestine
Fan Clubs
SKT1 Classic Fan Club! Maru Fan Club
Media & Entertainment
Anime Discussion Thread [Manga] One Piece [\m/] Heavy Metal Thread
Sports
Formula 1 Discussion 2024 - 2025 Football Thread NBA General Discussion TeamLiquid Health and Fitness Initiative For 2023 NHL Playoffs 2024
World Cup 2022
Tech Support
Computer Build, Upgrade & Buying Resource Thread
TL Community
Blogs
Culture Clash in Video Games…
TrAiDoS
from making sc maps to makin…
Husyelt
Blog #2
tankgirl
StarCraft improvement
iopq
Trip to the Zoo
micronesia
Customize Sidebar...

Website Feedback

Closed Threads



Active: 556 users

[Java] Brain teaser!

Blogs > Qzy
Post a Reply
Normal
Qzy
Profile Blog Joined July 2010
Denmark1121 Posts
September 22 2010 15:57 GMT
#1
Okay, my uni-teacher likes to give out small brain teasers, to think about. I'm pretty good with java, but this one I couldn't solve - so please do give a hint, if anyone does know the answer!

TAStudent ta; //Extends student
PhDStudent phd; //Extends TAStudent
Student student;

In TAStudent display() { System.out.println(“I am a TA”); }
In PhDStudent display() { System.out.println(“I am a PhD student”); }
In Student display() { System.out.println(“I am a regular student”); }

student = phd; // line 1
student.display(); // line 2

Modify, if necessary, line 1 in order to get the call to display() in line 2 run the method in the base class.

I guess they want us to outprint "I am a regular student"?

***
TG Sambo... Intel classic! Life of lively to live to life of full life thx to shield battery
Cambium
Profile Blog Joined June 2004
United States16368 Posts
September 22 2010 16:00 GMT
#2
use [code] tags please.
When you want something, all the universe conspires in helping you to achieve it.
Cambium
Profile Blog Joined June 2004
United States16368 Posts
Last Edited: 2010-09-22 16:05:19
September 22 2010 16:02 GMT
#3
On September 23 2010 00:57 Qzy wrote:
Okay, my uni-teacher likes to give out small brain teasers, to think about. I'm pretty good with java, but this one I couldn't solve - so please do give a hint, if anyone does know the answer!

TAStudent ta = new TAStudent(); //Extends student
PhDStudent phd = new PhDStudent(); //Extends TAStudent
Student student = new Student(); //assuming Student is not abstract

In TAStudent display() { System.out.println(“I am a TA”); }
In PhDStudent display() { System.out.println(“I am a PhD student”); }
In Student display() { System.out.println(“I am a regular student”); }

student = phd; // line 1
student.display(); // line 2

Modify, if necessary, line 1 in order to get the call to display() in line 2 run the method in the base class.

I guess they want us to outprint "I am a regular student"?


I don't really get the question, must you assign something to student? Otherwise, if you comment out line 1, you'd get exactly what you are looking for? If you can't comment it out, you can just do

student = student;
When you want something, all the universe conspires in helping you to achieve it.
Qzy
Profile Blog Joined July 2010
Denmark1121 Posts
September 22 2010 16:09 GMT
#4
On September 23 2010 01:02 Cambium wrote:
Show nested quote +
On September 23 2010 00:57 Qzy wrote:
Okay, my uni-teacher likes to give out small brain teasers, to think about. I'm pretty good with java, but this one I couldn't solve - so please do give a hint, if anyone does know the answer!

TAStudent ta = new TAStudent(); //Extends student
PhDStudent phd = new PhDStudent(); //Extends TAStudent
Student student = new Student(); //assuming Student is not abstract

In TAStudent display() { System.out.println(“I am a TA”); }
In PhDStudent display() { System.out.println(“I am a PhD student”); }
In Student display() { System.out.println(“I am a regular student”); }

student = phd; // line 1
student.display(); // line 2

Modify, if necessary, line 1 in order to get the call to display() in line 2 run the method in the base class.

I guess they want us to outprint "I am a regular student"?


I don't really get the question, must you assign something to student? Otherwise, if you comment out line 1, you'd get exactly what you are looking for? If you can't comment it out, you can just do

student = student;


It had to be cast, or method call - can't change ie student = student.
TG Sambo... Intel classic! Life of lively to live to life of full life thx to shield battery
fabiano
Profile Blog Joined August 2009
Brazil4644 Posts
September 22 2010 16:10 GMT
#5

public class Student
{
public void display()
{
System.out.println("I am a regular student.");
}
}

public class TAStudent extends Student
{
public void display()
{
System.out.println("I am a TA.");
}
}

public class PhDStudent extends TAStudent
{
public void display()
{
System.out.println("I am a PhD student.");
}
}

TAStudent ta;
PhDStudent phd;
Student student;

student = phd;
student.display();


This way is easier to picture the whole.
Im short on time, gotta get the bus in 5 minutes, so I will be trying to help more when I get to my University, if no one has answered yet.
"When the geyser died, a probe came out" - SirJolt
Qzy
Profile Blog Joined July 2010
Denmark1121 Posts
September 22 2010 16:15 GMT
#6
I'll just this line in (it's an extra line i didn't paste)

"Whatever modification you perform, be it a casting, another method call, etc., the
variable student MUST appear on the left side of the statement and the variable
phd MUST appear on the right side of the same statement."
TG Sambo... Intel classic! Life of lively to live to life of full life thx to shield battery
LastWish
Profile Blog Joined September 2004
2013 Posts
September 22 2010 16:24 GMT
#7
Ok I'm more of a C# programmer, so I might be wrong.
However in C# you must use virtual and override keywords to make inheritance work for methods properly.
So if the same applies for Java, then there is no need to modify line 1 - the program is correct.
The student.display() always calls the base method no matter which class it was instanced to.
- It's all just treason - They bring me down with their lies - Don't know the reason - My life is fire and ice -
NoUShutUp
Profile Joined January 2008
United States172 Posts
September 22 2010 16:30 GMT
#8
Hmm... I remember having something like this in my class a year ago. I'm not sure if I'm right but here is my thought process.

During compile time, Java only checks to see if types are valid and if there is a method call for that type. This means during compile time it checks to see if a Student can be a PhDStudent in line 1 and if the class Student has a display method. I am pretty sure both lines are valid.

During runtime in line 1, you are trying to store a PhDStudent into a Student. (This is where it gets iffy for me). I think you can cast phd to Student so then the variable student will be treated as a Student. Then when it calls on student.display(). It will recognize that student is still Student type and call on the base display method.
Qzy
Profile Blog Joined July 2010
Denmark1121 Posts
September 22 2010 16:31 GMT
#9
On September 23 2010 01:24 LastWish wrote:
Ok I'm more of a C# programmer, so I might be wrong.
However in C# you must use virtual and override keywords to make inheritance work for methods properly.
So if the same applies for Java, then there is no need to modify line 1 - the program is correct.
The student.display() always calls the base method no matter which class it was instanced to.


Yeah usually you write a @override, but that's not the point . The methods _are_ overridden Nicely spotted tho, sir!
TG Sambo... Intel classic! Life of lively to live to life of full life thx to shield battery
Cambium
Profile Blog Joined June 2004
United States16368 Posts
September 22 2010 16:31 GMT
#10
On September 23 2010 01:24 LastWish wrote:
Ok I'm more of a C# programmer, so I might be wrong.
However in C# you must use virtual and override keywords to make inheritance work for methods properly.
So if the same applies for Java, then there is no need to modify line 1 - the program is correct.
The student.display() always calls the base method no matter which class it was instanced to.


Java methods allow override by default.
When you want something, all the universe conspires in helping you to achieve it.
Cambium
Profile Blog Joined June 2004
United States16368 Posts
September 22 2010 16:37 GMT
#11
On September 23 2010 01:30 NoUShutUp wrote:
Hmm... I remember having something like this in my class a year ago. I'm not sure if I'm right but here is my thought process.

During compile time, Java only checks to see if types are valid and if there is a method call for that type. This means during compile time it checks to see if a Student can be a PhDStudent in line 1 and if the class Student has a display method. I am pretty sure both lines are valid.

During runtime in line 1, you are trying to store a PhDStudent into a Student. (This is where it gets iffy for me). I think you can cast phd to Student so then the variable student will be treated as a Student. Then when it calls on student.display(). It will recognize that student is still Student type and call on the base display method.


PhDStudent is a subclass of Student, regardless whether the phd object is casted to Student or TAStudent, the instance will always be of the PhD class. This is the underlying principle of polymorphism.
When you want something, all the universe conspires in helping you to achieve it.
Cambium
Profile Blog Joined June 2004
United States16368 Posts
Last Edited: 2010-09-22 16:48:19
September 22 2010 16:47 GMT
#12
As far as I know, there is no way to invoke Student's display method through the phd object.

This is what I would do:


student = phd == null ? student : student;

It satisfies the requirement of having student on the left side of the = operator, and phd on the right.

You might also be able to do something tricky with reflection by using the phd object to get the Student class's full name.
When you want something, all the universe conspires in helping you to achieve it.
Logo
Profile Blog Joined April 2010
United States7542 Posts
Last Edited: 2010-09-22 16:48:57
September 22 2010 16:47 GMT
#13
Probably cheating but...
student = phd.getClass().getSuperClass().getSuperClass().newInstance();

though as written it seems impossible/pointless because phd is null so you'd just use the logic of phd == null ?... explained in the post above mine.
Logo
AcrossFiveJulys
Profile Blog Joined September 2005
United States3612 Posts
September 22 2010 16:50 GMT
#14
as someone above said, either comment out the first line, or if you need to keep it as student = phd, you can do something cute like

student = (phd.super(phd)).super(phd);
gale_f0rce
Profile Joined June 2009
United States9 Posts
September 22 2010 16:51 GMT
#15
Isn't it just

student = (Student)phd;

Seems really simple
Qzy
Profile Blog Joined July 2010
Denmark1121 Posts
September 22 2010 16:52 GMT
#16
On September 23 2010 01:50 AcrossFiveJulys wrote:
student = (phd.super(phd)).super(phd);


Okay, give me like 1 hour to figure out what the heck that does :D
TG Sambo... Intel classic! Life of lively to live to life of full life thx to shield battery
Qzy
Profile Blog Joined July 2010
Denmark1121 Posts
September 22 2010 16:54 GMT
#17
On September 23 2010 01:51 gale_f0rce wrote:
Isn't it just

student = (Student)phd;

Seems really simple


Nooo, that would just throw out "I'm a phd student" .
TG Sambo... Intel classic! Life of lively to live to life of full life thx to shield battery
Cambium
Profile Blog Joined June 2004
United States16368 Posts
September 22 2010 16:55 GMT
#18
On September 23 2010 01:47 Logo wrote:
Probably cheating but...
student = phd.getClass().getSuperClass().getSuperClass().newInstance();


I like this, except you have to fight Java generics to get it working properly!
When you want something, all the universe conspires in helping you to achieve it.
gale_f0rce
Profile Joined June 2009
United States9 Posts
September 22 2010 17:00 GMT
#19
On September 23 2010 01:54 Qzy wrote:
Show nested quote +
On September 23 2010 01:51 gale_f0rce wrote:
Isn't it just

student = (Student)phd;

Seems really simple


Nooo, that would just throw out "I'm a phd student" .


No, the variable student is now of type Student, since (Student)phd is of type Student. This means that calling student.display() prints “I am a regular student.”
Logo
Profile Blog Joined April 2010
United States7542 Posts
Last Edited: 2010-09-22 17:05:04
September 22 2010 17:02 GMT
#20
On September 23 2010 02:00 gale_f0rce wrote:
Show nested quote +
On September 23 2010 01:54 Qzy wrote:
On September 23 2010 01:51 gale_f0rce wrote:
Isn't it just

student = (Student)phd;

Seems really simple


Nooo, that would just throw out "I'm a phd student" .


No, the variable student is now of type Student, since (Student)phd is of type Student. This means that calling student.display() prints “I am a regular student.”


It doesn't work like that =/. The reference to the object thinks it's a student, but the object itself is still a phd student.

Put it like this if you had
PhdStudent phd = new PhdStudent();
Student s = (Student)phd;
phd.displayName();

What would the 3rd line put out? Clearly not "I Am a regular student". Yet Both line 1 and line 2 point to the same object so how could they have different outputs.
Logo
NoUShutUp
Profile Joined January 2008
United States172 Posts
September 22 2010 17:02 GMT
#21
New idea... just type it into a java compiler and test it out >_>
Cambium
Profile Blog Joined June 2004
United States16368 Posts
Last Edited: 2010-09-22 17:10:00
September 22 2010 17:04 GMT
#22
On September 23 2010 01:55 Cambium wrote:
Show nested quote +
On September 23 2010 01:47 Logo wrote:
Probably cheating but...
student = phd.getClass().getSuperClass().getSuperClass().newInstance();


I like this, except you have to fight Java generics to get it working properly!


Going along with Logo's idea, the problem is that you need to add a try/catch block or make your caller method throw an Exception.


public class Runner {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
Student student = new Student();
@SuppressWarnings("unused")
TAStudent ta = new TAStudent();
PhDStudent phd = new PhDStudent();

student = ((Class<Student>) ((Class<TAStudent>) ((Class<PhDStudent>) phd
.getClass()).getSuperclass()).getSuperclass()).newInstance();
student.display();
}
}



Output:

I am a regular student.


Reflection is such a hack =\
When you want something, all the universe conspires in helping you to achieve it.
Cambium
Profile Blog Joined June 2004
United States16368 Posts
September 22 2010 17:04 GMT
#23
On September 23 2010 02:02 NoUShutUp wrote:
New idea... just type it into a java compiler and test it out >_>


logo's right; it's the basic principles of polymorphism.
When you want something, all the universe conspires in helping you to achieve it.
Qzy
Profile Blog Joined July 2010
Denmark1121 Posts
Last Edited: 2010-09-22 17:31:50
September 22 2010 17:31 GMT
#24
On September 23 2010 02:04 Cambium wrote:
Show nested quote +
On September 23 2010 01:55 Cambium wrote:
On September 23 2010 01:47 Logo wrote:
Probably cheating but...
student = phd.getClass().getSuperClass().getSuperClass().newInstance();


I like this, except you have to fight Java generics to get it working properly!


Going along with Logo's idea, the problem is that you need to add a try/catch block or make your caller method throw an Exception.


public class Runner {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
Student student = new Student();
@SuppressWarnings("unused")
TAStudent ta = new TAStudent();
PhDStudent phd = new PhDStudent();

student = ((Class<Student>) ((Class<TAStudent>) ((Class<PhDStudent>) phd
.getClass()).getSuperclass()).getSuperclass()).newInstance();
student.display();
}
}



Output:

I am a regular student.


Reflection is such a hack =\


Wont work.. Im getting the exception. What does reflection do?


TAStudent ta = new TAStudent("1");
PhDStudent phd = new PhDStudent("2");
Student student = new Student("2");
try {
student = ((Class<Student>) ((Class<TAStudent>) ((Class<PhDStudent>) phd.getClass()).getSuperclass()).getSuperclass()).newInstance();
student.display();
} catch (IllegalAccessException ex) {
Logger.getLogger(PhDStudent.class.getName()).log(Level.SEVERE, null, ex);
}


TG Sambo... Intel classic! Life of lively to live to life of full life thx to shield battery
NoUShutUp
Profile Joined January 2008
United States172 Posts
September 22 2010 17:42 GMT
#25
On September 23 2010 02:04 Cambium wrote:
Show nested quote +
On September 23 2010 02:02 NoUShutUp wrote:
New idea... just type it into a java compiler and test it out >_>


logo's right; it's the basic principles of polymorphism.


I know it is... it just bugs me cause I don't remember :p
FreeZEternal
Profile Joined January 2003
Korea (South)3396 Posts
September 22 2010 17:44 GMT
#26
student = true ? student : phd;
Qzy
Profile Blog Joined July 2010
Denmark1121 Posts
Last Edited: 2010-09-22 17:51:46
September 22 2010 17:51 GMT
#27
On September 23 2010 02:44 FreeZEternal wrote:
student = true ? student : phd;


Read whole thread... . student and phd needs to be on the left and right side, respectively.
TG Sambo... Intel classic! Life of lively to live to life of full life thx to shield battery
zcxvbn
Profile Joined August 2009
United States257 Posts
September 22 2010 18:10 GMT
#28
On September 23 2010 01:52 Qzy wrote:
Show nested quote +
On September 23 2010 01:50 AcrossFiveJulys wrote:
student = (phd.super(phd)).super(phd);


Okay, give me like 1 hour to figure out what the heck that does :D


It doesn't compile
NA: proberecall
Slithe
Profile Blog Joined February 2007
United States985 Posts
September 22 2010 18:34 GMT
#29
On September 23 2010 02:51 Qzy wrote:
Show nested quote +
On September 23 2010 02:44 FreeZEternal wrote:
student = true ? student : phd;


Read whole thread... . student and phd needs to be on the left and right side, respectively.


I see at least one instance of student on the left and one instance of phd on the right. Isn't that what the rule is saying? Unless you u saying that student cannot be on the right hand side at all?
Qzy
Profile Blog Joined July 2010
Denmark1121 Posts
September 22 2010 18:48 GMT
#30
On September 23 2010 03:34 Slithe wrote:
Show nested quote +
On September 23 2010 02:51 Qzy wrote:
On September 23 2010 02:44 FreeZEternal wrote:
student = true ? student : phd;


Read whole thread... . student and phd needs to be on the left and right side, respectively.


I see at least one instance of student on the left and one instance of phd on the right. Isn't that what the rule is saying? Unless you u saying that student cannot be on the right hand side at all?


I think the point is to apply the object address to student-variable, and then some how call the objects super-super-method .
TG Sambo... Intel classic! Life of lively to live to life of full life thx to shield battery
Cambium
Profile Blog Joined June 2004
United States16368 Posts
September 22 2010 20:17 GMT
#31
On September 23 2010 02:31 Qzy wrote:
Show nested quote +
On September 23 2010 02:04 Cambium wrote:
On September 23 2010 01:55 Cambium wrote:
On September 23 2010 01:47 Logo wrote:
Probably cheating but...
student = phd.getClass().getSuperClass().getSuperClass().newInstance();


I like this, except you have to fight Java generics to get it working properly!


Going along with Logo's idea, the problem is that you need to add a try/catch block or make your caller method throw an Exception.


public class Runner {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
Student student = new Student();
@SuppressWarnings("unused")
TAStudent ta = new TAStudent();
PhDStudent phd = new PhDStudent();

student = ((Class<Student>) ((Class<TAStudent>) ((Class<PhDStudent>) phd
.getClass()).getSuperclass()).getSuperclass()).newInstance();
student.display();
}
}



Output:

I am a regular student.


Reflection is such a hack =\


Wont work.. Im getting the exception. What does reflection do?


TAStudent ta = new TAStudent("1");
PhDStudent phd = new PhDStudent("2");
Student student = new Student("2");
try {
student = ((Class<Student>) ((Class<TAStudent>) ((Class<PhDStudent>) phd.getClass()).getSuperclass()).getSuperclass()).newInstance();
student.display();
} catch (IllegalAccessException ex) {
Logger.getLogger(PhDStudent.class.getName()).log(Level.SEVERE, null, ex);
}




What's the exception? It's probably throwing an exception because the constructors take in parameters (you never specified this in the original problem).
When you want something, all the universe conspires in helping you to achieve it.
Qzy
Profile Blog Joined July 2010
Denmark1121 Posts
Last Edited: 2010-09-22 20:26:49
September 22 2010 20:26 GMT
#32
On September 23 2010 05:17 Cambium wrote:
Show nested quote +
On September 23 2010 02:31 Qzy wrote:
On September 23 2010 02:04 Cambium wrote:
On September 23 2010 01:55 Cambium wrote:
On September 23 2010 01:47 Logo wrote:
Probably cheating but...
student = phd.getClass().getSuperClass().getSuperClass().newInstance();


I like this, except you have to fight Java generics to get it working properly!


Going along with Logo's idea, the problem is that you need to add a try/catch block or make your caller method throw an Exception.


public class Runner {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
Student student = new Student();
@SuppressWarnings("unused")
TAStudent ta = new TAStudent();
PhDStudent phd = new PhDStudent();

student = ((Class<Student>) ((Class<TAStudent>) ((Class<PhDStudent>) phd
.getClass()).getSuperclass()).getSuperclass()).newInstance();
student.display();
}
}



Output:

I am a regular student.


Reflection is such a hack =\


Wont work.. Im getting the exception. What does reflection do?


TAStudent ta = new TAStudent("1");
PhDStudent phd = new PhDStudent("2");
Student student = new Student("2");
try {
student = ((Class<Student>) ((Class<TAStudent>) ((Class<PhDStudent>) phd.getClass()).getSuperclass()).getSuperclass()).newInstance();
student.display();
} catch (IllegalAccessException ex) {
Logger.getLogger(PhDStudent.class.getName()).log(Level.SEVERE, null, ex);
}




What's the exception? It's probably throwing an exception because the constructors take in parameters (you never specified this in the original problem).


Yeah sorry, it takes a string - does that matter?
TG Sambo... Intel classic! Life of lively to live to life of full life thx to shield battery
Cambium
Profile Blog Joined June 2004
United States16368 Posts
September 22 2010 20:39 GMT
#33
On September 23 2010 05:26 Qzy wrote:
Show nested quote +
On September 23 2010 05:17 Cambium wrote:
On September 23 2010 02:31 Qzy wrote:
On September 23 2010 02:04 Cambium wrote:
On September 23 2010 01:55 Cambium wrote:
On September 23 2010 01:47 Logo wrote:
Probably cheating but...
student = phd.getClass().getSuperClass().getSuperClass().newInstance();


I like this, except you have to fight Java generics to get it working properly!


Going along with Logo's idea, the problem is that you need to add a try/catch block or make your caller method throw an Exception.


public class Runner {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
Student student = new Student();
@SuppressWarnings("unused")
TAStudent ta = new TAStudent();
PhDStudent phd = new PhDStudent();

student = ((Class<Student>) ((Class<TAStudent>) ((Class<PhDStudent>) phd
.getClass()).getSuperclass()).getSuperclass()).newInstance();
student.display();
}
}



Output:

I am a regular student.


Reflection is such a hack =\


Wont work.. Im getting the exception. What does reflection do?


TAStudent ta = new TAStudent("1");
PhDStudent phd = new PhDStudent("2");
Student student = new Student("2");
try {
student = ((Class<Student>) ((Class<TAStudent>) ((Class<PhDStudent>) phd.getClass()).getSuperclass()).getSuperclass()).newInstance();
student.display();
} catch (IllegalAccessException ex) {
Logger.getLogger(PhDStudent.class.getName()).log(Level.SEVERE, null, ex);
}




What's the exception? It's probably throwing an exception because the constructors take in parameters (you never specified this in the original problem).


Yeah sorry, it takes a string - does that matter?


Yes it does, because the newInstance() method throws IllegalAccessException if the class or its nullary constructor is not accessible. In this case, because you have an explicit constructor, we cannot access the default constructor.
When you want something, all the universe conspires in helping you to achieve it.
Cambium
Profile Blog Joined June 2004
United States16368 Posts
September 22 2010 20:43 GMT
#34
To fix it, you need to retrieve the constructor from the Class object and pass in the argument in the Constructor object's newInstance() method


student = ((Class<Student>) ((Class<TAStudent>) ((Class<PhDStudent>) phd.getClass()).getSuperclass()).getSuperclass()).getDeclaredConstructors()[0].newInstance({"1"});
When you want something, all the universe conspires in helping you to achieve it.
Normal
Please log in or register to reply.
Live Events Refresh
BSL: ProLeague
18:00
Grand Finals - bo9
Dewalt vs Bonyth
ZZZero.O485
LiquipediaDiscussion
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
BRAT_OK 179
ProTech70
StarCraft: Brood War
Mini 723
ZZZero.O 547
EffOrt 473
Soma 159
Aegong 48
Terrorterran 20
LuMiX 9
League of Legends
Grubby4981
Dendi1808
Counter-Strike
fl0m2066
Super Smash Bros
Mew2King205
Chillindude62
Westballz39
Heroes of the Storm
Khaldor775
Liquid`Hasu650
Other Games
FrodaN3366
B2W.Neo1121
Mlord662
mouzStarbuck284
Pyrionflax176
elazer95
Sick54
Organizations
Other Games
gamesdonequick46055
EGCTV1614
StarCraft 2
angryscii 41
Other Games
BasetradeTV32
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 18 non-featured ]
StarCraft 2
• HeavenSC 48
• Adnapsc2 28
• musti20045 2
• Kozan
• Migwel
• AfreecaTV YouTube
• sooper7s
• intothetv
• IndyKCrew
• LaughNgamezSOOP
StarCraft: Brood War
• 3DClanTV 47
• STPLYoutube
• ZZZeroYoutube
• BSLYoutube
Dota 2
• Ler156
League of Legends
• masondota2674
Other Games
• imaqtpie2154
• Shiphtur392
Upcoming Events
Wardi Open
14h 45m
Replay Cast
1d 3h
Sparkling Tuna Cup
1d 13h
WardiTV European League
1d 19h
MaNa vs sebesdes
Mixu vs Fjant
ByuN vs HeRoMaRinE
ShoWTimE vs goblin
Gerald vs Babymarine
Krystianer vs YoungYakov
PiGosaur Monday
2 days
The PondCast
2 days
WardiTV European League
2 days
Jumy vs NightPhoenix
Percival vs Nicoract
ArT vs HiGhDrA
MaxPax vs Harstem
Scarlett vs Shameless
SKillous vs uThermal
Replay Cast
3 days
RSL Revival
3 days
ByuN vs SHIN
Clem vs Reynor
Replay Cast
4 days
[ Show More ]
RSL Revival
4 days
Classic vs Cure
FEL
4 days
RSL Revival
5 days
FEL
5 days
FEL
5 days
Sparkling Tuna Cup
6 days
RSL Revival
6 days
FEL
6 days
Liquipedia Results

Completed

BSL 2v2 Season 3
HSC XXVII
Heroes 10 EU

Ongoing

JPL Season 2
BSL Season 20
Acropolis #3
KCM Race Survival 2025 Season 2
CSL 17: 2025 SUMMER
Copa Latinoamericana 4
Jiahua Invitational
Championship of Russia 2025
RSL Revival: Season 1
Murky Cup #2
BLAST.tv Austin Major 2025
ESL Impact League Season 7
IEM Dallas 2025
PGL Astana 2025
Asian Champions League '25
BLAST Rivals Spring 2025
MESA Nomadic Masters
CCT Season 2 Global Finals
IEM Melbourne 2025

Upcoming

2025 ACS Season 2: Qualifier
CSLPRO Last Chance 2025
CSL Xiamen Invitational
2025 ACS Season 2
CSLPRO Chat StarLAN 3
K-Championship
uThermal 2v2 Main Event
SEL Season 2 Championship
FEL Cracov 2025
Esports World Cup 2025
StarSeries Fall 2025
FISSURE Playground #2
BLAST Open Fall 2025
BLAST Open Fall Qual
Esports World Cup 2025
BLAST Bounty Fall 2025
BLAST Bounty Fall Qual
IEM Cologne 2025
FISSURE Playground #1
TLPD

1. ByuN
2. TY
3. Dark
4. Solar
5. Stats
6. Nerchio
7. sOs
8. soO
9. INnoVation
10. Elazer
1. Rain
2. Flash
3. EffOrt
4. Last
5. Bisu
6. Soulkey
7. Mini
8. Sharp
Sidebar Settings...

Advertising | Privacy Policy | Terms Of Use | Contact Us

Original banner artwork: Jim Warren
The contents of this webpage are copyright © 2025 TLnet. All Rights Reserved.