Reputation: 3
I am trying to teach myself how to program in java and right now I'm trying to teach myself how to use inheritance.
I want to create a class named Pushbutton which inherits from the class Door. In my class Pushbutton, I have a method called status, which takes a boolean value called button and depending on the value button, will either call the method open or close in the class Door.
The issue I'm having is that in my main method, I am trying to call the method status as seen on line 25, but I'm getting an error message saying
The method status(boolean) is undefined for the type Main.
I can see how to fix this issue without using inheritance, but then that defeats the purpose of what I'm trying to accomplish. Does anyone know how I can fix this issue while still using inheritance?
I have tried making the classes Pushbutton and Door public as well but then I get new error messages saying the classes must be in their own file. Also, the original error message doesn't go away.
class Door{
public void open() {
System.out.println("Door is opened");
}
public void close() {
System.out.println("Door is closed");
}
}
class Pushbutton extends Door{
public void status(boolean button) {
if (button==true) {
super.open();
}
else {
super.close();
}
}
}
public class Main {
public static void main(String[] args) {
boolean button=true;
status(button); //line 25
}
}
Upvotes: 0
Views: 89
Reputation: 1
Main
with the static main
method is the entry of your program.status
method of Pushbutton
class, first declare the instance of Pushbutton
, PushButton pushbutton = new Pushbutton()
, then call its method pushbutton.status()
.public class Main {
public static void main(String[] args) {
boolean open=true;
// create an instance of Pushbutton
Pushbutton pushbutton = new Pushbutton();
// invoke the method and pass it a boolean value
button.status(open); //line 25
}
}
Upvotes: 0
Reputation: 129
you need to create object of type Pushbutton first to be able to use a non-static method that exists in Pushbutton class
here:-
class Door{
public void open() {
System.out.println("Door is opened");
}
public void close() {
System.out.println("Door is closed");
}
}
class Pushbutton extends Door{
public void status(boolean button) {
if (button==true) {
super.open();
}
else {
super.close();
}
}
}
public class Main {
public static void main(String[] args) {
boolean open=true;
// create object of type Pushbutton
Pushbutton button = new Pushbutton();
// call the method status from the object
// and pass it the boolean parameter
button.status(open); //line 25
}
}
also i think you should not call it "Pushbutton", a button is not a Door (logically), maybe call it HomeDoor because home doors open and close?
Upvotes: 1