1.

Write a class “Programmer”. Give some properties and methods to it and show how you will access them in the main method by creating object(s) of this class.

Answer»

The following is the example code.

Java Code for Custom Class

import java.util.*;

class Programmer {

private int age;
private String name;

Programmer() {

}

Programmer(int age, String name) {
this.age = age;
this.name = name;
}

void setAge(int age) {
this.age = age;
}

void setName(String name) {
this.name = name;
}

int getAge() {
return age;
}

String getName() {
return name;
}

public void codes() {
System.out.println(this.name + " writes codes");
}

public void drinksCoffee() {
System.out.println(this.name + " drinks coffee and can then convert exponential complexity codes to polynomial");
}
}

class Main {
public static void main(String args[]) {
// Your code goes here
Programmer p1 = new Programmer(22,"Guneet");
p1.codes();
p1.drinksCoffee();
}

Sample Output

Guneet writes codes
Guneet drinks coffee and can then convert exponential complexity codes to polynomial.

  • Some things you should keep in mind: The properties must usually be set private and we should have getter and setter methods to access and modify them. This is good OOPS practice. Also, always create a default constructor as when we create a parameterized constructor, Java removes its own default constructor and the object creation without passing the parameters to the constructor would not be possible.



Discussion

No Comment Found