I have super class called pojo. I have a subclass called ExtendPojo.
pojo.java
package com.java.pojo;
public class pojo {
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 long getNumber() {
return number;
}
public void setNumber(long number) {
this.number = number;
}
public String toString() {
return "pojo [name=" + name + ", age=" + age + ", number=" + number + "]";
}
private String name;
private int age;
private long number;
}
ExtendPojo.java
package com.java.pojo;
public class ExtendPojo extends pojo{
public static void main(String[] args) {
pojo obj = new pojo();
obj.setName("santhosh");
ExtendPojo exObj = new ExtendPojo();
exObj.setName("mahesh");//It is not overriding
System.out.println(obj.getName());//it prints santhosh.
}
public void setName(String name){
super.setName(name);
}
}
You are creating two independent objects.
First you create an object and name it santhosh. This object is referenced by the obj variable.
pojo obj = new pojo();
obj.setName("santhosh");
Then you create a second object, which is referenced by the exObj variable.
ExtendPojo exObj = new ExtendPojo();
It doesn't have a name yet, since it's a new object and you haven't assigned the name. You then give it a name.
exObj.setName("mahesh");//It is not overriding
Now you print the name of the first object, which hasn't changed.
System.out.println(obj.getName());//it prints santhosh.
The code is doing exactly what you asked it to do.
If you intended the two variables to reference the same object, you'd do this:
ExtendPojo exObj = new ExtendPojo();
pojo obj = exObj ;//Same object, new variable, different type
obj.setName("santhosh");
exObj.setName("mahesh");//It is working now
System.out.println(obj.getName());//it prints mahesh.
I have gone through the Inheritance and method overriding concepts and clarified my doubts :)
public class ExtendPojo extends Pojo{
public static void main(String[] args) {
Pojo obj = new Pojo();
obj.setName("santhosh");
Pojo obj1 = new ExtendPojo();
obj1.setName("mahesh");//It is overriding now
System.out.println(obj1.getName());//it prints mahesh.
}
}
Related
I have a subclass "OnlineCourse". It´s a subclass of "Course". I want to return "OnlineCourse" in my class "Student". But instead of "EIST" I get back null.
Here´s what I have:
public class Student {
public String matriculationNumber;
public String name;
public int age;
public Course study() {
TODO 4: Comment the code below back in
Change the Course type to OnlineCourse and set its
title to "EIST"
return the new course
// Course course = new Course();
// course.join();
// return course;
Course EIST = new OnlineCourse();
EIST.join();
return EIST;
}
}
Subclass that extends course and should be initiated as the return type for "EIST" in the class Student.
public class OnlineCourse extends Course{
public URL livestreamUrl;
public Course join() {
System.out.println("joined the course " + title);
return this;
}
public Course drop() {
System.out.println("dropped out of the course" + title);
return this;
}
}
public abstract class Course {
public String title;
public String description;
public LocalDate examDate;
public List<Lecture> lectures;
public abstract Course join();
public abstract Course drop();
}
Main- Method:
public class Main {
public static void main(String[] args) {
var student = new Student();
student.matriculationNumber = "01234567";
student.name = "Joe Doe";
student.age = 42;
student.study();
}
}
I think you're saying the course title is showing as null. In which case you have to set it for it to print. I'd also note that where you have EIST - that's just a variable name, it can be anything and doesn't have any affect on any values.
If I were to guess, I think you'd want something like this -
public static void main(String[] args) {
var student = new Student();
student.matriculationNumber = "01234567";
student.name = "Joe Doe";
student.age = 42;
student.study("EIST");
}
And in Course, you'd want a setter method for the title like, -
public setCourseTitle(String title) {
this.title = title;
}
And in Student
public Course study(String courseTitle) {
Course EISTCourse = new OnlineCourse();
EISTCourse.setCourseTitle(courseTitle);
EISTCourse.join();
return EISTCourse;
}
Is there some way to print different data from an ArrayList containing different objects?
For example, I created two basic classes:
import java.util.*;
class Furniture{
String name;
int weight;
Furniture(String name, int weight){
this.name = name;
this.weight = weight;
}
String getName(){
return name;
}
int getWeight(){
return weight;
}
}
}
class Resident{
String name;
Resident(String name){
this.name = name;
}
String getName(){
return name;
}
}
Then I stored them in an ArrayList<Object> and wanted to print the names, by using declared below printArrayList method:
public class Main{
public static <E> void printArrayList(ArrayList<E> arrayToPrint){
for(E element : arrayToPrint){
try{
System.out.println(element.getName());
}
catch(Exception e){
System.out.println("Exception e: " + e);
}
}
}
public static void main(String []args){
Furniture sofa = new Furniture("Sofa", 5);
Resident mike = new Resident("Mike");
ArrayList<Object> arrayList = new ArrayList<>();
arrayList.add(sofa);
arrayList.add(mike);
printArrayList(arrayList);
}
Now, I know that not all objects can have a variable name or declared get method, therefore I tried to exclude these cases by try/catch.
I also tried to exclude it by using fe:
if(elements.getName() == null)
Still, same results.
You don't need to use a parameterized type. Rather introduce a specific interface (for example NameAware) that exposes the getName() method that your classes with implement. In this way you could rely on a common type.
public interface NameAware{
String getName();
}
public class Resident implements NameAware{
...
public String getName(){
return name;
}
}
public class Furniture implements NameAware{
...
public String getName(){
return name;
}
}
And define your method as :
public static void printArrayList(ArrayList<NameAware> arrayToPrint) {
for (NameAware element : arrayToPrint) {
try {
System.out.println(element.getName());
} catch (Exception e) {
System.out.println("Exception e: " + e);
}
}
}
Note that you should change your actual code from :
ArrayList<Object> arrayList = new ArrayList<>();
to
ArrayList<NameAware> arrayList = new ArrayList<>();
The best practice would be to declare an interface with the getName method, and have both Furniture and Resident implement it.
public interface Namable {
public String getName();
}
Then, use a List<Namable> instead of a List<Object>:
Furniture sofa = new Furniture("Sofa", 5);
Resident mike = new Resident("Mike");
List<Namable> arrayList = new ArrayList<>();
arrayList.add(sofa);
arrayList.add(mike);
for (Namable n : arrayList) {
System.out.println(n.getName());
}
I need to write some code which is as follows:
public class Person {
public static final String NAME;
public Person(String NAME) {
this.NAME = NAME;
}
}
public class Player extends Person {
public Peter(String name) {
super(name);
}
}
It's basically, I want the Player class to have a static final field called NAME, that is being initialized somewhere else, without manually writing in every class public static final String NAME = "Peter".
Is it possible?
As it has been said in the comments, you have poorly declared your NAME variable. In actuality, you don't want it to be static (although you can keep the final modifier, if you want). Your code should, instead, be something along the lines of:
public class Person {
public final String name;
public Person(String name) {
this.name = name;
}
}
public class Player extends Person {
public Player(String name) {
super(name);
}
}
Every person should have their own name; you don't want all objects to be sharing one NAME field
I do not know if I fully understand your question, but I think you have a few mistakes in your code. Like declare name of person as static variable, because static variables are often used as variables for the entire class, and if you changed the name, would change the name to the entire class, not for one instance. Also final is wrong, because you cannot set final variable.
I would do something like this:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return String.format("Person: %s", this.getName());
}
}
public class Player extends Person{
public Player(String name) {
super(name);
}
public String toString(){
return String.format("Player: %s", this.getName());
}
}
public class Match {
private Player player_one;
private Player player_two;
public Match(Player player_one, Player player_two) {
this.player_one = player_one;
this.player_two = player_two;
}
public Player getPlayer_one() {
return player_one;
}
public void setPlayer_one(Player player_one) {
this.player_one = player_one;
}
public Player getPlayer_two() {
return player_two;
}
public void setPlayer_two(Player player_two) {
this.player_two = player_two;
}
#Override
public String toString() {
return String.format("Right now are playing %s VS %s",player_one.getName(), player_two.getName());
}
}
public class PlayerTest {
public static void main(String[] args) {
Player peter = new Player("Peter");
Player anna = new Player("Anna");
Match tennisMatch = new Match(peter, anna);
System.out.println(tennisMatch.toString());
}
}
I static field (variable) only exists once for all instances of your class. Therefore what you try does not work by design.
What value would you expect the field to have after you created three different instances of this class using different parameters?
A final variable cannot be changed once it got initialized. For static variables this happens before the first instance of the class is even constructed. At the moment the constructor is executed the field cannot be changed anymore.
To initialize a static final variable you have to assign a value directly at the definition using the = operator or you have to do it in a static initializer which looks like this:
public class FooBar {
public static final String STATIC_VARIABLE;
static {
STATIC_VARIABLE = "Hello World";
}
}
You can make it like this:
private static final NAME;
public Player(String name){
NAME = name;
}
A final varible can be initialized once only if it wasn't initialized yet.
So in this way the constructor is helping you make it.
I have a couple to class in which I'm getting and setting a few things and then finally calling it in my main method. But when I call my class in the main method it just gives me the object instead of name,address and age. I know this structure is very complicated but I want to keep this structure because later on I will be adding a lot of things to this. It would be AMAZING if someone could tell me how to do this. I would really appreciate this. Below is my code for all my classes
This is my first class
public class methodOne
{
public String getName()
{
String name = "UserOne";
return name;
}
public int getAge()
{
int age = 17;
return age;
}
public String getAddress()
{
String address = "United States";
return address;
}
}
This is my second class
public class methodTwo
{
String name;
String address;
int age;
public methodTwo(methodOne objectOne)
{
name=objectOne.getName();
address=objectOne.getAddress();
age=objectOne.getAge();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
This is my third class
public class methodThree {
private methodTwo methodTwoInMethodThree;
private methodOne methodOneInMethodThree;
public methodThree()
{
this.methodOneInMethodThree = new methodOne();
this.methodTwoInMethodThree = new methodTwo(methodOneInMethodThree);
}
public methodTwo getMethodTwoInMethodThree() {
return methodTwoInMethodThree;
}
public void setMethodTwoInMethodThree(methodTwo methodTwoInMethodThree) {
this.methodTwoInMethodThree = methodTwoInMethodThree;
}
}
This is my fourth class which is the method maker
public class methodMaker {
public methodThree brandNewFunction(methodTwo object)
{
methodThree thirdMethod = new methodThree();
thirdMethod.setMethodTwoInMethodThree(object);
return thirdMethod;
}
}
This is my main class which calls methodMaker. What I want to achieve is that when I print the value it should print the name,address and age but instead it just prints trial.methodThree#4de5ed7b
public class mainClass {
public static void main(String args[])
{
methodMaker makerOfMethods = new methodMaker();
methodOne one = new methodOne();
methodTwo object = new methodTwo(one);
System.out.println(makerOfMethods.brandNewFunction(object).toString());
}
}
What you need to do is to override the default implementation of the .toString() method in the objects you want to print out:
#Override
public String toString()
{
return "Name: " + this.name;
}
EDIT:
I do not know exactly where you are printing, and you naming convention doesn't really help out, but from what I am understanding, you would need to implement it in all of you classes since they all seem to be related to each other.
So, in your methodOne class (can also be applied to methodTwo):
#Override
public String toString()
{
return "Name: " + this.name + " Age: " + this.age + " Address: + " this.address;
}
In your methodThree class:
private methodTwo methodTwoInMethodThree;
private methodOne methodOneInMethodThree;
#Override
public String toString()
{
StringBulder sb = new StringBuilder();
if(this.methodTwoInMethodThree != null)
{
sb.append("Method 2:").append(methodTwoInMethodThree.toString());
}
if(methodOneInMethodThree != null)
{
sb.append("Method 1:").append(methodOneInMethodThree.toString());
}
return sb.toString();
}
When you call
MyClass myObject = new MyClass();
System.out.println(myObject);
Implicitly , java calls instead
System.out.println(myObject.toString());
So, if in MyClass, you override toString(), then whatever your toString method returns is what's gonna be printed.
Side note: are you confusing classes and methods? Methods are functions in your classes, classes are wrappers around a bunch of attributes and methods. Your naming is confusing.
try this code:
public class methodTwo
{
String name;
String address;
int age;
public methodTwo(methodOne objectOne)
{
name=objectOne.getName();
address=objectOne.getAddress();
age=objectOne.getAge();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return name+" "+address+" "+age;
}
}
Are you printing the object using println()?
From the docs, println():
calls at first String.valueOf(x) to get the printed object's string value
This string value is obtained from the object's toString() method, which:
returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object
So if you want to print anything other than this you have to override the toString() method in your object and return a string containing whatever you want.
Just google "override tostring java" and you will see a ton of examples.
I have a POJO class with one of String array property having size is 2. But I am creating the object of Person class with passing array of size 5. It's not showing any exception. Why?
package classObject;
import java.util.Arrays;
public class Person implements Cloneable {
String name;
int age;
String[] skills = new String[2];
Person() {
}
Person(String name, int age, String[] skills) {
this.name = name;
this.age = age;
System.out.println("this.skills.length " + this.skills.length);
System.out.println("skills.length " + skills.length);
this.skills = skills;
System.out.println("Got array is " + Arrays.asList(this.skills));
System.out.println("length of arrays is " + this.skills.length);
}
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;
}
#Override
protected Person clone() throws CloneNotSupportedException {
return (Person) super.clone();
}
public String[] getSkills() {
return skills;
}
public void setSkills(String[] skills) {
this.skills = skills;
}
}
// Creating the Object of Person Class
public class classObject {
/* Way to create an object of any class */
public static void main(String args[]) {
try {
// Define the array with len 5
String[] skills = new String[5];
skills[0] = "Java";
skills[1] = "PHP";
skills[2] = "JDBC";
skills[3] = "ORACLE";
skills[4] = "SQL";
// Passing the array
Person objPerson = new Person("Mohit", 27, skills);
System.out.println("Size is " + objPerson.skills.length);
} catch (Exception e) {
e.printStackTrace();
}
}
}
String[] is an object, although it doesn't look like it. So when you declare.
String[] skills = new String[2];
You're actually declaring a pointer to a new object, which is a String[] object, with a size of 2.
Then you come a long with a new String[] object of size 5, and your reference now points to that.
This process has nothing to do with the original object, because when you state:
this.skills = skills;
you're not effecting the object that this.skills points to; only the pointer itself. The String[2] object will have no pointers referring to it, and the garbage collector will likely come a long and destroy it.
You're pointing the class variable to the argument passed in the function... Check its' size in the constructor and if it's not 2, then throw IllegalArgumentExepction.