Results 1 to 16 of 16
Like Tree2Likes
  • 1 Post By SurfMan
  • 1 Post By gimbal2

Thread: Taking an Object as an input? instanceof keyword test

  1. #1
    subterranean is offline Member
    Join Date
    Feb 2014
    Posts
    5
    Rep Power
    0

    Default Taking an Object as an input? instanceof keyword test

    I am trying to test the instanceof keyword.

    To do this, I've made a method with a simple logical test like so:
    Java Code:
     Vehicle vehicle1 = new Vehicle();
    
    public void Type(){
            if (vehicle1 instanceof Vehicle) {
        	    System.out.println("Type = Vehicle");
        	}
        		else if (vehicle1 instanceof Car) {
        			System.out.println("Type = Car");
        		}
        			else if (vehicle1 instanceof Truck) {
        		        	System.out.println("Type = Truck");
        			}
        		}
        		
    
    }
    I wanted to try implementing it into the class definitions for Vehicle, then extend that to Car and Truck, but I'm not sure how to use this test in a general case.
    The only way this method works is if I set the test to specifically accept a specific object as a parameter.
    I want to test multiple objects, but I'm not really sure how else to do this without simply copy-pasting the logical test multiple times and changing the respective objects that are used as parameters.

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,033
    Rep Power
    6

    Default Re: Taking an Object as an input? instanceof keyword test

    If you want to get vehicle1's class, you could use vehicle1.getClass().getName(). But I am not really certain what you are trying to accomplish.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  3. #3
    subterranean is offline Member
    Join Date
    Feb 2014
    Posts
    5
    Rep Power
    0

    Default Re: Taking an Object as an input? instanceof keyword test

    Thanks, but that's actually not what I'm trying to do. I'm trying to implement it as a method into the class definition for Vehicle.
    Java Code:
    public class Vehicle {
        public int speed;
            
        // the Vehicle class has one constructor
        public Vehicle() {
        int startSpeed = 0;
            this.speed = startSpeed;
        }        
    
        //methods for the Vehicle class
        public void stop(){
        System.out.println("Stopping");
        }
        public void start(){
        System.out.println("Starting");
        }
        public void turn(){
        System.out.println("Turning");
        }
    }
    the methods turn(), stop() and start() are all parts of the class definition for Vehicle.
    I want to implement the Type() method as a general method that, like the methods turn(), stop() and start() can be called for a Vehicle object.
    However, I don't really know how to do that.
    Like this:
    Java Code:
    Vehicle vehicle1 = new Vehicle();
    vehicle1.Type();
    //print type of vehicle1
    Instead of having to specifically set "vehicle1" as a parameter, I want to be able to use this method with any Vehicle object.
    Last edited by subterranean; 02-07-2014 at 02:14 PM.

  4. #4
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,033
    Rep Power
    6

    Default Re: Taking an Object as an input? instanceof keyword test

    Let's say for example you do the following in your Vehicle class:

    Java Code:
    public String getType() {
        return getClass().getName();
    }
    Now what is it you want to do? This will return the class name of whatever class extends Vehicle.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  5. #5
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,094
    Rep Power
    4

    Default Re: Taking an Object as an input? instanceof keyword test

    I am always hesitant to use classnames as identifiers for a certain type. Besides that, it will definately mess up any obfuscation you got going when doing getClass().getName().equals("Car").

    Depending on what you want to achieve with this excersise, one possibility is to use enums.

    Java Code:
    public abstract class Vehicle {
        public enum Type {
           CAR, BUS, TRUCK
        }
    
        public abstract Vehicle.Type getType()
    }
    
    public class Car extends Vehicle {
        public Vehicle.Type getType() {
            return Vehicle.Type.CAR;
        }
    }
    The real question here is: why do you need the type of the vehicle at runtime?
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  6. #6
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,033
    Rep Power
    6

    Default Re: Taking an Object as an input? instanceof keyword test

    I got the impression the OP did not want to have to override the method for every subclass. So the only way I know is to return the class name. I am still not certain how this is to be used.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  7. #7
    subterranean is offline Member
    Join Date
    Feb 2014
    Posts
    5
    Rep Power
    0

    Default Re: Taking an Object as an input? instanceof keyword test

    It's just an exercise to test understanding for the usage for instanceof that my teacher assigned.
    I am not sure why my teacher wants me to have the method in each class definition, though.

  8. #8
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,094
    Rep Power
    4

    Default Re: Taking an Object as an input? instanceof keyword test

    Usually instanceof is not used in baseclasses, but in classes using those. I could imagine an example like this:

    Java Code:
    public class Vehicle {
        public void start(){
            
        }
    }
    
    class Car extends Vehicle {
        public void adjustMirror(){
            
        }
    }
    
    class Truck extends Vehicle {
        
    }
    
    class MyProgram {
        public static void main(String[] args) {
            Vehicle blah = new Car();
            
            //works
            blah.start();
            
            //doesn't work
            blah.adjustMirror();
            
            if (blah instanceof Car) {
                //works
                ((Car)blah).adjustMirror();
            }
        }
    }

    PS: make sure you follow the Java naming rules, like Jim showed in post #4.
    gimbal2 likes this.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  9. #9
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,033
    Rep Power
    6

    Default Re: Taking an Object as an input? instanceof keyword test

    Well you can't have the target of an instanceof be a variable.

    So you cannot do this

    Java Code:
    if (object instanceof typeVariable) {
       //
    }
    just as you can't do this:
    Java Code:
    SomeType a = (typeVariable) q; where q is an instance of SomeType.
    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  10. #10
    subterranean is offline Member
    Join Date
    Feb 2014
    Posts
    5
    Rep Power
    0

    Default Re: Taking an Object as an input? instanceof keyword test

    My teacher wants me to make a method in my client program to accomplish the exercise now. So I'm guessing you would do something like this:
    Java Code:
    public class Driver {
    public static void main(String[] args){
    
    	public void getType(){
    	
    	Vehicle car = new Car();
    	Vehicle truck = new Truck();
    	Vehicle vehicle = new Vehicle();
    if (car instanceof Vehicle) {
    	    System.out.println("Type = Vehicle");
    	}
    		else if (car instanceof Car) {
    			System.out.println("Type = Car");
    		}
    		else if (car instanceof Truck) {
    		    System.out.println("Type = Truck");
    			}
    		if (vehicle instanceof Vehicle) {
    		    System.out.println("Type = Vehicle");
    		}
    			else if (vehicle instanceof Car) {
    				System.out.println("Type = Car");
    			}
    			else if (vehicle instanceof Truck) {
    			    System.out.println("Type = Truck");
    				}
    		if (truck instanceof Vehicle) {
    		    System.out.println("Type = Vehicle");
    		}
    			else if (truck instanceof Car) {
    				System.out.println("Type = Car");
    			}
    			else if (truck instanceof Truck) {
    			    System.out.println("Type = Truck");
    				}
    	
    			}
    		}
    	}
    But isn't this impossible? You can't define a method inside of the main method, right?

  11. #11
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,094
    Rep Power
    4

    Default Re: Taking an Object as an input? instanceof keyword test

    No, that's why you should move that code back to Vehicle. I'd also rename it to printType() or something. Since it doesn't return anything (void), naming it "getType" makes it confusing.

    Your Driver class would then look like this:
    Java Code:
    public class Driver {
       public static void main(String[] args){
         Vehicle car = new Car();
         Vehicle truck = new Truck();
         Vehicle vehicle = new Vehicle();
         
         car.printType();
         truck.printType();
         vehicle.printType();
       }
    }
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  12. #12
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,365
    Rep Power
    6

    Default Re: Taking an Object as an input? instanceof keyword test

    This thread is maddening :) I'd want to include abstract classes, interfacing, the 'this' keyword, all beautiful things that would lead to slightly more realistic examples of the usage of the instanceof keyword. But that's just out of scope.

    IMO the instructor is wrong in introducing that keyword this soon.
    SurfMan likes this.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  13. #13
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,094
    Rep Power
    4

    Default Re: Taking an Object as an input? instanceof keyword test

    Quote Originally Posted by gimbal2 View Post
    This thread is maddening :) I'd want to include abstract classes, interfacing, the 'this' keyword, all beautiful things that would lead to slightly more realistic examples of the usage of the instanceof keyword. But that's just out of scope.

    IMO the instructor is wrong in introducing that keyword this soon.
    Hear hear. I thought I was the only one... It's scary how stuck the professors are on ancient procedural shit.

    Edit: if you see the examples I gave the OP, you can see it going from abstract classes to inheritance example to crap. :) But hey, as long as the prof is happy we're good to go. You'll learn some real world programming when you land your first project :)
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  14. #14
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,365
    Rep Power
    6

    Default Re: Taking an Object as an input? instanceof keyword test

    Well I hope the OP picks at least one personal project to do before his first job/internship to get a feel for creating something 'real' from start to finish :)
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  15. #15
    subterranean is offline Member
    Join Date
    Feb 2014
    Posts
    5
    Rep Power
    0

    Default Re: Taking an Object as an input? instanceof keyword test

    Quote Originally Posted by jim829 View Post
    Well you can't have the target of an instanceof be a variable.

    So you cannot do this

    Java Code:
    if (object instanceof typeVariable) {
       //
    }
    just as you can't do this:
    Java Code:
    SomeType a = (typeVariable) q; where q is an instance of SomeType.
    Regards,
    Jim
    With this in mind, shouldn't it be impossible to put this method in Vehicle class?

  16. #16
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,094
    Rep Power
    4

    Default Re: Taking an Object as an input? instanceof keyword test

    Quote Originally Posted by subterranean View Post
    With this in mind, shouldn't it be impossible to put this method in Vehicle class?
    It can be done, but only if you use the keyword "this". I am not sure if you've already had that subject...

    Java Code:
    public class Vehicle {
    
        public void printType() {
            if (this instanceof Car) {
                System.out.println("CAR");
            }
            ...
        }
    }
    I must warn you, every time you use this pattern in real-world code, God kills a puppy.

    Edit: re-did example.
    Last edited by SurfMan; 02-07-2014 at 05:37 PM.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

Similar Threads

  1. Taking input from use
    By leepikamukharji in forum New To Java
    Replies: 1
    Last Post: 11-08-2011, 03:33 PM
  2. Problem with taking input and printing it.
    By equal in forum New To Java
    Replies: 3
    Last Post: 11-11-2010, 11:02 PM
  3. Use of keyword instanceof
    By darek9576 in forum New To Java
    Replies: 3
    Last Post: 03-14-2010, 11:35 PM
  4. Taking input from Properties File
    By bugger in forum New To Java
    Replies: 4
    Last Post: 05-07-2008, 10:30 AM
  5. Taking input from console
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 11-05-2007, 05:47 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •