How to create an object from a subclass in Java - java

So I have this class:
public class parent {
private int id;
private int row;
public parent(int id,int row) {
this.id=id;
this.row=row
}
}
and then I have this class which extends parent
public class son extends parent {
public son(int id,int row) {
super(id,son);
}
}
the question is how do i create an object for class son.Do I have to call it like this:
son x=new son(int id,int row);
I am really confused.

Yep, you're just about spot on! To be absolutely clear, you wouldn't use the type of id and row in calling the constructor, you would just give values of that type.
So this is wrong:
son x = new son(int 5, int 6); //Incorrect
And this is correct:
son x = new son(5, 6); //Correct
You can also pass variables of the correct type, like this:
int id = 5;
int row = 6;
son x = new son(id, row);
Also, I just noticed that you wrote:
public class parent {
private int id;
private id row;
//....
instead of
public class parent {
private int id;
private int row; //Note the change id --> int here
//....
If this was a typo, don't worry about it. Otherwise you may have a conceptual misunderstanding. id isn't a type, but int is. So we can't declare row as an id, but we can declare it as an int. Unlike in C and friends you can't create synonyms of types with a typedef, so you're stuck with the base types (int, boolean, etc).
Since it appears that you're new to Java, the convention is for classes to have Pronoun Case (capitalized first letter of each word) names. Thus it would be better style to use the following formatting for your classes:
public class Parent {
private int id;
private int row;
public Parent(int id,int row) {
this.id=id;
this.row=row
}
}
public class Son extends Parent {
public Son(int id,int row) {
super(id,son);
}
}
public class ThisClassHasManyWordsInItAndItShouldBeFormattedLikeThis {
//.....
}
Which then makes the construction:
Son x = new Son(5,6);
Once you've constructed a Parent object like Parent p = new Parent(4,5);, there's no way to change p into a Son. It's not possible. However, you can copy p into a new Son, and you can make some modifications to the classes to make it easier to make these copies:
public class Parent {
private int id;
private int row;
public Parent(int id,int row) {
this.id=id;
this.row=row
}
public int getId() {
return id;
}
public int getRow() {
return row;
}
}
public class Son extends Parent {
public Son(int id,int row) {
super(id,son);
}
public Son(Parent p) {
super(p.getId(), p.getRow());
}
}
Now we can create a Parent, and copy it into a new Son:
Parent p = new Parent(4,5);
Son s = new Son(p); //will have id of 4 and row of 5
It's worth noting that while all this is well and good for learning how class extension works, you're not actually using it quite correctly. By saying Son extends Parent, you're saying that Son is a type of Parent, which isn't true in the elementary school model of a Family. A better way to model a family would probably be:
public class Person {
private Person mother;
private Person father;
public Person(Person mother, Person father) {
this.mother = mother;
this.father = father;
}
}
If you're still looking for a way to include class extension, then Man and Woman make sense as extensions of class Person, because a Man is a type of Person. (i.e. All men are people, not all people are men).
public class Person {
private Man father;
private Woman mother;
public Person(Man father, Woman mother) {
this.father = father;
this.mother = mother;
}
}
public class Man extends Person {
public Man(Man father, Woman mother) {
super(father, mother);
}
}
public class Woman extends Person {
public Woman(Man father, Woman mother) {
super(father, mother);
}
}

Related

How do I code an ID number whose first digit changes depending on the subclass created?

I'm working on an assignment in my computer science course and I am stuck on a certain part where I'm asked to generate ID numbers with specific rules and I am not sure how to go about it. Here are the exact instructions:
Phase 3: Item
Items are used in the system as a superclass for both Flight and Payloads. All Items are issued a unique identifier
within the system, for tracking. The rules for IDs are as follows:
• All ID numbers are 9 digits long
• The first digit changes based on the type of item
o Commercial Flights start with 1
o Industrial Flights start with 2
o Persons start with 3
o Cargo starts with 4
• The last 8 digits begin at 0 and increase by one for each item created
o That is, the first Item created will end in 0, the next will end in 1, and so on. Example: creating a
Commercial flight would be issued id 100000000, then a Person would be issued 300000001
respectively.
Consider where to add code in the hierarchy (Item, and its subclasses) to generate and store these IDs.
This is the code I tried, the class Item and its constructor:
public abstract class Item {
protected int id;
public Item() {
int commercialID = 100000000;
int industrialID = 200000000;
if( this instanceof Commercial){
id = commercialID;
commercialID++;
} else if (this instanceof Industrial) {
id = industrialID;
industrialID++;
}
}
I also tried making the id variable static but that changed nothing
Here are Commercial and Industrial too
public class Industrial extends Flight{
public Industrial(){
super();
}
}
public class Commercial extends Flight{
public Commercial(){
super();
}
}
Thank you.
You Item class is you top (abstract) class with 2 (abstract) subclasses: Payload and Flight
Item must define an abstract method that will return the offset in each concrete subclass.
Payload has 2 subclasses: Cargo and Person
Flight has 2 subclasses: CommercialFlight and IndustrialFlight
You must store the last generated id in a static field and increase it by one before to append it to the offset defined for each concrete class.
See example below:
public abstract class Item {
protected int id;
protected static int lastGeneratedId = 0;
protected Item() {
lastGeneratedId++;
this.id = 100000000 * getIdPrefix() + lastGeneratedId;
System.out.println(toString());
}
protected abstract int getIdPrefix();
#Override
public String toString() {
return "New " + getClass().getName() + " created with id " + id;
}
}
The two abstract sublasses:
Flight
public abstract class Flight extends Item {
public Flight() {
super();
}
}
Payload
public abstract class Payload extends Item {
public Payload() {
super();
}
}
And the concrete classes:
CommercialFlight
public class CommercialFlight extends Flight {
public CommercialFlight() {
super();
}
#Override
protected int getIdPrefix() {
return 1;
}
}
IndustrialFlight
public class IndustrialFlight extends Flight {
public IndustrialFlight() {
super();
}
#Override
protected int getIdPrefix() {
return 2;
}
}
Person
public class Person extends Payload {
public Person() {
super();
}
#Override
protected int getIdPrefix() {
return 3;
}
}
Cargo
public class Cargo extends Payload {
public Cargo() {
super();
}
#Override
protected int getIdPrefix() {
return 4;
}
}
And a class to test all this:
public class ItemTester {
public static void main(String[] args) {
new Cargo();
new IndustrialFlight();
new Cargo();
new CommercialFlight();
new IndustrialFlight();
new Person();
new Person();
}
}

Dimanic Model in Java

I'm making a contacts app, this is my model.
public class Contact {
private RelationShip relationShip;
public static class RelationShip {
private Friend friend;
private Enemie enemie;
private Family family;
private class Family {
private Brother brother;
private Sister sister;
}
}
}
I want to create it you can do it the way suiguiente.
RelationShip realation = new RelationShip(RelationShip.Friend);
Contact contact = new Contact(realation);
I want to establish the kind of relationship in a variable. Really do not know how to ask the question. an example would be something like this:
layout.setOrientation (LinearLayout.VERTICAL);
LinearLayout.VERTICAL is a constant or an enumerate. Take a look here for example.
To achieve the same behavior in your code set those values as constants (usually int).
public static class RelationShip {
public static final int FRIEND = 0;
public static final int ENEMIE = 1;
public static final int FAMILY = 2;
...
}
public class Contact {
private int relationshipType;
...
public void setRelationShipType(int relationShip) {
}
public boolean areWeFriends() {
if (relationshipType==Relationship.FRIEND)
return true;
else
return false;
}
...
}
You can then set the relationship setRelationShipType(Relationship.FRIEND). Or check if the relationship of Contact HerryPotter is a friend with HarryPotter.areWeFriends()
EDIT:
Actually the correct way is indeed the one suggested by alfasin: using enumerates.
public enum RelationShip {
FRIEND, ENEMIE, FAMILY
}
public class Contact {
private RelationShip relationshipType;
public void setRelationShipType(RelationShip relationShip) {
...
}
public boolean areWeFriends() {
if (relationshipType==Relationship.FRIEND)
return true;
else
return false;
}
}

How to convert an object from class to superclass

I have to model breakwater that controls permissions in certain coast. My solution implements a class "Ship" and classes "OilShip", "FishingShip" and "CarriageShip", I used inheritance and made
public class OilShip extends Ship{
...
}
public class FishingShip extends Ship{
...
}
public class CarriageShip extends Ship{
...
}
In another class I have Ship ship=new Ship(...); and I'd like to somehow make an Oilship into Ship, i.e.
public Class Abcd{
Ship ship;
public Abcd(OilShip oship){
ship=oship; //*************
}
}
There seems to be a problem with the code, please tell me.
Make sure you call the superclass' constructor inside your subclasses' constructors.
This solution works fine for me:
public class Ship {
private String name;
private int weight;
public Ship(String name, int weight) {
this.name = name;
this.weight = weight;
}
}
class OilShip extends Ship {
private int oilCapacity;
public OilShip(int oilCapacity, String name, int weight) {
super(name, weight);
this.oilCapacity = oilCapacity;
}
}
class FishingShip extends Ship {
private int fisherMen;
public FishingShip(int fisherMen, String name, int weight) {
super(name, weight);
this.fisherMen = fisherMen;
}
}
class CarriageShip extends Ship {
private int containers;
public CarriageShip(int containers, String name, int weight) {
super(name, weight);
this.containers = containers;
}
}
As mentioned before, Java-classes should always be given a name, where the first character is in UPPERCASE and the same with each new word --> CamelCase
You don't need different constructors. The awesome thing behind using inheritance here, is, that no matter what subclass from the superclass "Ship" you put into your constructor in "abcd", it will be accepted:
public class Abcd {
private Ship ship;
public Abcd(Ship ship){
this.ship = ship;
}
}

Passing object as parameter for constructor

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.

How to extend or implement classes? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Picture to show task:
First I am sorry, for my bad to for expressing my mind.
I have such a task, I don't need that you do it for me.
Vehicle is parent class for Sedan (Cause Sedan class is String type).
How to extend or implement Vehicle class with universal class?
I forgot to ask my teacher, but maybe you will know, what means striped pointer to Owner class, and what is that: has a?
P.S. If you need code that I have written already, I will show you.
So this is my parent Vehicle class:
public class Vehicle {
private int vehicleNumber;
protected int fuelTankSize;
protected int maxSpeed;
protected Owner owner;
//1
public Vehicle(int vehicleNumber){
this.vehicleNumber = vehicleNumber;
}
//2
public Vehicle(int vehicleNumber, int fuelTankSize) {
this.vehicleNumber = vehicleNumber;
this.fuelTankSize = fuelTankSize;
}
//3
public Vehicle(int vehicleNumber, int fuelTankSize, int maxSpeed) {
this.vehicleNumber = vehicleNumber;
this.fuelTankSize = fuelTankSize;
this.maxSpeed = maxSpeed;
}
//4
public Vehicle(int vehicleNumber, int fuelTankSize, int maxSpeed, Owner owner) {
this.vehicleNumber = vehicleNumber;
this.fuelTankSize = fuelTankSize;
this.maxSpeed = maxSpeed;
this.owner = owner;
}
//1
public int getMaxSpeed() {
return maxSpeed;
}
public void setMaxSpeed (int maxSpeed){
this.maxSpeed = maxSpeed;
}
//2
protected int getFuelTankSize(){
return fuelTankSize;
}
protected void setFuelTankSize (int fuelTankSize){
this.fuelTankSize = fuelTankSize;
}
//3
public Owner getOwner(){
return owner;
}
public void setOwner (Owner owner){
this.owner = owner;
}
}
child Sedan with:
public class Sedan extends Vehicle {
private String registrationIndex;{
}
public Sedan (int vehicleNumber, int fuelTankSize, int maxSpeed, String registrationIndex, Owner owner) {
super(vehicleNumber, fuelTankSize, maxSpeed, owner);
this.setRegistrationIndex (registrationIndex);
}
public String getRegistrationIndex (){
return registrationIndex;
}
public void setRegistrationIndex (String registrationIndex) {
this.registrationIndex = registrationIndex;
}
}
second Universal child without an error:
public class Universal extends Vehicle {
private int trunkSize;
public Universal (int vehicleNumber, int fuelTankSize, int maxSpeed, int trunkSize, Owner owner) {
super(vehicleNumber, fuelTankSize, maxSpeed, owner);
this.setTrunkSize (trunkSize);
}
public int getTrunkSize() {
return trunkSize;
}
public void setTrunkSize(int trunkSize) {
this.trunkSize = trunkSize;
}
public void printDescription() {
super.printDescription();
System.out.println("Universalo bagažinės tūris: " + getTrunkSize() + "l.");
}
}
and some misterious (to me) Owner class:
public class Owner {
public String firstName;
public String lastName;
public Owner (String firstName){
this.firstName = firstName;
}
public Owner (String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
}
added VechileTest for testing:
public class VehicleTest {
public static void main(String[] args) {
Vehicle vehicleInf = new Vehicle (1, 45, 260);
Universal universalInf = new Universal(2, 50, 220, 70);
Sedan sedanInf = new Sedan (3, 40, 180, "AVA 123");
vehicleInf.printDescription();
universalInf.printDescription();
sedanInf.printDescription();
}
}
Well, 1st of all I recommend you read a good tutorial / explanation of UML class diagrams, like this here for example.
After you know the basics, it should be easy to translate that into Java code.
I'll give you the code for the Universal class and a start for your Vehicle. The rest you'll have to do on your own.
The class Universal:
public class Universal extends Vehicle {
private int trunkSize;
public int getTrunkSize() {
return this.trunkSize;
}
public void setTrunkSize(int trunkSize) {
this.trunkSize = trunkSize;
}
}
As you can see the first block inside a class box refers to the variables. The - and + indicates the visibility (private for -, public for +).
The next block is about the methods, specifying visibility, return type, method name and parameters (type and name).
The arrow between Universal and Vehicle indicates a inheritance relationship (see in code that Universal extends Vehicle).
So all in all the diagram is a construction plan for your classes; at least for the static part, meaning the relationships and state they can have.
The start of class Vehicle:
public class Vehicle {
private int vehicleNumber;
// the rest here ...
}
Edit:
Well, now that I see your code, you seem to have a few misconceptions:
The Sedan type is not from type String, it is from type Sedan (which extends Vehicle). Just the new member variable in the Sedan type is of type String, does not matter.
To your 1st question: The Vehicle class is the base (parent) class of Sedan. You do not to do anything with it, inheritance is expressed from the child towards the parent, not the other way around. Vehicle should usually be declared abstract (as you cannot create an instance of a generic Vehicle), but this is not in the diagram.
To your 2nd question: The has a relationship is just this. It expressed that one class has another class as it's member (which is redundantely expressed inside the class diagram already), so nothing to do for that.
Additionally your code has a few issues:
I do not see any constructors declared in Vehicle class, those 4 can go.
Your Sedan has a superflous pair of {} after declaration of your registrationIndex variable.
Since your Vehicle has no default constructor, you must call this constructor from your Sedan class (or remove the constructors from Vehicle.
Your Universal class calls the Vehicle constructor with the trunkSize while the Vehicle constructor expects the vehicleNumber there.
Your Vehicle class doesn't have a parameterless constructor, which means that Universal and Sedan must explicitly call one of them (super(...);). You're doing this in Universal (albeit incorrectly as you're passing the trunk size instead of the vehicle number expected by Vehicle's constructor) but not in Sedan.
As for the second question: The two major relations in OOP are is a and has a. The difference can be easily explained like this:
A Sedan is a vehicle
A vehicle has an owner
is a means it inherits some properties of something else, has a means that it has a reference to something else.

Categories