Subscribe To MegiSoft RSS Feeds!     Your Browser OR  Google Feedburner

Java Object Casting

It is possible In Java to put an object into a more general type or cast up the hierarchy implicitly. A subclass in Java contains the members of the superclass, but a superclass doesn’t contain all the members of a subclass.

In the below example, the Laptop class extends the Device class that is why it has all the members of the Device including brand and methods, while Device doesn’t have the ram and the hardDrive attributes.

 

Device device = new Laptop (); is a legal casting.
Laptop laptop = (Laptop) device;

 

You can store a Device object to a Laptop type reference without explicitly casting. If you try to store a Laptop object to a Device type reference, explicit casting is required.

Device dv  = new Device ();

If we instantiate the Device class, then the following will cause a ClassCastException error:

Laptop lap = (Laptop) dv;

Article: Java casting object
Quizzes: Beginner  Intermediate  Advanced 

casting-objects-color

Example: upcasting and downcasting in Java

In the following example, both classes share the attribute price and Laptop class overrides the method getPrice(). By upcasting the Device class to Laptop, we get the attributes of the superclass Device, but the methods, which are overridden in the class Laptop:

Question:

What is written to the standard output as the result of running the following program?

public class Device {

	double price = 5;

	public double getPrice(){
		return price;
	}
}

public class Laptop extends Device {

	double price = 534;

	public double getPrice(){
		return(price - 20); // reduce discount
	}
}

public class TestDevice {

	public static void main(String[] args){
		// upcasting & downcasting the objects device and laptop
		Device device = new Laptop();
		Laptop laptop = (Laptop) device;
		System.out.println("item.price: " + device.price);
		System.out.println("item.getPrice(): " + device.getPrice());
		System.out.println("laptop.price: " + laptop.price);
		System.out.println("laptop.getPrice(): " + laptop.getPrice());
	}
}

Answer:
item.price: 5.0
item.getPrice(): 514.0
laptop.price: 534.0
laptop.getPrice(): 514.0

 

Exercise 1

What is written to the standard output as the result of executing the following statements?

public class Employee {

	String name = "Jack";
	double salary = 1800;

	public double getSalary(){
		return salary;
	}
	public double getSalary(double salary){
		return salary;
	}
}

public class Programmer extends Employee {

	double salary = 2400;
	String language;

	public double getSalary(){
		return salary;
	}
	public double getSalary(double salary){
		return salary + 100;
	}
}

public class TestEmployee {

	public static void main(String[] args){
		Employee employee = new Programmer();
		System.out.print(employee.salary);
		System.out.print(", " + employee.getSalary());
		System.out.print(", " + employee.getSalary(3300));
	}
}

Select the correct answer.



Please, leave your questions, feedback and suggestions in the comments below! If you need more explanation by any of the answers, just let me know to update it for you!

Exercise 2

What is written to the standard output as the result of executing the following statements?

public class Device {

	String brand;
	double price = 5;

	public Device() {
		System.out.print("This is a device: ");
	}
	public void print(){
		System.out.print(this.price);
	}
}

public class Laptop extends Device {

	double price = 600;
	int ram;
	double hardDrive;

	public Laptop() {
		System.out.print("This is a laptop: ");
	}
	public void print(){
		System.out.print(this.price);
	}
}

public class TestLaptopCode {

	public static void main(String[] args){
		Device device = new Laptop();
		device.print();
	}
}

Select the correct answer.



Please, leave your questions, feedback and suggestions in the comments below! If you need more explanation by any of the answers, just let me know to update it for you!

Megisoft.com offers a practical method to learn and improve your Java skills. It avoids unnecessary long boring theoretical explanations, but it uses many exercises and quizzes. The author of Megisoft is Sar Maroof who has more than a decade of experience with web development mainly with Java, MySql, HTML and more..
Article: Java casting object
Quizzes: Beginner  Intermediate  Advanced 

Suggested Articles:


Click Here For Info about: Sar Maroof's New Java Book
Author: Sar Maroof
More than a decade of experience with developing web applications mainly with Java.
Sun Certified JSP as well as EJB
CIW Certified Internet Webmaster - Mind IT
Applied Science in Physics HBO Amsterdam
Bachellor Science in Physics at Basra university.
 Subscribe To Megisoft RSS Feeds! (Your Browser)
 Mail This Page To A Friend!
 Bookmark This Page!
Share on FacebookTweet about this on TwitterShare on RedditShare on LinkedIn

13 Comments

Add a Comment
  1. That’s a skillful answer to a difflcuit question

  2. Answer a “This code writes “This is a device: This is a laptop: 600.0” to the standard output.” is correct. The methods of the object employee depends on the type Programmer including its constructor.

    Something seems off with the description of the answer for the device exercise…

    1. My apology, you are right! I improved the answer.

      1. These pieces really set a standard in the intydsru.

    2. Life is short, and this article saved valabule time on this Earth.

  3. Your website is really unique. I love your quizzes.

    1. I am glad about that thanks 🙂

      1. I think you hit a buleylse there fellas!

    2. Ho ho, who wodula thunk it, right?

  4. Good article, thanks!

    1. You are welcome!

      1. Problem solved, thanks!

    2. Holy shtinzi, this is so cool thank you.

Leave a Reply

megisoft © 2016