Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

about upcasting

 
lang lang
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Instrument{
public void play(){}
static void tune(Intrument i){
//...
i.play();
}
}
class Wind extends Instrument[
public static void main(String[] args){
Wind flute=new Wind();
Intrument.tune(flute);//upcasting
}
}///:-
I am confused about 'upcasting',would you say something about it ?
how to use it?
thank you !
----Lang
 
Wirianto Djunaidi
Ranch Hand
Posts: 210
Ruby Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
upcasting is when you refer to an object by its more general identity.
In your example you are passing flute which is a Wind object into the
tune() method which take Instrument object. So within the Instrument.tune()
your flute is seen as Instrument object, Wind object.
Just like when your neighbour just bought a new Subaru Outback, and your
wife told you, "oh, Jim just bought a new Car".
 
Gorkhali Mountainman
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
******/
*Here is more Simple example! Car is parent Class and Hammer is child *class! upcasting means calling method or variable from upper class!
*-@@@
******/
//Hammer.java
class Car {
public static void drive(){
System.out.println("I drive Car");
}
}
class Hammer extends Car {
public static void drive(){
System.out.println("I drive Hammer!");
}
public static void main(String[] args){
Hammer H2 = new Hammer();
//call drive method from parent class Car
Car.drive();//upcasting
//call drive method from child class Hammer
H2.drive();
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic