Get the property from a private variable - java

I created 2 methods. Method1 assigns value to a variable via setter, method2 gets the value of the variable via a getter.
However, when I call method2 the program returns null or null. Only private variables can be used, do not use public or static.
Is there any solution or code example for me? Sorry, I'm a newbie. Thanks very much!
class Info {
private String name;
private int age;
public Info() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class Test {
public static void main(String[] args) {
Test test = new Test();
test.method1();
test.method2();
}
public void method1() {
Info a = new Info();
a.setName("John");
a.setAge(21);
}
public void method2() {
Info a = new Info();
//I want to print Name and Age values from class Info after method1 set value
System.out.println("Name: " + a.getName() + " Age: " + a.getAge());
}
}

The scope of Info a = new Info(); is limited to the method that you have declared it in. Consider making it a field.
public class Test {
private Info a = new Info();
Test test = new Test();
test.method1();
test.method2();
}
public void method1() {
a.setName("John");
a.setAge(21);
}
public void method2() {
System.out.println("Name: "+ a.getName() + " Age: " + a.getAge());
}
}
Alternatively you could create local variables, but pass them between the methods:
In main
Info a = new Info();
Test test = new Test();
test.method1(a);
test.method2(a);
Of course this would require you change you method signatures to
public void method1(Info a) {...}
public void method2(Info a) {...}

A private global variable can only be set by a method that is private.
A method that is private can only be called inside the class it is coded(implemented).
However, inside the class you can mix security declarations levels of variables in code, but to set or get the method used must be as the variable it sets or gets with or without a method return statement.
To set and obtain(get) anything private from calls located outside the class you must use a public method inside the same class to call the private methods or if the calling class is in the same (class package hierarchy) packages hierarchy level and package tree you can use a protected method to call from such an external class but that in the external class must be called by a protected method (potentially)returning to a protected variable.
If there is only the default level "no access security declaration of the class" given (e.g. public protected - nothing stated but "class NamedAClass"), of such a class with the get set then it is similar but more lax security than private using default security level, with default security level , you can only call from a class located in the exact same package as the class with the code to call.

Related

Java Inheritance: Calling a subclass method in a superclass

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.

Java No enclosing instance of type is accessible

there I'm pretty new to Java and have german class and method titles. This Code is meant to give a string output for every class extending "Musiker". I have already looked on SO but my problem is that changing it to static gives an error on the class itself. The main reason why I open a new Question is, that every other class is working as planned. And please don't wonder why the Strings look weird, the Book I copied this from is meant to be humoristic.
public class Proberaum {
public static void main(String[] args) {
try {
Musiker saenger = new Saenger();
Musiker gitarrist = new Gitarrist();
Musiker bassist = new Bassist();
Musiker trompeter = new Trompeter();
Musiker backgroundSaengerin = new BackgroundSaengerin();
machtMusik(saenger, gitarrist, bassist, trompeter, backgroundSaengerin);
} catch(Exception e) {
new Exception().printStackTrace();
}
}
public static void machtMusik(Musiker... gruppe) {
for(Musiker musiker : gruppe) {
musiker.musizieren();
}
}
public class Musiker {
private String name;
private int alter;
private Band band;
public void musizieren() {
System.out.println("OO Mmmmmmmmh, OO Mmmmmmmmh");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAlter() {
return alter;
}
public void setAlter(int alter) {
this.alter = alter;
}
public Band getBand() {
return band;
}
public void setBand(Band band) {
this.band = band;
}
}
public class Band {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Saenger extends Musiker {
#Override
public void musizieren() {
this.singen();
}
public void singen() {
System.out.println("Oh, bäbi, juuuu a mei sannnnscheiiiiin");
}
}
public class BackgroundSaengerin extends Saenger {
}
public class Bassist extends Musiker {
}
public class Gitarrist extends Musiker {
public void musizieren() {
System.out.println("Tschiiiiiingzäääängggggg");
}
}
public class Trompeter extends Musiker {
}
}
Your Saenger class is actually a non-static member of the Proberaum class. Because it's non-static, you actually need to create an instance of Proberaum before you can use any of these classes:
Proberaum proberaumObject = new Proberaum();
Musiker saenger = new proberaumObject.Saenger();
In your case, classes inside classes is probably not what you want to do. If you extract each of your classes into its own file, you should find your problem going away. (If that's not possible for whatever reason, declaring your subclasses as static should work too.)
Like Joe C also mentioned in his answer: the core of the problem is that your classes Saenger, Musiker, etc etc. are all nested classes (nested inside Proberaum), but they are defined as non-static.
In Java, non-static nested classes are called "inner classes". Inner classes have implicit access to their enclosing class members (even private ones), but of course the flipside of this is that there first needs to be an object of that enclosing class for the inner class to reference. That is why the compiler is complaining in your example: you're trying to create an object of class Saenger, which is an inner class of Proberaum, so to create that object it needs to have a reference to an object of type Proberaum. Since you're doing the object creation in the (static) main method, no such object exists.
So, to fix, you have to change your inner classes. Easiest is to declare them all static. Note that you can do this is in addition to be making them public:
public static class Seanger extends Musiker { ...
As also remarked elsewhere however, you really should not put every class in the same file. Learn to work with one class per file, it's the Java Way™.
Instead of declaring the nested classes as static, one can alternatively create objects of nested classes like mentioned below.
Proberaum proberaumObject = new Proberaum();
Musiker saenger = proberaumObject.new Saenger();

Abstract Class and toString() method

I am a little confused on how to set up the TestHomework method so that it prints properly when using the toString() method. Right now when I run the main method it prints "null - 0" but what I would like it to say is "Math - 6". This program is supposed to extend an abstract class. It is supposed to say how many pages there are for homework and for what subject.
public abstract class Homework {
private int pagesToRead;
private String typeHomework;
{
// initialise instance variables
pagesToRead = 0;
typeHomework = "none";
}
public Homework(int pages, String hw) {
this.pagesToRead = pages;
this.typeHomework = hw;
}
public abstract void createAssignment(int p);
public int getPages() {
return pagesToRead;
}
public void setPagesToRead(int p) {
pagesToRead = p;
}
public String getTypeHomework() {
return typeHomework;
}
public void setTypeHomework(String hw) {
typeHomework = hw;
}
}
public class MyMath extends Homework {
private int pagesRead;
private String typeHomework;
public MyMath(int pages, String hw) {
super(pages,hw);
}
public void createAssignment(int p) {
setTypeHomework("Math");
setPagesToRead(p);
}
public String toString() {
return typeHomework + " - " + pagesRead;
}
}
public class TestHomework {
public static void main(String[] args) {
MyMath one = new MyMath(6, "Math");
one.createAssignment(6);
System.out.println(one);
}
}
That's because you are defining the 2 properties (that one of them happen to have the same name as one of the abstract class's) but you are not initializing them, you are initializing those of the abstract class. (So their values is always set to their type's default)
You need to drop those from the MyMath class, & define the toString method in your abstract class: it's the one to be used by default by its inheriting classes.
public abstract class Homework {
private int pagesToRead;
private String typeHomework;
// Same code
// Define the toString here
#Override
public String toString() {
return typeHomework + " - " + pagesToRead;
}
}
public class MyMath extends Homework {
// You don't need to define any extra attributes
public MyMath(int pages, String hw) {
super(pages,hw);
}
public void createAssignment(int p) {
setTypeHomework("Math");
setPagesToRead(p);
}
}
public static void main(String[] args) {
// Calls the constructor of the MyMath class, which in turn
// invokes the constructor of its superclass, the 'Homework' class
MyMath one = new MyMath(6, "Math");
one.createAssignment(6);
// Invokes the toString of the MyMath class. Since it does not have one,
// The toString method of its superclass (Homework) is called.
System.out.println(one);
}
Your derived class has its own typeHomework and pagesRead fields, which are never set (even though the base class happens to have fields with the same names). Therefore, they stay null and 0.
You should delete those fields and use the data from the base class, via the public getter methods.
Why it doesn't work:
Be careful you redeclared the attribute typeHomework of you parent class. Attributes are automatically added to your extending class so you don't have to write them again.
By redeclaring it you confused the compiler, viewing your code in debug shows, that your one object contains your typeHomework twice:
typeHomework = null // The one from the super class
typeHomework = "Math" // The one from your child class
Your method now uses the typeHomework from your super-class therefor the output is null!
pagesRead is 0 because you are setting the pagesToRead of your super-class to 6(not pagesRead!) when calling setPagesToRead(p);.
Some style tips
Use the #Override annotation when overriding methods like this:
#Override
public void createAssignment(int p) {
setTypeHomework("Math");
setPagesToRead(p);
}
It's not really needed but it's good practice (readers of your code know that it overrides something).
When referring to attributes of your class it's also good practice to use the this statement so it's clear, that you're referring to an attribute and not a local variable:
#Override
public String toString() {
return this.typeHomework + " - " + this.pagesRead;
}

How to access a variable which is declared in a method belonging to another Java class?

I have recently started trying my hands at Java and I am stuck at this problem. I have two Java files called Main_file.java and Helper.java. The Helper.java file contains a String variable called the name, which I wish to access form my Mainfile.java and assign to a string variable x. The files look soemthing like this.
Main.java
public class Mainfile{
Helper myhelper =new MyHelper();
public void create_func(){
String x = /* assign the value name from the helper file */;
}
Helper.java
public class Helper{
public void add_name() {
String name = "New_name";
}
}
But this does not seem to work. I am not really sure if the method I am trying is right or wrong. Could somebody please help me? Thank you in advance.
The variable name you create in your Helper class is not class-member but only a member which exists in the method add_name()
If you want a class member you'll have to create it like this:
public class Helper{
String name = "New_name";
}
then you can access it like this:
public class MainFile{
Helper myHelper = new Helper();
public void create_func(){
String x = myHelper.name;
}
}
Many people will say that class-members "have" to be private, so it might be nicer to create getters and setters for the class member:
public class Helper{
private String name = "New_name";
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
}
public class MainFile{
Helper myHelper = new Helper();
public void create_func(){
String x = myHelper.getName();
}
}
You can not directly access a local variable of a method of another class. You can do it by making the method returning the object and access it by calling the method by an object of the class. This is how you can:
public class Mainfile{
Helper myhelper =new Helper();
public void create_func(){
String x = myhelper.add_name();
}
}
public class Helper{
public String add_name(){
String name = "New_name";
return name;
}
}

Java print method won't work in class

I am trying to get the print method in my actor class to print the String that was
built in the toString() method. However I keep getting an error. (invalid method declaration, return type required)
public class actor {
private String name;
private String address;
private int age;
public actor(String name, String address, int age) {
this.name = name;
this.address = address;
this.age = age;
}
public void setName (String name) {
this.name = name;
}
public void setAddress (String address) {
this.address = address;
}
public void setAge (int age) {
this.age = age;
}
public void setFilm () {
}
public String getName () {
return name;
}
public String getAddress () {
return address;
}
public String toString (String name, int age, String address){
return name+" who's "+age+" and lives in "+address;
}
public void print (){
String a = toString();
System.out.println(a);
}
print();
}
I have been trying to get this working for quite a while to no avail.
Here's the two parts to the trouble you're having:
In order to run your program, you have to have a main method.
You have to understand what static and non-static mean.
First, as mentioned by others, you can't just have a method run because it's declared and defined in your class. You actually need to have it called, directly or indirectly, by the main method. The main method is written like this:
public static void main(String[] args) {
// Do Stuff
}
Secondly, you have to understand what static and non-static mean. Which means, you have to understand the difference between classes and objects.
Classes are blue prints. They describe how to build a particular type of object, what properties (or fields) it has, and what methods can be called off of it.
Objects are the actual instances of objects declared by a class. Think of it like this: A class is like the blueprint for a smart car. The objects are the smart cars themselves.
So now, static vs non-static.
Static means that it belongs to the class (the blueprint), rather than to the actual object. The main method, you will notice, is static. It belongs to the class it's declared in, rather than to any instance objects. This means, outside of itself, the main method knows only about the class that it's in, and any other static methods or objects in that class. Things that are not static belong to the actual objects created from the class -- and the main method will know nothing about these actual objects, unless they are created inside of the main method itself.
So, something like this won't work:
public class StuffDoer {
public void doStuff {
System.out.println("Doing Stuff");
}
public static void main(String[] args) {
doStuff(); // Won't work!
// You can't call a non-static, instance method in a static method!
}
}
Instead, you can first create a new instance object of your class inside of the main method, and then call the non-static instance method off of your instance object:
public class StuffDoer {
public void doStuff {
System.out.println("Doing Stuff");
}
public static void main(String[] args) {
new StuffDoer().doStuff(); // This will work,
// because now you have an instance to call the instance method off of.
}
}
This is usually not as good of a choice, but will also work:
public class StuffDoer {
public static void doStuff { //Now, we make this method static
System.out.println("Doing Stuff");
}
public static void main(String[] args) {
doStuff(); // This will work now, because this method is static.
}
}
You're trying to call print() from your class body. Instead, write a main method and print from there:
public static void main(String[] args) {
Actor a = new Actor(...);
a.print();
}
You should have a main function to let the program run, like:
remove the last line print() then create a new file call Main.java, write
package yourPackage // put them into the same package,
main class can call actor class
public class Main{
public static void main(String[] args) {
actor a = new actor();
a.print();
}
}
Why do you need print() method ? You can just use -
Actor a = new Actor(...);
System.out.println(a);
This will implicitly execute toString() method
Ideally you should do this way. Since purpose of toString() method is to give meaningful String representation of an object.
actor actorObj = new actor();
System.out.println(actorObj );
Calling print(); on class body is invalid. Remove following method call.
print();
First off, you should be calling the print() method from somewhere else (main for example). Even with that, you have an error: You are calling the toString() method (with no arguments, which is taken from the Object class). Just remove the arguments from your toString method to override that one. It can see the fields of its own class anyways. With this, you can do something like the following, and take advantage of Java's default toString call:
public static void main(String[] args) {
System.out.println(new Actor("Bob", "410 Main Street", 42);
}
Java does not allow you to call a method in the body of a class as you are attempting to do with the line of code that is print(); You must put the call to print inside another method. For example
public static void main(String[] args) {
actor a = new actor();
a.print();
}
By adding a main method to your class and using the constructor for Actor in that method you create an Author object. On this Author object call print().
TJamesBoone has given a really good answer to give you an understanding of what is really happening. Follow his answer and it will do as you want.
https://stackoverflow.com/a/19981973/1785341
here is your code.. compile and run..
public class actor {
private String name;
private String address;
private int age;
public actor(String name, String address, int age) {
this.name = name;
this.address = address;
this.age = age;
}
public void setName (String name) {
this.name = name;
}
public void setAddress (String address) {
this.address = address;
}
public void setAge (int age) {
this.age = age;
}
public void setFilm () {
}
public String getName () {
return name;
}
public String getAddress () {
return address;
}
#Override
public String toString (){
return name+" who's "+age+" and lives in "+address;
}
public void print (){
//String a = toString();
System.out.println(this);
}
public static void main( String[] args )
{
actor a = new actor( "xyz","abc",20 );
a.print();
}
}
Simple as it is....
Once you write toString() method in a class then do another method called print() and call inside the print() method toString() method.
public void print()
{
System.out.println(toString());
}

Categories