If I have this structure in Java:
class A{
private string Name;
public string getName() {
return this.Name;
}
class B extends A{
private string Name;
public string getName(){
return this.Name;
}
}
I create an object of class B and I want to access through that object the inherited method getName(). How can I do this? Is the method getName() from A overridden by B method?
I want to access through that object the inherited method getName().
How can I do this?
From a context outside of B, you cannot.
From within B, you can do
super.getName();
if its super type declares a getName() method.
In your example the method A#getName() is inherited and overriden in B.
Note that private fields are not inherited.
Note that fields with the same name may hide inherited fields.
Change your structure to:
class A{
protected string Name;
public string getName() {
return this.Name;
}
}
class B extends A{
public B(String Name) {
this.Name = Name;
}
}
Then you can do:
B myB = new B();
myB.Name = "Susie";
System.out.println(myB.getName()); //Prints Susie
You should place a setter for Name in class A. Also, String needs to be capitalized in Java.
You could just define class B the following way
class B extends A{
// no repetition of name
public String getName(){
//you don't need to access A.name directly just
//use you A.getName() since it's your superclass
//you use super, this way A.name can be private
String localVarName = super.getName();
// do class B changes to Name
return localVarName;
}
/*
*rest of B class you may want to add
*/
}
Related
Beginner question - how do I avoid repeating code in sibling classes, where each has its own different version of the same field?
See example below: can I somehow move the getName() method (as well as far more complex methods) to the parent class?
public abstract class Car {
public abstract String getName();
}
public class PassengerCar extends Car {
private String name = "Passenger Car";
#Override
public String getName() { return name; }
}
public class CoalCar extends Car {
private String name = "Coal Car";
#Override
public String getName() { return name; }
}
You can, for example: create a constructor in the parent class which takes a name, and specify that name in the constructor of the child classes:
abstract class Car {
private String name;
public Car(String name) {
this.name = name;
}
public String getName() { return name; }
}
class PassengerCar extends Car {
public PassengerCar() {
super("Passenger Car");
}
}
class CoalCar extends Car {
public CoalCar() {
super("Coal Car");
}
}
Which then can be used like this:
Car passenger = new PassengerCar();
System.out.println(passenger.getName());
This prints out:
Passenger Car
#Mark's answer is the solution, but let me add a bit of background to it.
Simple rule of thumb: if you want something that all subclasses have in common, place it into the parent class.
What do you have?
a field called name used by all subclasses (it doesn't matter that the values are different, see below),
a getter called getName() used by all subclasses,
an initial value "Passenger Car" for all PassengerCar instances,
an initial value "Coal Car" for all CoalCar instances.
So, the name field and the getName() method go into Car, and the different initial values for that field go into the constructors of PassengerCar and CoalCar.
I'm writing program that demonstrates the use of inheritance and I have created a variable using the super() keyword. I am now trying to place the value of that variable into a new method that calls it so that I can call that method in my main method to use its value within other classes.
Here is the relevant code:
Food class (super class)
public class Food {
//field that stores the name of the food
public String name;
//constructor that takes the name of the food as an argument
public Food(String name){
this.name = name;
}
public String getName() {
return name;
}
}
Meat class (sub class with super keyword)
public class Meat extends Food
{
public Meat() {
super("Meat");
}
public String getName() {
return //get super() value??;
}
}
Main class
public class Main {
public static void main(String[] args)
{
Wolf wolfExample = new Wolf();
Meat meatExample = new Meat();
System.out.println("************Wolf\"************");
System.out.println("Wolves eat " + meatExample.getName());
}
}
Any help is appreciated, thanks.
You could just do
public String getName() {
return super.getName();
}
Although you don't even need to override the method in the first place, because you declared the field name in super class to be public which means it can be accessed from anywhere.
Don't override public String getName() in Meat class.
The inheritance allows to inherit public and protected methods of Food in all subclasses of Food, therefore in Meat.
So Meat which IS a Food has by definition this behavior :
public String getName() {
return name;
}
which returns the name field stored in the parent class.
Overriding a method in subclass to write exactly the same code than in the parent method is useless and should not be done because it is misleading. A person which reads the code will wonder : why having overrided the method in the child class if it does the same thing than the parent class ?
Edit
Besides, if you want to access a field declared in a super class from a subclass, you should :
provide a public getter in the super class if the field is private. Here :
public String getName() {
return name;
}
use directly the field in the subclass if the field has the protected modifier.
As a general rule, you should avoid declaring instance fields with the modifier public because by default properties of a object should be protected and you should provide methods to modify the field only if needed.
So, declaring your Food class like that seems more suitable :
public class Food {
//field that stores the name of the food
private String name;
//constructor that takes the name of the food as an argument
public Food(String name){
this.name = name;
}
public String getName() {
return name;
}
}
In your Meat class, imagine you would like to add an additional information in the string returned by getName(), you could override it and why not using the field from the super class :
public class Meat extends Food {
public Meat() {
super("Meat");
}
#Override
public String getName() {
return super.getName + "(but don't abuse it)";
}
}
Here overriding the method is helpful because the behavior of the method in the child class differs from which one definedin the super class.
Simply write:
public String getName() {
return name;
}
This is because when searching for a variable named name, Java proceeds in this order:
Local variables (none)
Current class's fields (none)
Superclass's fields (found)
Super-super-class's fields (etc.)
However, you didn't need to override getName() in the subclass in the first place. If you didn't define it, then it would inherit the superclass's implementation, which corresponds exactly to the behavior you wanted. Thus you were doing extra work for no gain.
The other answers showed you how to do what you want.
But you should't do it (in real life projects)!
The most important principle in object oriented programming is encapsulation (aka information hiding). This means that the internal structure of a class should not be visible or accessible to the outside.
Therefore all member variables should be private.
Also you should avoid setter/getter methods since they just redirect the access. (except the class is a DTO without any logic of its own).
Since food class has the method getName declared as public do
public String getName() {
return super.getName();
}
i am a 1st year IT Student taking OOP...
i have this abstract parent Class...
public abstract class Person{
private String Name;
protected Person(){
setName("xxxxxxxx");
}
public abstract String getName();
public abstract void setName(String name);
}
and this is its child class...
public class PetOwner extends Person{
private boolean hasKids;
private boolean hasAllergies;
public PetOwner(){
setName("xxxx");
setAllergies(true);
setKids(true);
}
public PetOwner(String name, boolean a, boolean k){
setName(name);
setKids(k);
setAllergies(a);
}
public String getName(){return Name;}
public void setName(String n){ Name = n;}
public boolean getAllergies(){return hasAllergies;}
public void setAllergies(boolean a){hasAllergies = a;}
public boolean getKids(){return hasKids;}
public boolean setKids(boolean k){hasKids = k;}
}
when i compile the child class it has errors that the "Name" is a private variable of Person.
my question is how can i access the private variables of the parent class in my child class by not changing it to public or protected??
Don't define your name setters and getters as abstract if you dont want to change "String Name" access modifier to public or protected. Do this:
public String getName(){return Name;}
public void setName(String name){Name = name;}
In your child class; Do this:
public String getName(){return super.getName();}
public void setName(String n){ super.setName(n);}
On Another Note: You're not assigning value to Name in your super class constructor. Write Name = xxxx instead because you are calling a setter that is abstract!
private members are private to the entity they are defined in. protected are private to the entity they are defined and to their subclasses. public means no protection/accessible everywhere.
Roughly, if you define an attribute in a given entity then almost all the management of it should be defined at the same place. It means that if a Person has a name then the method setName and getName should be defined in Person. They could be redefined in subclasses but they should at least be defined in Person.
Think about it: why would you like (in common cases) every PetOwner or ClergyMan to define setName? They will probably both do exactly the same; so factoring the definition in Person is the right way.
public class A {
String name;
public A() {
this("My Name");
}
}
I came across this line of code from an ebook (Dietel_Java_HowTo) that I'm reading and also tried reading some article (javaworld/constructor) about constructor. They have used snippets of code like what I have on top. It's giving me an undefined String error.
Is the this keyword referring to the variable name, if so why am I getting the error. I'm new in java please bear.
By using this("My Name"); from inside a constructor, you are invoking another overloaded constructor of the Class A, but, you haven't define a constructor which accepts String argument. So compiler complains it.
Possible corrected version
public class A{
String name;
public A(){
this("My Name");
}
public A(String name){
this.name = name;
}
}
Because there is no constructor of A that takes a String(also string name should be String name) as parameter. To correct it:
public class A{
String name;
public A(){
this("My Name");
}
public A(String name){
this.name = name;
}
}
Also, your program does not compile, public class A(){} is invalid.
That is because you are trying to call the constructor with the this("My Name") call, but the constructor does not take any parameters. Try defining another constructor as shown below:
public class A() {
string name;
public A() {
this("My Name");
}
public A(String a) {
this.name = name;
}
}
Have a look at the java tutorial on constructors to get a good idea.
In java by using this(parameters) keyword you can call the overloaded constructor. In your case you are facing compile time error due to you are trying to calling overloaded constructor which belongs to static polymorphism concept so its give compile time error. So you will have to need to add new constructor with single string parameter and your class would be change in to below class:
public class A{
String name;
public A(){
this("My Name");
}
public A(String name){
//your logic
}
}
How would I initialise the string name and the instance variable named right in the superclass to true from the HighRights class?
So if high is an instance of HighRights then
high.getSecret();
should return the secret is 42
public class SecurityRights {
private boolean right;
private boolean canreadSecret;
String SECRET="the secret is 42";
public SecurityRights(boolean r) {
right =r;
if (r) canreadSecret=true; else canreadSecret=false;
}
boolean getRight(){
return right;
}
boolean canReadSecret(){
return canreadSecret;
}
String getSecret(){
if (canreadSecret) return SECRET; else return "access denied";
}
}
public class HighRights extends SecurityRights
{
private String name;
public HighRights(String n){
}
public String getName(){
return name;
}
public static void main(String[] a){
HighRights s= new HighRights("Lisa");
System.out.print(s.getName() +" "+s.getSecret());
}
}
You call the Parent's constructor by calling super().
So in your case
super(booleanValue);
Usually, this would be placed in the first line of your child constructor.
You could also change the privacy level from private to protected, and then you would be able to access it in all child objects.
You can either make a method just like you did when calling getSecret() and intialize and boolean and string.
OR
you can use the super methods. Here is some more info. You would pretty much be making a constructor for the class, but since an instance of the class is never really created only a Child of that instance, you need to use the super command to make constructors.
The inherited class would have the following implementation:-
class HighRights extends SecurityRights
{
private String name;
public HighRights(boolean r,String n){
super(r);
this.name = n;
}
public String getName(){
return name;
}
public static void main(String[] a){
HighRights s= new HighRights(false,"Lisa");
System.out.print(s.getName() +" "+s.getSecret());
}
}
In this implementation, the super keyword is used. super keyword is used when you need to call the superclass's constructor from the constructor of the subclass. Since you needed to access the right variable of SecurityRights from the constructor of HighRights, you could access it by using the super keyword. More information can be found at oracle's manual.
Also, you gave an argument in the constructor of SecurityRights but you didn't assign it to any variable. Please avoid these mistakes.