I am trying to access the super class variable name from user input.
I am not sure how to have the super class variable name point to the user input. Here is the code for it. Any ideas thank you.
package chapter4;
import java.util.Scanner;
public class VetOffice extends Animal {
public VetOffice(int lifeExpectancy, int weight, String name, Character gender, String type) {
super(lifeExpectancy, weight, name, gender, type);
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please enter name of pet");
//super(name);
//= console.next();
//}
}
}
//}
The thing is you cannot access super class variables in main method. Because it is static method. If you want to access in main() you have to make Animal class name variable to static. Then you can assgin a value directly in main().
Like this:
in Animal class,
static String name;
in VetOffice,
name = console.next();
You can try different ways depending on the thing that you are going to achieve you have to decide,
Is this variable can be declare as static or not? Because static variables common for every object.
Another way you can do this is,
Create getters and setters for Animal class member variables. Then also you cannot access in the main method because also you have to make those methods and variable to static.
As a solution without makinng them static or a new methods even getters and setters in super class you can create default constructor for super class and assign values like below:
If your variable in the super class is private you have to create getters and setters.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please enter name of pet");
VetOffice pet = new VetOffice();
pet.name = console.next();
System.out.println(pet.name);
}
Note: create default constructor If it is unnecessary to create object from VetOffice or super class seeing that you have to pass values to constructor.
UPDATE:
According to your comment
If your variable in the super class is private do this:
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please enter name of pet");
VetOffice pet = new VetOffice();
pet.setName(console.next());
System.out.println(pet.getName());
}
Another way that you asked for in the comment:
Animal class(partialy implemented to show you)
public class Animal {
int lifeExpectancy;
static int weight;
static String name;
Animal(int lifeExpectancy, int weight, String name, Character gender, String type){
this.weight = weight;
this.name = name;
}
public static String getName() {
return name;
}
public static void setName(String n) {
name = n;
}
}
Then in the main method:
Animal.setName(console.next());
System.out.println(Animal.getName());
Related
I have a 2 class, one of which extends the superclass.
when I call the sub-class from the main, I get an error because "the method I call isn't a part of the class", but as my programme goes on, it should work
I had to use it only with the casting of class, but my teacher told me that casting should not be used in such a work, so please I'd like to understand where I'm wrong and where I can do better
(Im providing the code of 3 classes, the sub-class, the super-class, and the main)
Main
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Type in the number");
int number = in.nextInt();
System.out.print("Type in the name");
String name = in.next();
Test testObj = new Test(number);
testObj = new TestSub(number);
testObj.setNameSub(name);
in.close();
}
}
Super class
public class Test {
protected int number;
protected String name;
public Test(int number){
this.number=number;
}
public void setName(String name){
this.name=name;
}
public String toString(){
return "the name is "+name+"the number is "+number;
}
}
Sub Class
public class TestSub extends Test {
public TestSub(int number){
super(number);
}
public void setNameSub(String name){
setName(name);
}
public String toStringSub(){
return toString();
}
}
The error I get is this:
The method setNameSub(String) is undefined for the type Test
In the main where there is this instruction : testObj.setNameSub(name);
The error here is (as indicated in the comments) that you initialize testObj as Test instead of TestSub, causing the error when the compiler isn't able to find setNameSub() between Test's methods.
So the easy solution is clearly to initialize testObj as a TestSub.
The correct solution that takes advantage of the methods inheritance would be to keep the initialization as it is but to call the method testObj.setName(name) instead, and deleting setNameSub() and toString() methods from TestSub class since they don't add any difference from the methods in the Test class.
I'm very new to java and would like to know whether calling a subclass method in a superclass is possible. And if doing inheritance, where is the proper place to set public static void main.
Superclass
public class User {
private String name;
private int age;
public User() {
//Constructor
}
//Overloaded constructor
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public static void main(String []args) {
User user1 = new Admin("Bill", 18, 2);
System.out.println("Hello "+user1.getName());
user1.getLevel();
}
}
Subclass
public class Admin extends User {
private int permissionLevel;
public Admin() {
//Constructor
}
//Overloading constructor
public Admin(String name, int age, int permissionLevel) {
super(name, age);
this.permissionLevel = permissionLevel;
}
public void getLevel() {
System.out.println("Hello "+permissionLevel);
}
}
Short answer: No.
Medium answer: Yes, but you have to declare the method in the superclass. Then override it in the subclass. The method body from the subclass will be in invoked when the superclass calls it. In your example, you could just put an empty getLevel method on User.
You could also consider declaring User as an abstract class and declaring the getLevel method as abstract on the User class. That means you don't put any method body in getLevel of the User class but every subclass would have to include one. Meanwhile, User can reference getLevel and use the implementation of its subclass. I think that's the behavior you're going for here.
I'm very new to java and would like to know whether calling a subclass
method in a superclass is possible.
A superclass doesn't know anything about their subclasses, therefore, you cannot call a subclass instance method in a super class.
where is the proper place to set public static void main.
I wouldn't recommend putting the main method in the Admin class nor the User class for many factors. Rather create a separate class to encapsulate the main method.
Example:
public class Main{
public static void main(String []args) {
User user1 = new Admin("Bill", 18, 2);
System.out.println("Hello "+user1.getName());
user1.getLevel();
}
}
No, it is not possible to call sub class method inside super class.
Though it is possible to call different implementations of the same method in a client code while you have a variable with a super class type and instantiate it with either super class or sub class objects. It is called polymorphism.
Please, consider the following example:
public class User {
private String name;
private int age;
protected int permissionLevel;
public User() {
//Constructor
}
//Overloaded constructor
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public void getLevel() {
System.out.println("Hello "+ permissionLevel);
}
}
public class Admin extends User {
public Admin() {
//Constructor
}
//Overloading constructor
public Admin(String name, int age, int permissionLevel) {
super(name, age);
this.permissionLevel = permissionLevel;
}
#Override
public void getLevel() {
System.out.println("Hello "+permissionLevel);
}
public static void main(String []args) {
User user1 = new Admin("Bill", 18, 2);
System.out.println("Hello "+user1.getName());
user1.getLevel(); //call to subclass method
user1 = new User("John", 22); //the variable is the same but we assign different object to it
user1.getLevel(); //call to superclass method
}
}
Answering your second question, no, it does not matter where you place your main method as long as it is of right method signature. As you can see in my example I moved the method to Admin.java - it is still acceptable.
Calling subclass method in a superclass is possible but calling a subclass method on a superclass variable/instance is not possible.
In java all static variable and methods are considered to be outside the class i.e they do have access to any instance variable or methods. In your example above it will be wise to create a new class called Main and put public static void main in there but this is just a hygiene issue and what you have above will work except for the line.
user1.getLevel()
Use case: If employee eats, then automatically should sleep:-)
Declare two methods eat and sleep from class person.
Invoke the sleep method from eat.
Extend person in the employee class and override only the sleep method:
Person emp=new Employee();
emp.eat();
Explanation: As eat method is not in subclass, it will invoke the super class eat. From there, sub class's sleep will be invoked.
I need to set values from the subclass by invoking the set method from the super class. I need to set monster name and health from the subclass
Alien class
public class Alien {
//Instance variables
public String monsterName;
public int HP;
//A method that sets monster properties
public void setValues(String monsterN, int health) {
monsterName = monsterN;
HP = health;
}
//A method that returns the monster name
public String getName() {
return monsterName;
}
//A method that returns monster's health
public int getHP() {
return HP;
}
//ToString method that prints out the info
public String toString() {
return("Monster name: " + getName() + "Monster's current health point: " + getHP());
}
}
Snake class
public class SnakeAlien extends Alien {
//Instance variable
//Set the snake values
Alien aObject = new Alien();
aObject.setvalues("Snake\n" 55));
}
The main class
public class Main {
public static void main(String[] args) {
Alien object = new Alien();
object.toString();
System.out.println(object);
}
}
I know how would I set these values through the main class, but I need to do it from the sub class SnakeAlien which inherets from the Alien class.
Because everything is public (which is terrible BTW) you can simply call the superclass' methods frimbthe subclasses. Not even super is needed.
Though, you should change members you don't want to reach from the outside to at least protected, and if you never want to make a pure Alien object, you should make that an avstract class.
the requirements are:
Create a file Hop.java with a public class named Hop.
Create two other classes: Skip a subclass of Hop and Jump a subclass of Skip.
Create a no-argument constructor in each of the three classes that prints the name of the class on a line by itself (e.g., use System.out.println(“Hop”) to print the “Hop” class name.
Create a main method (where?) and create a new instance of Jump.
Compile and run. You should see the output Hop, Skip, and Jump printed to standard out. Can you explain it?
and the code I write so far is :
public class Hop {
private String name;
public Hop(String name) {
this.name = name;
}
public static void main(String args[]) {
Jump j = new Jump("Hop", "Skip", "Jump");
System.out.println(j);
}
}
class Skip extends Hop {
private String name1;
public Skip(String name, String name1) {
super(name);
this.name1 = name1;
}
}
class Jump extends Skip {
private String name2;
public Jump(String name, String name1, String name2) {
super(name, name1);
this.name2 = name2;
}
}
This is what the question is asking you to do:
(The intention of the question is to demonstrate that all super class constructors are implicitly called (recursively) when an instance of a subclass is created.)
public class Hop {
public Hop() {
System.out.println("Hop");
}
public static void main(String args[]) {
Jump j = new Jump();
}
}
class Skip extends Hop {
public Skip() {
System.out.println("Skip ");
}
}
class Jump extends Skip {
public Jump() {
System.out.println("Jump ");
}
}
Read the question carefully. Follow the instructions. Try to think what the question is meant to demonstrate.
Im doing a question that requires you to make a class customers which will later on be added into an array list in the method of another class. However I am getting an error on the line i marked ERROR, that says:
"No enclosing instance of type Question3 is accessible. Must qualify the allocation with an enclosing instance of type Question3 (e.g. x.new A() where x is an instance of Question3)." And I have no clue why.
public class Question3 {
static ArrayList<customers> a= new ArrayList<customers>();
private static Scanner kbd;
public static void main(String[] args)
{
String input="";
double price=1;
String name="";
while(price != 0)
{
System.out.println("Customer Name: ");
name= kbd.nextLine().trim();
System.out.println("Purchase Price: ");
price= Double.parseDouble(kbd.nextLine().trim());
addSale(name,price); //ERROR
}
}
public static void addSale(String name, double price)
{
customers c= new customers(name,price);
a.add(c);
}
public class customers
{
String name;
double price;
public customers(String name, double price)
{
this.name=name;
this.price=price;
}
}
}
You also have to initialize the kbd variable as:
kbd = new Scanner( System.in );
Please review your code using this suggestion and the others above.
A main method is static and thus has static context. No instance of Question3.class is required for a thread to enter that code block. Your class customers is defined inside of Question3. Because it is an inner class, it has implicit access to the fields and methods inside of the Question3 class, but it requires an instance of Question3 to be able to achieve that behavior. You need to move the code you have now in main(String args[]) into a constructor for the class Question3, and create an instance of Question3 in your main method like so :
public static void main(String args[]) {
Question3 myQuestion3 = new Question3();
}
Alternatively as mentioned by others, you could make your customers class static. This will solve the issue by effectively making customers a top level class, but you will lose the ability to implicitly access the fields and methods of its enclosing type, which is the Question3 class.
First off Great job so far. However, there are a couple of errors that I see in the code.
First you class should be a static class. You are trying to use static methods without a static class.
public static class Question3 {
static ArrayList<customers> a= new ArrayList<customers>();
private static Scanner kbd;
public static void main(String[] args)
{
Also, you need to create your scanner for the user to input an object.
private static Scanner kbd = new Scanner(System.In);
Do these and your code will work perfectly!
You should change the declaration your class customers to solve this issue.
Currently its a non-static inner class. You should change it to static inner class.
public static class customers
Non-static inner classes refers implicitly to the instance of the container class. Here you trying to create new instance of customer class in a static function, you don't have Question3 instance there.
Just change your inner class to a public static class:
public static class customers {
And the error disappears :)
There are two problems in your code.
First , you have to initialize scanner object by providing System.in parameter to it.
Second , while creating customer object you have to follow proper syntax.
Here is the working code:
public class Question3 {
static ArrayList<customers> a= new ArrayList<customers>();
private static Scanner kbd=new Scanner(System.in); // <---- Notice this
public static void main(String[] args)
{
String input="";
double price=1;
String name="";
while(price != 0)
{
System.out.println("Customer Name: ");
name= kbd.nextLine().trim();
System.out.println("Purchase Price: ");
price= Double.parseDouble(kbd.nextLine().trim());
addSale(name,price); //ERROR
}
System.out.println(a);
}
public static void addSale(String name, double price)
{
// customers c= new customers(name,price);
Question3.customers c = new Question3().new customers(name, price); // <---Notice this
a.add(c);
}
public class customers
{
String name;
double price;
public customers(String name, double price)
{
this.name=name;
this.price=price;
}
} }