Win a copy of Practice Tests for OCP Java 17 Certification Exam (1Z0-829) this week in the OCPJP forum!
  • 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Rob Spoor
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
  • Scott Selikoff
Bartenders:
  • Piet Souris
  • Jj Roberts
  • fred rosenberger

Automatic Casting

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am not able to compile this code.
class Shape{
String Shape = "Shape";
int i;
Shape(){
System.out.println("Constructor Shape");
}
void draw(){
System.out.println("Draw Shape");
}
//String getCircleString(){return "None";}
}
class Circle extends Shape{
String sc = "Circle";
int ic;
Circle(){
System.out.println("Constructor Circle");
}
void draw(){
int ic1=0 ;
System.out.println("Draw Circle"+ic1);
}
public String getCircleString(){
return sc;
}
}

public class Geometry{
String g = "Geometry";
public static void main(String[] arg){
Shape s1 = new Circle();
s1.draw();
System.out.println("Variable Shape 3 sc from accessor "+ s1.getCircleString());

}
}
It gives me an error on the Print statement at s1.getCircleString() is not defined in the Shape class. But since I created it as a Circle should it not identify the function defined there.
If I create this function in Shape also then the error does not occur.
Guys can some one explain to me why this is happening as it is happening.
Thanks in advance.
 
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
At compile time, s1 is treated as an object of type Shape which doesn't contain the method in question which is why you get the compile error. At run time, s1 will be treated as an object of type Circle since that is what it really is. You can see this since s1.getCircleString() actually runs the method of Circle and not the one from Shape.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic