Write a class encapsulating the convept of a file, assuming a file has only a si
ID: 3548239 • Letter: W
Question
Write a class encapsulating the convept of a file, assuming a file has only a single attribute: the name of the file. Include a constructor, the accessors and mutators, and methods toString and equals. Also, code a method returning the extension of the file, that is, the letters after the last dot in the file (for instance, if the file name is Test.java, then the method should return java); if there is no dot in the file name, then the method should return "unknown extension." Write a client class to test all the methods in your class.
Explanation / Answer
// save as file.java and run
// private string extension; this variable not required in your code.
public class file
{
private String name;
private static int count=0;
file()
{
}
file(String n)
{
name = n;
count++;
}
public void setFilename(String n)
{
name = n;
count++;
}
public String getFilename()
{
return name;
}
public String toString()
{
return "File name is "+name;
}
public boolean equals(file a)
{
if((this.getFilename()).equals(a.getFilename())) return true;
else
return false;
}
public String getExtension()
{
int k = name.indexOf('.');
if(k>0)
return name.substring(k+1);
else
return "Unkown Extension";
}
public static void main(String[] args)
{
file f1 = new file("king.jpg");
file f2 = new file();
f2.setFilename("matlab.m");
System.out.println("file f2 name is " + f2.getFilename());
System.out.println(f2);
System.out.println(""+ f1.getFilename()+ " Equals? " + f2.getFilename() + " " + f1.equals(f2));
file f3 = new file("hihihi");
System.out.println(f3 + " " + f3.getExtension());
file f4 = new file("king.jpg");
System.out.println(f1.getFilename()+ "Equals? " + f4.getFilename()+ " " + f1.equals(f4));
System.out.println("No of File Objects Till Created "+ f1.count);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.