Generating Undeclared Methods

Eclipse has many features that make the job of a programmer easy. Here a simple project is created and will use few of those features to demonstrate how easy programming can be using Eclipse. Most of the new programmers, ignore these and prefer to code everything themselves which is time consuming.




  1. First creating a package: really simple. Right click the project name and click “ New ” – > “ Package” . Name it as “car” .


  2. Creating a class in it named “ Car ” and defined 2 private attributes namely “ doors ” , “ seats ” . Now generate getters/setters for that. Eclipse can generate those for us. In the Source menu, click “ Generate getters and setters ” .



  3. Now make another class in the same package named “ Honda ”. Create a “ main ” method in this class. Eclipse will generate “ main ” method once you check the “ generate main method ” checkbox while creating the class.

  4. Also to make Car class to be the superclass for “ Honda ” class. Click “ Browse ” button against superclass field of the class declaration window. As “ Car ” class is under package “ cars ”, parent class for Honda will be “ cars.Car ”.


Eclipse will generate the following code:



package cars;public class Honda extends Car {
 
/**
 
* @param args
 
*/

 
public static void main(String[] args) {
 
// TODO Auto-generated method stub
 
}
 
}

In class Honda, following lines of code are added.



	Car car1 = new Honda(); car1.setSeats(4);
 
car1.setDoors(2);
 
System.out.println(car1.calcNum());

“ car1.calcNum() ” shows error as this method is not declared in the class Car. One way is to go back to class Car and declare the method. Simple way is to click the red cross on the left of the problem line and Eclipse will give you the options for automatically generating the required method in the required class. After generating the required method, Write code according to the requirement in the generated method.



Review the code:



package cars;public class Car {private int doors;private int seats;
 
public int getDoors() {
 
return doors;
 
}
 
public void setDoors(int doors) {
 
this.doors = doors;
 
}
 
public int getSeats() {
 
return seats;
 
}
 
public void setSeats(int seats) {
 
this.seats = seats;
 
}
 
public Object calcNum() {
 
return this.getDoors() * this.getSeats();
 
}
 
}
 
package cars;
 
public class Honda extends Car {
 
public static void main(String[] args) {
 
Car car1 = new Honda();
 
car1.setSeats(4);
 
car1.setDoors(2);
 
System.out.println(car1.calcNum());
 
}
 
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.