• Post Reply Bookmark Topic Watch Topic
  • New Topic

Mystery - getContentPane() JFrame

 
Asif Mansoori
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
getContentPane() method of JFrame returns Container but if I do following

JPanel panel = (JPanel)getContentPane();

and try to access methods defined only in JPanel. For example

System.out.println(panel.getUIClassID());//statment # 1
or
System.out.println(panel.getUI());//statement # 2

both above statement #1 and #2 works

I am confused because getContentPane() of JFrame return type is Container class. Neither getUIClassID() or getUI() methods are part of Container class or its super class or any inherited class which Container could inherit from. why above statements works.

I am just beginner please help
Thanks
 
Mark Vedder
Ranch Hand
Posts: 624
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch.

That's working because in this line:



You are casting the return value of getContentPane() to a JPanel. Since a JPanel is a subclass of a Container, and in this case the thing being returned is a JPanel, the casting works. So at that point, your 'panel' variable is a reference type of JPanel. So you can call any of JPanel's methods on it. Now if the JFrame's container was not a JPanel, that line would throw a ClassCastException.

This concept is called Polymorphism. It is a little bit more involved than what I can explain in a couple of sentences in a forum post. But it is a very important concept to understand in Object-Oriented Programming (and in Java). In fact, it is a cornerstone concept of OOP. I suggest you take a look a the camp fire story How my Dog learned Polymorphism. Camp fire stories are some tutorials here at JavaRanch that are told in story format making it more fun (and easier) to learn.

You may also want to read the excellent book Head First Java, 2nd Edition. Head first Java is a great book and does one of the best jobs at teaching polymorphism.

Good luck in your studies of Java. We look forward to seeing you around the Ranch
[ December 08, 2008: Message edited by: Mark Vedder ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!