I have 3 classes. These classes are Class1, Parent and Child. I'm having some trouble to figure out how to write a constructor I need for my Child class.
public Class1
{
private String firstName;
private String lastName;
public Class1()
{
firstName="";
lastName="";
}
public Class1(String firstName, String lastName)
{
this.firstName=firstName;
this.lastName=lastName;
}
//Methods and stuff
}
public Parent
{
private Class1 class1;
private double number;
public Parent();
{
class1=new Class1();
number=0;
}
public Parent(Class1 c, double n)
{
Class1=c;
number=n;
}
//Methods and stuff
}
public Child extends Parent
{
private String string;
private Boolean boolean;
public Child(Class1 class1, double n, String s, Boolean b)
{
//Don't know how to get the Class1 part to work
//Don't know how to get the double to work
string=s;
boolean=b;
//Methods and stuff
}
I don't know how to write the code so that I can get my constructor to take the arguments like this:
new Child(new Class1("String", "String"), 10, "String", true);
I hope this helps clarify what my problem is.
Create Child constructor as
public Child(Class1 objClass1, double number, string str, boolean bool){
super(objClass1,number);
this.str=str;
this.bool=bool;
}
Create Parent constructor as
public Parent(Class1 objClass1, double number){
this.objClass1=objClass1;
this.number=number;
}
and you can called the child constructor as
Child objChild=new Child(new Class1(str1,str2),number,str,bool);
I'm not going to give you the code, because you've not given us enough information, but let's assume you've got a class structure like..
public class Parent
{
private String field;
public Parent(String field) {
this.field = field;
}
}
public class Child extends Parent {
private String field;
public Child(String field)
{
this.field = field;
}
}
What you can do is specify a constructor in your Child class that passes the variables up the inheritance chain, to your Parent class:
public Child(String field, String parentField)
{
super(parentField); // Calls the parent class.
this(field);
}
So what you've done there, is passed the parentField up to the Parent class, and you've called your existing constructor that accepts a single String parameter.
Apply this principle to your code and you'll get it in minutes.
Related
Error
public Cat (String nm, int legs, String sd, String col)
For this constructor I got following compiler error:
constructor Animal in class Animal cannot be applied to given types;
required: String, int
found: no arguments
reason: actual and formal arguments lists differ in length
Code
The parent class is right below the child class.
public class Cat extends Animal {
private String sound;
private String colour;
public Cat (String nm, int legs, String sd, String col) {
nm = super.getName();
legs = super.getNumOfLegs();
sound = sd;
colour = col;
}
public abstract class Animal {
protected String name;
protected int numOfLegs;
public Animal() {
}
public Animal(String nm, int legs) {
name = nm;
numOfLegs = legs;
}
public String getName() {
return name;
}
public int getNumOfLegs() {
return numOfLegs;
}
public abstract String display();
}
}
Should the parent abstract class be placed in a separate file instead?
I've tried that initially but it returned way more errors than it did now, especially from the abstract method display().
What is causing the error?
There are a couple of things you should change.
First of all, it is the best way to put the super class into a separate file. If you want to keep in one file you need drag it out of the Cat class and remove the scope (not public or private). But this is not a good coding style for a super class.
The next thing is, with the name/nm and legs/numOfLegs. Either you call the super constructor and provide the two variables (see my example) or you use name = nm; and numOfLegs = legs;
You should also reconsider if the name and numOfLegs varialbes need to be protected or if is fine to provide the access only through the getter.
If the number of legs, the name, sound and color will not change you could also make them immutable (with the key word final, e.g. private final String sound). If not you can make them accessible with a setter.
Finally you need to implement the abstract method in the Cat class...
public class Cat extends Animal {
private String sound;
private String colour;
public Cat(String nm, int legs, String sd, String col) {
super(nm, legs);
sound = sd;
colour = col;
}
#Override
public String display() {
return null;
}
}
abstract class Animal {
protected String name;
protected int numOfLegs;
public Animal(String nm, int legs) {
name = nm;
numOfLegs = legs;
}
public String getName() {
return name;
}
public int getNumOfLegs() {
return numOfLegs;
}
public abstract String display();
}
lets suppose i have this Parent Class
public abstract class Parent
{
private String name;
private String surname;
public Parent(String name, String surname)
{
this.name=name;
this.surname=surname;
}
and lets suppose i have many child classes like that and everyone of them has it's own different attributes to add to their parent ones
public class Child extends Parent
{
private String favColor;
public Child(String name,String surname,String favColor)
{
super(name,surname);
this.favColor=favColor;
}
public getFavColor()
{
return this.favColor
}
now i'm in this situation
Parent parent = new Child(name,surname,favColor);
and what i want to do is calling the method getFavColor() on the object parent like this
parent.getFavColor();
is this working? i guess not, so how could i be able to call such method on such object? i thought of declaring abstract getters of childs attributes on the superclass but that doesn't sound very prone to the open/closed principle, because in a time in future when i will want to add more child-like classes i will have to declare every getters of the child attributes in the superclass which is not supposed to know about his childrens.
thank you very much :)
In this case you can't call the getFavColor() method. The method is defined only in Child class and your reference is Parent. For this, is necessary the definition the getFavColor() method in Parent Class.
You would create a abstract method fav() in Parent class:
public abstract class Parent
{
private String name;
private String surname;
public Parent(String name, String surname)
{
this.name=name;
this.surname=surname;
}
public abstract String fav();
}
So called:
parent.fav();
Thus, you can implement the method in different ways on your children, such as:
public class Child extends Parent
{
private String favColor;
public Child(String name,String surname,String favColor)
{
super(name,surname);
this.favColor=favColor;
}
public String fav()
{
return this.favColor;
}
}
And:
public class SecondChild extends Parent
{
private String favSport;
public Child(String name,String surname,String favColor)
{
super(name,surname);
this.favColor=favColor;
}
public String fav()
{
return this.favSport;
}
}
Use this only if the signature of methods are equals in all children (in your case, if all children methods return a String).
You would need an abstract method to do that. Your parent is already abstract so that's good. It would go something like this:
public abstract class Parent {
private String name;
private String surname;
public Parent(String name, String surname) {
this.name = name;
this.surname = surname;
}
public void showFavColor() {
system.print.ln(this.getFavColor());
}
abstract string getFavColor();
}
public class Child extends Parent {
private String favColor;
public Child(String name, String surname, String favColor) {
super(name, surname);
this.favColor = favColor;
}
#Override
public String getFavColor() {
return this.favColor
}
}
Every child of the parent MUST extends the abstract function. Since the function is technically declared in the parent, it is accessible from it.
This means, you could do
Parent parent = new Child(name,surname,favColor);
parent.showFavColor();
I have a class that has a variable of type Name.
public class Holder {
private Name name;
private int snumber;
The Name class has two strings called first and last that are assigned values by setter methods. I would like to send over the strings from the Name class to name in the Holder class, but I'm having trouble doing so. I think I've taken a step in the right direction by doing this
public class Holder {
private Name name;
private int snumber;
public void setName(){
name = new Name();
name.getFirst();
name.getLast();
}
but I can't say that I really know what the correct approach is. I also tried name.setFirst(getFirst) but that doesn't work. Any ideas would be appreciated.
The same way you would if the class wasn't nested.
Your setName() method should take a parameter (maybe 2, first and last) and then invoke the name.setFirstName(), name.setLastName() methods.
Right now, your setName() method isn't doing anything.
E.G:
public class Holder
{
private Name name;
private int snumber;
public Holder()
{
this.name = new Name();
}
public void setName(String firstName, String lastName)
{
this.name.setFirst(firstName);
this.name.setLAst(lastName);
}
}
Here is a good article explaining the relationship between Java inner and outer classes:
https://www.tutorialspoint.com/java/java_innerclasses.htm
class Outer_Demo {
// private variable of the outer class
private int num = 175;
// inner class
public class Inner_Demo {
public int getNum() {
System.out.println("This is the getnum method of the inner class");
return num;
}
}
}
public class My_class2 {
public static void main(String args[]) {
// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();
// Instantiating the inner class
Outer_Demo.Inner_Demo inner = outer.new Inner_Demo();
System.out.println(inner.getNum());
}
}
Note that the example creates instances of both "Outer_Demo" AND "Inner_Demo (outer.new Inner_Demo();).
Ok, so I figured something out that works.
public class Holder {
private int snumber;
private Name name;
public void setName(Name n){
name=n;
}
public Name getName(){
return name;
}
I need help fixing my code with the basic concepts listed above. To save from clutter, I took a screen shot of the directions here: https://imgur.com/SdiotUi
However, when I run my code it isn't working. I know there are a lot of errors but I'm having trouble fixing them even though I've spent the past few hours googling the correct way to do this.
When I create the first constructors I am not sure if I am assigning the name and legs correctly, I am having trouble returning "true", I get an error calling the parent class taking one argument, and I don't think I am overriding the abstract class correctly.
My code:
public class Animal1 {
private String animalName;
public int numberOfLegs;
public Animal1(String name){
name = animalName;
name = "John";
}
public Animal1(String name, int legs){
name = animalName;
legs = numberOfLegs;
name = "Jack";
legs = 4;
}
public String getName(){
return animalName;
}
public int getLegs(){
return numberOfLegs;
}
public void isAMammal(){
return true;
}
public void isCarnivorous(){
return true;
}
public abstract class getHello{
}
}
public class Cat1 extends Animal1{
public Cat1(String name){
Animal1.name;
}
public abstract class getHello{
return "Meow";
}
}
public class Dog1 extends Animal1{
public Dog1(String name){
Animal1.name;
}
public abstract class getHello{
return "Woof";
}
}
public abstract class Animal1 { // If you want to have an abstract method, declare the class as abstract
private final String animalName;
private final int numberOfLegs; // better of using private and make it final since it's not going to change.
public Animal1(final String name, final int legs){ //better making the input parameters final since they are not supposed to be changed
//name = animalName;
//legs = numberOfLegs;//it assigned the field to an input parameter. that will take no effect on the object created.
animalName = name;
numberOfLegs = legs;
}
public String getName(){
return animalName;
}
public int getLegs(){
return numberOfLegs;
}
public boolean isAnimal(){ //boolean function needs a return type too!!
return true;
}
public boolean isCarnivorous(){
return true;
}
public abstract String getHello(); // an abstract method has same requirement as a normal method besides the abstract modifier. it will need a return type. And it ends with a semicolon
}
public class Cat1 extends Animal1{
public Cat1(final String name){
super(name, 4); //use super to call parent constructor
}
#Override
public String getHello(){
return "Meow";
}
}
public class Dog1 extends Animal1{
public Dog1(final String name){
super(name, 4);
}
#Override
public String getHello(){
return "Woof";
}
}
First, it looks like a few of your methods are declared as classes. I assume you wanted to make them abstract methods. They need to be changed to:
public abstract String getHello();
Note that abstract methods can only be declared in an abstract class. So, you need to redefine Animal1 as abstract.
public abstract class Animal1
Next, when you implement the abstract method, you define it as
public String getHello()
If you are using an IDE like Eclipse it will automatically offer to generate this method.
Finally, when using your constructor in your child classes like Cat1, you are trying to set "name" as if it was a static variable and bypassing the constructor you already had set for Animal1. The best way to correct this is to change the constructor in Cat1 and Dog1 to call the super constructor.
public Cat1(String name){
super(name);
}
The book I am reading says I cant, but my program proves otherwise. For example the code below compiles well, even though i try to access the private properties of the parent class. Then I can freely print them. Can anyone tell me if the book is wrong, or am I doing something wrong?
class Asset
{
private int Id;
private String type;
public int getId()
{
return Id;
}
public String getType()
{
return type;
}
public void setId(int Id)
{
this.Id=Id;
}
public void setType(String type)
{
this.type=type;
}
public void printDescription()
{
System.out.println("Asset Id: "+Id);
System.out.println("Asst type: "+ type);
}
}
class BankAccount extends Asset
{
private String bankName;
private int accountNumber;
private float balance;
public String getBankName()
{
return bankName;
}
public int getAccountNumber()
{
return accountNumber;
}
public float getBalance()
{
return balance;
}
public void setBankName(String bankName)
{
this.bankName=bankName;
}
public void setAccountNumber(int accountNumber)
{
this.accountNumber=accountNumber;
}
public void setBalance(float balance)
{
this.balance=balance;
}
public void printDescriptionnn()
{
System.out.println("The Bank name is: "+ bankName);
System.out.println("Account number: "+ accountNumber);
System.out.println("Your balance is: "+ balance);
}
}
public class AssetTest
{
public static void main(String[] args)
{
BankAccount llogari= new BankAccount();
Scanner input = new Scanner(System.in);
Scanner sinput= new Scanner(System.in);
System.out.print("Type the ID of your asset: ");
llogari.setId(input.nextInt());
System.out.print("Type the type of your asset: ");
llogari.setType(sinput.nextLine());
System.out.print("Give the bank name: ");
llogari.setBankName(sinput.nextLine());
System.out.print("Type the Account Number: ");
llogari.setAccountNumber(input.nextInt());
System.out.print("Type your balance: ");
llogari.setBalance(input.nextFloat());
llogari.printDescription();
llogari.printDescriptionnn();
}
}`
You can access them through public or protected getters but you can't access the private properties directly. In your example, you're using the public setters to modify the property. You can access them through public method !
So to answer you question, private members are not inherited by subclasses. Alternatively, you can have protected members that are inherited by subclasses.
EDIT
From Java Language Specificiation
Members of a class that are declared private are not inherited by subclasses of that class.
Only members of a class that are declared protected or public are inherited by subclasses declared in a package other than the one in which the class is declared.
Because you're not directly modifying the parent class's elements. You're calling public functions that modify the private elements, which is completely valid.
A subclass does not have direct access to the private members of a super class. It only has direct access to the public and protected members.
In this context, direct access means: super.member
If the super class implements protected or public accessor or mutator methods, then you may be able to indirectly access them. Indirect access would look something like: super.getMember() or super.doSomething().
Any subclass does not have permission to direct access of the private members of a super class. It can access to the public and protected members.